#!/usr/bin/python

"""
tuxpaint-savedir.py

Uses the 'wxWidgets' module to display a graphical user interface (GUI)
which asks the user who they are.  It then uses that choice
to determine what directory Tux Paint should save its files in
(via the "--savedir" command-line option)

Bill Kendrick
bill@newbreedsoftware.com
http://www.tuxpaint.org/

Friendly 'mkdir()' by Trent Mick, 2001.Oct.18
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82465

2005.Feb.10 - 2011.Dec.14 (v3)
"""

import wx
import os
import sys

# File containing a list of names and corresponding paths to folders
# (directories) that Tux Paint should save in, when the name is
# supplied. Blank lines are ignored.
# i.e.:
"""
John Smith
F:/users/john

Jane Doe
F:/users/jdoe

Teacher
C:/tuxpaint/
"""
USERS_FILE='users.txt'

# Folder (directory) that all of the ones listed in the file are under (OPTIONAL)
# (e.g., "F:/users/", then the USERS_FILE could just list the rest of the
# path after that)
BASEDIR=""

# Command to execute, and its location
if (sys.platform == "win32" or wx.Platform == "__WXMSW__" or "__WXMSW__" in wx.PlatformInfo):
  # Windows typical
  CMD_DIR='C:/Program Files/TuxPaint/'
  CMD='TuxPaint.exe'
else:
  # Assuming Linux and other Unix-likes, with system-installed Tux Paint
  CMD_DIR='/tmp/usr/bin/'
  CMD='tuxpaint'

# Whether to try and make the folders (directories) ourself  (0=no, 1=yes)
MAKE_DIR=1

LIST=wx.NewId()
LAUNCH=wx.NewId()
QUIT=wx.NewId()


class frame_tuxpaint_launcher(wx.Frame):
    def __init__(self):
        self.frame = wx.Frame.__init__(self, None, -1, "Tux Paint Launcher (v3)")
	
        self.list_users = wx.ListBox(self, LIST, (0, 0), (-1, 120))
	""" FIXME: There's got to be a way to get this to fill the space; maybe http://docs.wxwidgets.org/2.8/wx_sizeroverview.html ? -bjk 2011.12.14 """

        self.list_users.Bind(wx.EVT_KEY_DOWN, self.onKeyPress)

	try:
          file = open(USERS_FILE)
        except(IOError), e:
          self.error = wx.MessageBox("Error. Cannot open '%s': '%s'" % (USERS_FILE, e), "Tux Paint Launcher", wx.ICON_EXCLAMATION)
          sys.exit()
        done = 0
	while done == 0:
          print "a"
          line_name = '\n'
          while done == 0 and line_name == '\n':
              print "a1"
              line_name = file.readline()
              print "line_name = %s" % line_name
              if line_name == '':
                  done = 1

          if done == 0:
              print "b"
              line_dir = '\n'
              while line_dir == '\n':
                  print "b1"
                  line_dir = file.readline()
                  print "line_dir = %s" % line_dir
                  if line_dir == '':
                      self.error = wx.MessageBox("Unexpected end of file after '%s' in '%s'" % (line_name.strip(), USERS_FILE), "Tux Paint Launcher", wx.ICON_EXCLAMATION)
                      sys.exit()

          line_name = (line_name.replace('\n', '')).replace('\r', '').strip()
          line_dir = (line_dir.replace('\n', '')).replace('\r', '').strip()

          """ FIXME If there is a duplicate name, with a different directory, append a "(2)", etc. after it -bjk 2011.12.14 """
          """ FIXME If there is a duplicate name with a duplicate directory, ignore it -bjk 2011.12.14 """
	  
          self.list_users.Append(line_name, line_dir)
	file.close()

        self.button_launch = wx.Button(self, LAUNCH, "Launch!")
        self.button_launch.Bind(wx.EVT_KEY_DOWN, self.onKeyPress)
	wx.EVT_BUTTON(self, LAUNCH, self.cb_launch)
        self.button_launch.SetBackgroundColour("#44FF44")
	
        self.button_quit = wx.Button(self, QUIT, "Quit")
        self.button_quit.Bind(wx.EVT_KEY_DOWN, self.onKeyPress)
	wx.EVT_BUTTON(self, QUIT, self.cb_quit)
        self.button_quit.SetBackgroundColour("#FF4444")
	
        row = wx.BoxSizer(wx.VERTICAL)
        row.Add(self.list_users, 0, wx.ALIGN_CENTER)
        col = wx.BoxSizer(wx.HORIZONTAL)
        col.Add(self.button_launch, 1, wx.EXPAND)
        col.Add(self.button_quit, 1, wx.EXPAND)

	row.Add(col, 0, wx.ALIGN_CENTER)

        self.SetSizer(row)
        """ FIXME: How to get ESC to work without being focused on the list or a button? -bjk 2011.12.14 """

    def onKeyPress(self, event):
        keycode = event.GetKeyCode()
        if keycode == wx.WXK_RETURN or keycode == wx.WXK_NUMPAD_ENTER:
            self.cb_launch(event)
        elif keycode == wx.WXK_ESCAPE:
            self.cb_quit(event)
        else:
            event.Skip()

    def cb_quit(self, event):
        self.Destroy()

    def cb_launch(self, event):
    	if self.list_users.GetSelection() != -1:
            DIR = BASEDIR + self.list_users.GetClientData(self.list_users.GetSelection())
            if MAKE_DIR == 1:
                _mkdir(DIR)

            try:
                os.chdir(CMD_DIR)
            except(OSError),e:
                wx.MessageBox("Cannot change to '%s': '%s'" % (CMD_DIR, e), "Tux Paint Launcher", wx.ICON_EXCLAMATION)
                sys.exit()

            print os.spawnl(os.P_NOWAIT, CMD, "./tuxpaint", "--savedir", '"' + DIR + '"')
            """ FIXME: Check for error """
            self.Destroy()

def _mkdir(newdir):
    """works the way a good mkdir should :)
        - already exists, silently complete
        - regular file in the way, raise an exception
        - parent directory(ies) does not exist, make them as well
    """
    if os.path.isdir(newdir):
        pass
    elif os.path.isfile(newdir):
        wx.MessageBox("A file with the same name as the desired directory, '%s', already exists" % newdir, "Tux Paint Launcher", wx.ICON_EXCLAMATION)
        sys.exit()
    else:
        head, tail = os.path.split(newdir)
        if head and not os.path.isdir(head):
            _mkdir(head)
            print "_mkdir %s" % repr(newdir)
        if tail:
            os.mkdir(newdir)
            """ FIXME: Check for error """


app = wx.PySimpleApp()
frame = frame_tuxpaint_launcher()
frame.Show(1)
app.MainLoop()

