Class: Openall_time_applet

Inherits:
Object
  • Object
show all
Defined in:
lib/openall_time_applet.rb

Overview

The base class of the applet. Spawns all windows, holds subclasses for models and gui, holds models objects and holds database-objects.

Defined Under Namespace

Classes: Gui, Models

Constant Summary collapse

CONFIG =

Config controlling paths and more.

{
  :settings_path => "#{Knj::Os.homedir}/.openall_time_applet",
  :run_path => "#{Knj::Os.homedir}/.openall_time_applet/run",
  :db_path => "#{Knj::Os.homedir}/.openall_time_applet/openall_time_applet.sqlite3",
  :sock_path => "#{Knj::Os.homedir}/.openall_time_applet/sock",
  :log_path => "#{Knj::Os.homedir}/.openall_time_applet/log"
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Openall_time_applet

Initializes config-dir and database.



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/openall_time_applet.rb', line 78

def initialize(args = {})
  Dir.mkdir(CONFIG[:settings_path]) if !File.exists?(CONFIG[:settings_path])
  self.check_runfile_and_cmds
  
  #Spawn logging-object.
  require "logger"
  @log = Logger.new(CONFIG[:log_path])
  @log.level = Logger::DEBUG
  
  self.require_gtk2
  @debug = args[:debug]
  
  #Database-connection.
  @log.debug("Spawning database-object.")
  @db = Knj::Db.new(
    :type => "sqlite3",
    :path => CONFIG[:db_path],
    :return_keys => "symbols",
    :index_append_table_name => true
  )
  
  #Update to latest db-revision.
  @log.debug("Updating database.")
  self.update_db
  
  #Models-handeler.
  @log.debug("Spawning model-handler.")
  @ob = Knj::Objects.new(
    :datarow => true,
    :db => @db,
    :class_path => "#{File.dirname(__FILE__)}/../models",
    :class_pre => "",
    :module => Openall_time_applet::Models
  )
  @ob.events.connect(:no_name, &self.method(:objects_no_name))
  @ob.connect("object" => :Timelog, "signals" => ["delete_before"], &self.method(:on_timelog_delete))
  
  @log.debug("Spawning event-handler.")
  @events = Knj::Event_handler.new
  @events.add_event(:name => :timelog_active_changed)
  
  #Options used to save various information (Openall-username and such).
  @log.debug("Spawning options-object.")
  Knj::Opts.init("knjdb" => @db, "table" => "Option")
  
  #Set crash-operation to save tracked time instead of loosing it.
  Kernel.at_exit(&self.method(:destroy))
  
  #Set default-color to "green_casalogic".
  Knj::Opts.set("tray_text_color", "green_casalogic") if Knj::Opts.get("tray_text_color").to_s.strip.empty?
  
  #Spawn tray-icon.
  @log.debug("Spawning tray-icon.")
  self.spawn_trayicon
  
  #Start reminder.
  @log.debug("Starting reminder.")
  self.reminding
  
  #Start unix-socket that listens for remote control.
  @log.debug("Spawning UNIX-socket.")
  @unix_socket = Openall_time_applet::Unix_socket.new(:oata => self)
  
  #Start autosync-timeout.
  @log.debug("Starting auto-sync.")
  self.restart_autosync
  
  @log.debug("OpenAll Time Applet started.")
  
  #Used to test when new tasks are created.
  #@ob.list(:Task, "title" => "Test no org") do |task|
  #  puts "Deleting test task."
  #  @ob.delete(task)
  #end
end

Instance Attribute Details

#dbObject (readonly)

Various readable variables.



65
66
67
# File 'lib/openall_time_applet.rb', line 65

def db
  @db
end

#debugObject (readonly)

Various readable variables.



65
66
67
# File 'lib/openall_time_applet.rb', line 65

def debug
  @debug
end

#eventsObject (readonly)

Various readable variables.



65
66
67
# File 'lib/openall_time_applet.rb', line 65

def events
  @events
end

#logObject (readonly)

Various readable variables.



65
66
67
# File 'lib/openall_time_applet.rb', line 65

def log
  @log
end

#obObject (readonly)

Various readable variables.



65
66
67
# File 'lib/openall_time_applet.rb', line 65

def ob
  @ob
end

#reminder_nextObject

Returns the value of attribute reminder_next.



66
67
68
# File 'lib/openall_time_applet.rb', line 66

def reminder_next
  @reminder_next
end

#tiObject (readonly)

Various readable variables.



65
66
67
# File 'lib/openall_time_applet.rb', line 65

def ti
  @ti
end

#timelog_activeObject

Various readable variables.



65
66
67
# File 'lib/openall_time_applet.rb', line 65

def timelog_active
  @timelog_active
end

#timelog_active_timeObject (readonly)

Various readable variables.



65
66
67
# File 'lib/openall_time_applet.rb', line 65

def timelog_active_time
  @timelog_active_time
end

Class Method Details

.const_missing(name) ⇒ Object

Autoloader for subclasses.



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/openall_time_applet.rb', line 49

def self.const_missing(name)
  namel = name.to_s.downcase
  tries = [
    "#{File.dirname(__FILE__)}/../classes/#{namel}.rb"
  ]
  tries.each do |try|
    if File.exists?(try)
      require try
      return Openall_time_applet.const_get(name)
    end
  end
  
  raise "Could not load constant: '#{name}'."
end

.execObject

Shortcut to start the application. Used by the Ubuntu-package.



26
27
28
# File 'lib/openall_time_applet.rb', line 26

def self.exec
  require "#{File.dirname(__FILE__)}/../bin/openall_time_applet.rb"
end

Instance Method Details

#check_runfile_and_cmdsObject

Creates a runfile or sending a command to the running OpenAll-Time-Applet through the Unix-socket.



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/openall_time_applet.rb', line 169

def check_runfile_and_cmds
  #If run-file exists and the PID within is still running, then send command (if given) and exit.
  if File.exists?(CONFIG[:run_path]) and Knj::Unix_proc.pid_running?(File.read(CONFIG[:run_path]).to_i) and File.exists?(CONFIG[:sock_path])
    running = true
    
    begin
      require "socket"
      UNIXSocket.open(CONFIG[:sock_path]) do |sock|
        cmd = nil
        ARGV.each do |val|
          if match = val.match(/^--cmd=(.+)$/)
            cmd = match[1]
            break
          end
        end
        
        if cmd
          puts "Executing command through sock: #{cmd}"
          sock.puts(cmd)
        end
      end
    rescue Errno::ECONNREFUSED
      running = false
    end
    
    if running
      puts "Already running"
      exit
    end
  end
  
  File.open(CONFIG[:run_path], "w") do |fp|
    fp.write(Process.pid)
  end
  
  Kernel.at_exit(&self.method(:unlink_runfile))
end

#destroyObject

Saves tracking-status if tracking. Stops Gtks main loop.



469
470
471
472
473
474
475
# File 'lib/openall_time_applet.rb', line 469

def destroy
  self.timelog_stop_tracking
  
  #Use quit-variable to avoid Gtk-warnings.
  Gtk.main_quit if @quit != true
  @quit = true
end

#gtk_timeoutObject



499
500
501
502
# File 'lib/openall_time_applet.rb', line 499

def gtk_timeout
  @sync_thread = Knj::Thread.new(&self.method(:run_autosync)) if !@sync_thread
  true
end

#oa_conn(args = nil) ⇒ Object

Creates a connection to OpenAll, logs in, yields the connection and destroys it again.

Examples

oata.oa_conn do |conn|

task_list = conn.task_list

end



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/openall_time_applet.rb', line 267

def oa_conn(args = nil)
  begin
    args_conn = {
      :oata => self,
      :host => Knj::Opts.get("openall_host"),
      :port => Knj::Opts.get("openall_port"),
      :username => Knj::Opts.get("openall_username"),
      :password => Base64.strict_decode64(Knj::Opts.get("openall_password")),
      :ssl => Knj::Strings.yn_str(Knj::Opts.get("openall_ssl"), true, false)
    }
    args_conn.merge!(args) if args
    
    conn = Openall_time_applet::Connection.new(args_conn)
    yield(conn)
  ensure
    conn.destroy if conn
  end
end

#objects_no_name(event, classname) ⇒ Object

Called when something doesnt have a name to get a replacement-name in the objects-framework.



164
165
166
# File 'lib/openall_time_applet.rb', line 164

def objects_no_name(event, classname)
  return _("not set")
end

#on_timelog_delete(timelog) ⇒ Object

Called when a timelog is deleted.



155
156
157
158
159
160
161
# File 'lib/openall_time_applet.rb', line 155

def on_timelog_delete(timelog)
  #Stop tracking if the active timelog is being deleted.
  if @timelog_active and @timelog_active.id.to_i == timelog.id.to_i
    @log.debug("Tracked timelog is being deleted - stopping tracking before deletion.")
    self.timelog_stop_tracking
  end
end

#push_time_updatesObject

Pushes time-updates to OpenAll.



339
340
341
342
# File 'lib/openall_time_applet.rb', line 339

def push_time_updates
  @log.debug("Pushing timelogs.")
  @ob.static(:Timelog, :push_time_updates, {:oata => self})
end

#remindingObject

This method starts the reminder-thread, that checks if a reminder should be shown.



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/openall_time_applet.rb', line 236

def reminding
  Knj::Thread.new do
    loop do
      enabled = Knj::Strings.yn_str(Knj::Opts.get("reminder_enabled"), true, false)
      if enabled and !@reminder_next
        @reminder_next = Datet.new
        @reminder_next.mins + Knj::Opts.get("reminder_every_minute").to_i
      elsif enabled and @reminder_next and Time.now >= @reminder_next
        self.reminding_exec
        @reminder_next = nil
      end
      
      sleep 30
    end
  end
  
  return nil
end

#reminding_execObject

This executes the notification that notifies if a timelog is being tracked.



256
257
258
259
260
# File 'lib/openall_time_applet.rb', line 256

def reminding_exec
  return nil unless @timelog_active
  @log.debug("Sending reminder through notify.")
  Knj::Notify.send("time" => 5, "msg" => sprintf(_("Tracking task: %s"), @timelog_active[:descr]))
end

#require_gtk2Object

Requires the heavy Gtk-stuff.



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/openall_time_applet.rb', line 213

def require_gtk2
  require "gtk2"
  
  #For msgbox and translation of windows.
  require "knj/gtk2"
  
  #For easy initialization, getting and settings of values on comboboxes.
  require "knj/gtk2_cb"
  
  #For easy initialization, getting and settings of values on treeviews.
  require "knj/gtk2_tv"
  
  #For easy making status-windows with progressbar.
  require "knj/gtk2_statuswindow"
end

#restart_autosyncObject

Restarts the auto-syncing timeout.



478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/openall_time_applet.rb', line 478

def restart_autosync
  #Remove current timeout.
  Gtk.timeout_remove(@autosync_timeout) if @autosync_timeout
  @autosync_timeout = nil
  
  #Get various info from db.
  enabled = Knj::Strings.yn_str(Knj::Opts.get("autosync_enabled"), true, false)
  interval = Knj::Opts.get("autosync_interval").to_i
  interval_msecs = interval * 60 * 1000
  
  if !enabled #dont continue if autosync isnt enabled.
    self.status = _("Disabled automatic synchronization.")
    return nil
  end
  
  self.status = sprintf(_("Restarted automatic sync. to run every %s minutes."), Knj::Locales.number_out(interval, 1))
  
  #Start new timeout.
  @autosync_timeout = Gtk.timeout_add(interval_msecs, &self.method(:gtk_timeout))
end

#run_autosyncObject

This method is executing the automatic synchronization.



505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'lib/openall_time_applet.rb', line 505

def run_autosync
  begin
    self.status = _("Synchronizing organisations.")
    self.update_organisation_cache
    
    self.status = _("Synchronizing worktime.")
    self.update_worktime_cache
    
    self.status = _("Automatic synchronization done.")
  rescue => e
    self.status = sprintf(_("Error while auto-syncing: %s"), e.message)
    puts Knj::Errors.error_str(e)
  ensure
    @sync_thread = nil
  end
end

#show_mainObject



292
293
294
295
296
297
# File 'lib/openall_time_applet.rb', line 292

def show_main
  @log.debug("Show main window.")
  Knj::Gtk2::Window.unique!("main") do
    Openall_time_applet::Gui::Win_main.new(:oata => self)
  end
end

#show_overviewObject



307
308
309
310
311
312
# File 'lib/openall_time_applet.rb', line 307

def show_overview
  @log.debug("Show overview.")
  Knj::Gtk2::Window.unique!("overview") do
    Openall_time_applet::Gui::Win_overview.new(:oata => self)
  end
end

#show_preferencesObject

Spawns the preference-window.



300
301
302
303
304
305
# File 'lib/openall_time_applet.rb', line 300

def show_preferences
  @log.debug("Show preferences.")
  Knj::Gtk2::Window.unique!("preferences") do
    Openall_time_applet::Gui::Win_preferences.new(:oata => self)
  end
end

#show_worktime_overviewObject



314
315
316
317
318
319
# File 'lib/openall_time_applet.rb', line 314

def show_worktime_overview
  @log.debug("Show worktime-overview.")
  Knj::Gtk2::Window.unique!("worktime_overview") do
    Openall_time_applet::Gui::Win_worktime_overview.new(:oata => self)
  end
end

#spawn_trayiconObject

Spawns the trayicon in systray.



287
288
289
290
# File 'lib/openall_time_applet.rb', line 287

def spawn_trayicon
  return nil if @ti
  @ti = Openall_time_applet::Gui::Trayicon.new(:oata => self)
end

#status=(newstatus) ⇒ Object

Prints status to the command line and the statusbar in the main window (if the main window is open).



523
524
525
526
527
528
529
530
531
# File 'lib/openall_time_applet.rb', line 523

def status=(newstatus)
  @log.debug("New status: '#{newstatus}'.")
  puts "Status: '#{newstatus}'."
  win_main = Knj::Gtk2::Window.get("main")
  
  if win_main
    win_main.gui["statusbar"].push(0, newstatus)
  end
end

#sync_realObject

Refreshes task-cache, create missing worktime from timelogs and push tracked time to timelogs. Shows a status-window while doing so.



377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# File 'lib/openall_time_applet.rb', line 377

def sync_real
  sw = Knj::Gtk2::StatusWindow.new
  self.timelog_stop_tracking if @timelog_active
  
  Knj::Thread.new do
    begin
      sw.label = _("Pushing time-updates.")
      self.push_time_updates
      sw.percent = 0.3
      
      sw.label = _("Update task-cache.")
      self.update_task_cache
      sw.percent = 0.66
      
      sw.label = _("Updating worktime-cache.")
      self.update_worktime_cache
      sw.percent = 1
      
      sw.label = _("Done")
      
      sleep 1
    rescue => e
      Knj::Gtk2.msgbox("msg" => Knj::Errors.error_str(e), "type" => "warning", "title" => _("Error"), "run" => false)
    ensure
      sw.destroy if sw
    end
  end
end

#sync_static(args = {}) ⇒ Object

Synchronizes organisations, tasks and worktimes.



345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/openall_time_applet.rb', line 345

def sync_static(args = {})
  sw = Knj::Gtk2::StatusWindow.new("transient_for" => args["transient_for"])
  
  return Knj::Thread.new do
    begin
      sw.label = _("Updating organisation-cache.")
      self.update_organisation_cache
      sw.percent = 0.33
      
      sw.label = _("Updating task-cache.")
      self.update_task_cache
      sw.percent = 0.66
      
      sw.label = _("Updating worktime-cache.")
      self.update_worktime_cache
      sw.percent = 1
      
      sleep 1 if !block_given?
      sw.destroy if sw
      sw = nil
      yield if block_given?
    rescue => e
      sw.destroy if sw
      sw = nil
      Knj::Gtk2.msgbox("msg" => Knj::Errors.error_str(e), "type" => "warning", "title" => _("Error"), "run" => false)
    ensure
      sw.destroy if sw
    end
  end
end

#timelog_active_time_trackedObject

Returns the amount of seconds tracked.



463
464
465
466
# File 'lib/openall_time_applet.rb', line 463

def timelog_active_time_tracked
  return 0 if !@timelog_active_time
  return Time.now.to_i - @timelog_active_time.to_i
end

#timelog_stop_trackingObject

Stops tracking a timelog. Saves time tracked and sets sync-flag.



407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/openall_time_applet.rb', line 407

def timelog_stop_tracking
  if @timelog_active
    @log.debug("Stopping tracking of timelog.")
    secs_passed = Time.now.to_i - @timelog_active_time.to_i
    
    @timelog_active.update(
      :time => @timelog_active[:time].to_i + secs_passed,
      :sync_need => 1
    )
    @timelog_logged_time[:timestamp_end] = Time.now
  end
  
  @timelog_active = nil
  @timelog_active_time = nil
  @ti.update_icon if @ti
  @events.call(:timelog_active_changed)
end

#trayicon_timelogsObject



533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
# File 'lib/openall_time_applet.rb', line 533

def trayicon_timelogs
  yielded_titles = {}
  
  #Make a list of all timelogs in the menu.
  @ob.list(:Timelog, "orderby" => "descr") do |timelog|
    task_id = timelog[:task_id].to_i
    yielded_titles[task_id] = {} if !yielded_titles.key?(task_id)
    
    title = timelog.descr_short.strip.downcase
    next if yielded_titles[task_id].key?(title)
    yielded_titles[task_id][title] = true
    
    yield(timelog)
  end
end

When the Ruby-process exits this method will be called through ‘Kernel.at_exit’.



208
209
210
# File 'lib/openall_time_applet.rb', line 208

def unlink_runfile
  File.unlink(CONFIG[:run_path]) if File.exists?(CONFIG[:run_path]) and File.read(CONFIG[:run_path]).to_i == Process.pid.to_i
end

#update_dbObject

Updates the database according to the db-schema.



230
231
232
233
# File 'lib/openall_time_applet.rb', line 230

def update_db
  require "#{File.dirname(__FILE__)}/../conf/db_schema.rb"
  Knj::Db::Revision.new.init_db("debug" => false, "db" => @db, "schema" => Openall_time_applet::DB_SCHEMA)
end

#update_organisation_cacheObject



333
334
335
336
# File 'lib/openall_time_applet.rb', line 333

def update_organisation_cache
  @log.debug("Updating organisation-cache.")
  @ob.static(:Organisation, :update_cache, {:oata => self})
end

#update_task_cacheObject

Updates the task-cache.



322
323
324
325
# File 'lib/openall_time_applet.rb', line 322

def update_task_cache
  @log.debug("Updating task-cache.")
  @ob.static(:Task, :update_cache, {:oata => self})
end

#update_worktime_cacheObject

Updates the worktime-cache.



328
329
330
331
# File 'lib/openall_time_applet.rb', line 328

def update_worktime_cache
  @log.debug("Updating worktime-cache.")
  @ob.static(:Worktime, :update_cache, {:oata => self})
end