Пример #1
0
    def connect_to_harvest(self):
        '''
        connect to harvest and get data, set the current state and save the config
        '''
        #check harvest status
        if not self.check_harvest_up():
            return

        #set preference fields data
        self.set_prefs()

        if not self.uri or not self.username or not self.password:
            self.preferences_window.show()
            self.preferences_window.present()

            self.running = False
            return self.not_connected()

        try:
            self.harvest = Harvest(self.uri, self.username, self.password)
        except HarvestError as e:
            self.running = False
            self.attention = "Unable to Connect to Harvest!"
            self.set_message_text("Unable to Connect to Harvest\r\n%s" % e)
            self.warning_message(self.timetracker_window, "Error Connecting!\r\n%s" % e)
            return self.not_connected()
        except Exception as e:
            #catch all other exceptions
            self.running = False
            self.attention = "ERROR: %s" % e
            self.set_message_text("Error\r\n%s" % e)
            raise e

        #by this time no error means valid login, so lets save it to config
        self.save_config()
        self.set_message_text("%s Logged In" % self.username)

        self.preferences_window.hide()
        self.refresh_and_show()

        #all should be fine by now, return true
        return True
Пример #2
0
                          outputFile=logFile,
                          target='javadoc')
    print('OK')


# Create installer
strVersion = UpdateVersion.getVersionName()
print("Creating installer for OpenNI " + strVersion + " " + plat)
finalDir = "Final"
if not os.path.isdir(finalDir):
    os.mkdir(finalDir)

if plat == 'Android':
    build_android()
    outputDir = 'OpenNI-Android-' + strVersion
    harvest = Harvest('..', outputDir, 'Arm', 'Android')
    harvest.run()

    finalFile = finalDir + '/' + outputDir + ".tar"
    print('Creating archive ' + finalFile)
    subprocess.check_call(['tar', '-cf', finalFile, outputDir])

elif platform.system() == 'Windows':
    import win32con, pywintypes, win32api, platform

    (bits, linkage) = platform.architecture()
    matchObject = re.search('64', bits)
    is_64_bit_machine = matchObject is not None

    if is_64_bit_machine:
        MSVC_KEY = (win32con.HKEY_LOCAL_MACHINE,
Пример #3
0
class uiLogic(uiBuilder, uiCreator, logicFunctions):
    def __init__(self,*args, **kwargs):
        super(uiLogic, self).__init__(*args, **kwargs)
        #print 'logic __init__'
        #get all the widgets from the glade ui file
        if self.builder_build(widget_list_dict={}, *args, **kwargs):
            #initialize application
            #run before_init to setup callbacks and other junk that may be needed later on
            self.before_init()

            #run the meat of the setup, the application is actually ran from the callback via _run_application()
            self.init()

            #setup any other callbacks and whatnot, this is after all other callback have been connected inside init
            self.after_init()

    def callback(self, *args, **kwargs): #executed after init, lets us inject interrupts
        '''
        execution order:
        logic __init__
            signals before init
            init
            signals after init
        signal helpers __init__
        signals __init__
        logic callback
            logic _run_application
                checking harvest up
        signal helpers callback
        signals callback
        '''
        #print 'logic callback'
        def _handle_callback(*args):
            return self._run_application()

        return kwargs.get("function")( lambda *args, **kwargs: _handle_callback(*args, **kwargs) )

    def quit_gracefully(self): #after all those callbacks and stuff, this function works like a charm, successfully injected interrupts
        print 'quitting'

    def _run_application(self):
        #print 'logic _run_application'
        #call functions to start up app from here
        self.load_config()

        self.set_status_icon()

        self.connect_to_harvest()

        self.center_windows(self.timetracker_window, self.preferences_window)

        self.start_elapsed_timer()
		
        if sys.platform != "win32":
            self._status_button = StatusButton()
            self._notifier = Notifier('TimeTracker', gtk.STOCK_DIALOG_INFO, self._status_button)
			
        self.about_dialog.set_logo(gtk.gdk.pixbuf_new_from_file(media_path + "logo.svg"))

        return self

    def check_harvest_up(self):
        #print 'checking harvest up'
        if HarvestStatus().get() == "down":
            self.warning_message(self.timetracker_window, "Harvest Is Down")
            self.attention = "Harvest is Down!"
            return self.not_connected()
        return True

    def refresh_comboboxes(self):
        if self.project_combobox_handler:
            self.project_combobox.handler_block(self.project_combobox_handler)

        self.create_liststore(self.project_combobox, self.projects, self.current_selected_project_idx)

        if self.project_combobox_handler:
            self.project_combobox.handler_unblock(self.project_combobox_handler)

        #repopulate the tasks comboboxes, because they can be different for each project
        if self.current_selected_project_id and self.current_selected_task_idx > -1:
            if self.task_combobox_handler:
                self.task_combobox.handler_block(self.task_combobox_handler)
            self.create_liststore(self.task_combobox, self.tasks[self.current_selected_project_id], self.current_selected_task_idx)
            if self.task_combobox_handler:
                self.task_combobox.handler_unblock(self.task_combobox_handler)

        elif self.current_selected_task_idx > -1:#no current project running, just select the first entry
            if self.task_combobox_handler:
                self.task_combobox.handler_block(self.task_combobox_handler)
            self.create_liststore(self.task_combobox, {}, self.current_selected_task_idx, True, "Select Project First") #select default None option
            if self.task_combobox_handler:
                self.task_combobox.handler_unblock(self.task_combobox_handler)


        self.set_comboboxes(self.project_combobox, self.current_selected_project_id)
        self.set_comboboxes(self.task_combobox, self.current_selected_task_id)

    def not_connected(self):
        self.preferences_window.show()
        self.preferences_window.present()

        if not self.attention:
            self.attention = "Not Connected to Harvest!"
        else:#append any previous message
            self.attention = "Not Connected to Harvest!\r\n%s" % self.attention

        #self.warning_message(self.timetracker_window, self.attention)

        return

    def set_entries(self):
        if not self.harvest:
            return self.not_connected()

        #get data from harvest
        data = self.harvest.get_today()

        self._setup_current_data(data)

        self.attention = None #remove attention state, everything should be fine by now

        if not self.running:
            self.statusbar.push(0, "Stopped")

    def connect_to_harvest(self):
        '''
        connect to harvest and get data, set the current state and save the config
        '''
        #check harvest status
        if not self.check_harvest_up():
            return

        #set preference fields data
        self.set_prefs()

        if not self.uri or not self.username or not self.password:
            self.preferences_window.show()
            self.preferences_window.present()

            self.running = False
            return self.not_connected()

        try:
            self.harvest = Harvest(self.uri, self.username, self.password)
        except HarvestError as e:
            self.running = False
            self.attention = "Unable to Connect to Harvest!"
            self.set_message_text("Unable to Connect to Harvest\r\n%s" % e)
            self.warning_message(self.timetracker_window, "Error Connecting!\r\n%s" % e)
            return self.not_connected()
        except Exception as e:
            #catch all other exceptions
            self.running = False
            self.attention = "ERROR: %s" % e
            self.set_message_text("Error\r\n%s" % e)
            raise e

        #by this time no error means valid login, so lets save it to config
        self.save_config()
        self.set_message_text("%s Logged In" % self.username)

        self.preferences_window.hide()
        self.refresh_and_show()

        #all should be fine by now, return true
        return True

    def _setup_current_data(self, harvest_data):
        self.entries_count = len(harvest_data['day_entries'])

        self.today_total_hours = 0 #total hours amount for all entries combined
        self.today_total_elapsed_hours = 0 #today_total_hours + timedelta

        self.running = False

        self.projects = {}
        self.tasks = {}

        #all projects, used for liststore for combobox
        for project in harvest_data['projects']:
            project_id = str(project['id'])
            self.projects[project_id] = "%s - %s" % (project['client'], project['name'])
            self.tasks[project_id] = {}
            for task in project['tasks']:
                task_id = str(task['id'])
                self.tasks[project_id][task_id] = "%s" % task['name']

        _updated_at = None #date used to determine the newest entry to use as last entry, a user could on a diff comp use\
        # harvest web app and things go out of sync so we should use the newest updated_at entry

        # reset
        self.current_entry_id = None
        self.current_hours = ""
        self.current_project_id = None
        self.current_task_id = None
        self.current_created_at = None
        self.current_updated_at = None

        #get total hours and set current
        for entry in harvest_data['day_entries']:
            #how many hours worked today, used in counter label
            self.today_total_hours += entry['hours']

            #make dates into a datetime object we can use
            entry['updated_at'] = parse(entry['updated_at'])
            entry['created_at'] = parse(entry['created_at'])

            #this should all go away, leave for now
            if not _updated_at:#first time
                _updated_at = entry['updated_at']

            #use most recent updated at entry
            if _updated_at <= entry['updated_at']:
                _updated_at = entry['updated_at']
                _updated_at_time = mktime(entry['updated_at'].timetuple())

                stopped = False

                last_line = entry["notes"].split("\n")[-1] if entry.has_key("notes") and entry['notes'] else ""

                if last_line.split(" ")[-1] == "#TimerStopped" or last_line.find("#SwitchTo") > -1:
                    stopped = True

                if self.is_running(_updated_at_time, stopped):
                    self.running = True

                    self.current_hours = "%0.02f" % round(entry['hours'], 2)
                    self.current_notes = entry['notes']

                    self.current_updated_at = _updated_at_time

                    entry_id = str(entry['id'])
                    project_id = str(entry['project_id'])
                    task_id = str(entry['task_id'])

                    self.current_entry_id = entry_id

                    self.current_project = self.projects[project_id]
                    self.current_selected_project_id = project_id
                    self.current_selected_project_idx = self.projects.keys().index(
                        project_id) + 1 #compensate for empty 'select one'

                    self.current_selected_task_id = task_id
                    self.current_selected_task_idx = self.tasks[project_id].keys().index(
                        task_id) + 1 #compensate for empty 'select one'
                    self.current_task = self.tasks[project_id][task_id]

                    self.current_created_at = entry['created_at'] #set created at date for use in statusbar, as of now

                    self.current_text = "%s %s %s" % (entry['hours'], entry['task'], entry['project']) #make the text

        self.refresh_comboboxes() #setup the comboboxes
    def is_running(self, timestamp, stopped = False):
        if timestamp:
            if int(timestamp + self._interval) > int(mktime(datetime.utcnow().timetuple())):
                if not stopped:
                    return True

        return False

    def _get_elapsed_time_diff(self, timestamp):
        if timestamp:
            if float(timestamp + self._interval) > float(mktime(datetime.utcnow().timetuple())):
                return float(timestamp + self._interval) - float(mktime(datetime.utcnow().timetuple()))
        return False

    def stop_and_refactor_time(self, task_type = ""):
        if self.is_running(self.current_updated_at):
            #TODO: figure out how to keep track on lost seconds and add them up them auto correct,
            #also handle(when dialog yes response) the time when interval dialog is showing and the timer is actually stopped
            secs = self._get_elapsed_time_diff(self.current_updated_at) #seconds left to run this timer
            interval = round(float(self.interval) * (secs / self._interval),2) # interval to subract from already alloted time

            self.running = False
            self.last_project_id = self.current_project_id
            self.last_task_id = self.current_task_id

            if task_type != "":
                self.last_notes = self.get_notes(self.current_notes, False, "%s"%task_type) # task switched
            else:
                self.last_notes = self.get_notes(self.current_notes, True, "#TimerStopped") #timer stopped
                
            self.last_hours = "%0.02f" % round(float(self.current_hours) - float(interval), 2)
            self.last_text = self.current_text
            self.last_entry_id = self.current_entry_id
            #print self.last_hours
            entry = self.harvest.update(self.last_entry_id, {#append to existing timer
                'notes': self.last_notes,
                'hours': self.last_hours,
                'project_id': self.last_project_id,
                'task_id': self.last_task_id
            })
            #print entry
            self.set_entries()

    def append_add_entry(self):
        if self.harvest: #we have to be connected
            if self.current_selected_project_id and self.current_selected_task_id:
                if self.get_textview_text(self.notes_textview).strip("\n") == "":
                    return #Fail early, notes cannot be empty to send anything

                data = self.harvest.get_today()
                if not 'day_entries' in data:# this should never happen, but just in case lets check
                    self.attention = "Unable to Get data from Harvest"
                    self.set_message_text("Unable to Get data from Harvest")
                    return

                if self.running:
                    got_one = False
                    for entry in data['day_entries']:
                        if (entry['project_id'] == self.current_selected_project_id\
                            and entry['task_id'] == self.current_selected_task_id)\
                            and self.current_hours: #current running time with timedelta added from timer
                            #print 'running and exists', self.current_hours, self.last_hours

                            task = self.tasks[self.current_selected_project_id][self.current_selected_task_id]
                            self.stop_and_refactor_time(
                                "#SwitchTo %s " % task) #refactor any previous time alloted to a task
                            print 'running and exists', entry['hours'], self.current_hours, self.last_hours


                            if str(entry['id']) != str(self.last_entry_id): #dont increment timer if only append note to current timer
                                hours = round(float(entry['hours']) + float(self.interval), 2) #task switched
                                notes = self.get_notes(entry['notes'], True, "", True)
                            else:
                                hours = round(float(entry['hours']), 2) # same task as before, since interval timer running no need to increment time again
                                notes = self.get_notes(entry['notes'])

                            entry = self.harvest.update(entry['id'], {#append to existing timer
                                 'notes': notes,
                                 'hours': hours,
                                 'project_id': self.current_selected_project_id,
                                 'task_id': self.current_selected_task_id
                            })
                            #print entry
                            got_one = True
                            break

                    if not got_one:
                        #not the same project task as last one, add new entry
                        print 'running and doesnt exist'
                        project_id = self.get_combobox_selection(self.project_combobox)
                        task_id = self.get_combobox_selection(self.task_combobox)
                        task = self.tasks[project_id][task_id]
                        notes = self.get_notes(None, True, "", True), #TimerStarted
                        self.stop_and_refactor_time("#SwitchTo %s "%task) #refactor any previous time alloted to a task
                        entry = self.harvest.add({
                            'notes': notes,
                            'hours': self.interval,
                            'project_id': project_id,
                            'task_id': task_id
                        })
                        #print entry
                    if 'timer_started_at' in entry and 'id' in entry: #stop the timer if adding it has started it
                        self.harvest.toggle_timer(entry['id'])
                else:
                    got_one = False
                    for entry in data['day_entries']:
                        if (entry['project_id'] == self.current_selected_project_id\
                            and entry['task_id'] == self.current_selected_task_id): #found existing project/task entry for today, just append to it
                            #self.harvest.toggle_timer(entry['id'])
                            print 'not running and exists'

                            entry = self.harvest.update(entry['id'], {#append to existing timer
                                 'notes': self.get_notes(entry['notes'], True, "", True),
                                 'hours': round(float(entry['hours']) + float(self.interval), 2),
                                 'project_id': self.current_selected_project_id,
                                 'task_id': self.current_selected_task_id
                            })
                            #print entry
                            got_one = True
                            break

                    if not got_one:
                        #not the same project task as last one, add new entry
                        print 'not running and doesnt exist'
                        entry = self.harvest.add({
                            'notes': self.get_notes(None, True, "", True), #TimerStarted
                            'hours': self.interval,
                            'project_id': self.current_selected_project_id,
                            'task_id': self.current_selected_task_id
                        })
                        #print entry
                    if 'timer_started_at' in entry and 'id' in entry: #stop the timer if it was started by harvest, do timing locally
                        self.harvest.toggle_timer(entry['id'])

            else:
                self.statusbar.push(0, "No Project and Task Selected")
                return False
            self.set_textview_text(self.notes_textview, "")
            self.set_entries()
        else: #something is wrong we aren't connected
            return self.not_connected()
Пример #4
0
    print 'Creating java documentation...',
    build_android_project('../Wrappers/java', outputFile=logFile, target='javadoc')
    print 'OK'

# Create installer
strVersion = UpdateVersion.getVersionName()
print "Creating installer for OpenNI " + strVersion + " " + plat
finalDir = "Final"
if not os.path.isdir(finalDir):
    os.mkdir(finalDir)

if plat == 'Android':
    build_android()
    outputDir = 'OpenNI-Android-' + strVersion
    harvest = Harvest('..', outputDir, 'Arm', 'Android')
    harvest.run()

    finalFile = finalDir + '/' + outputDir + ".tar"
    print('Creating archive ' + finalFile)
    subprocess.check_call(['tar', '-cf', finalFile, outputDir])

elif platform.system() == 'Windows':
    import win32con,pywintypes,win32api,platform

    (bits,linkage) = platform.architecture()
    matchObject = re.search('64',bits)
    is_64_bit_machine = matchObject is not None

    if is_64_bit_machine:
        MSVC_KEY = (win32con.HKEY_LOCAL_MACHINE, r"SOFTWARE\Wow6432Node\Microsoft\VisualStudio\10.0")