~ubuntu-branches/ubuntu/raring/agtl/raring

« back to all changes in this revision

Viewing changes to freerunner/usr/lib/site-python/advancedcaching/core.py

  • Committer: Bazaar Package Importer
  • Author(s): Heiko Stuebner
  • Date: 2009-09-11 20:39:19 UTC
  • Revision ID: james.westby@ubuntu.com-20090911203919-v0oh5cf3w8ly1366
Tags: upstream-0.3.0+git20090911
ImportĀ upstreamĀ versionĀ 0.3.0+git20090911

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/python
 
2
# -*- coding: utf-8 -*-
 
3
 
 
4
#       Copyright (C) 2009 Daniel Fett
 
5
#       This program is free software: you can redistribute it and/or modify
 
6
#   it under the terms of the GNU General Public License as published by
 
7
#   the Free Software Foundation, either version 3 of the License, or
 
8
#   (at your option) any later version.
 
9
#
 
10
#   This program is distributed in the hope that it will be useful,
 
11
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
 
12
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
13
#   GNU General Public License for more details.
 
14
#
 
15
#   You should have received a copy of the GNU General Public License
 
16
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
17
#
 
18
#       Author: Daniel Fett simplecaching@fragcom.de
 
19
#
 
20
 
 
21
 
 
22
 
 
23
### For loading the conf file
 
24
#from advancedcachinglib.geocaching import FieldnotesUploader
 
25
import json
 
26
import sys
 
27
import os
 
28
 
 
29
import downloader
 
30
import geocaching
 
31
import gpsreader
 
32
import provider
 
33
import gobject
 
34
import gtk
 
35
import os
 
36
 
 
37
#import cProfile
 
38
#import pstats
 
39
 
 
40
 
 
41
if len(sys.argv) < 2:
 
42
    print "Usage: %s --desktop (not really implemented yet) or %s --simple" % (sys.argv[0], sys.argv[0])
 
43
    exit()
 
44
        
 
45
arg = sys.argv[1].strip()
 
46
if arg == '--simple':
 
47
    import simplegui
 
48
    gui = simplegui.SimpleGui
 
49
else:
 
50
    from advancedcaching import biggui
 
51
    gui = biggui.BigGui
 
52
 
 
53
        
 
54
class Standbypreventer():
 
55
    STATUS_NONE = 0
 
56
    STATUS_ALIVE = 1
 
57
    STATUS_SCREEN_ON = 2
 
58
 
 
59
    def __init__(self):
 
60
        self.requested_status = self.STATUS_NONE
 
61
                
 
62
    def __del__(self):
 
63
        self.__unrequest_all()
 
64
                
 
65
    def set_status(self, status):
 
66
        if status != self.requested_status:
 
67
            self.__unrequest_all()
 
68
            self.__request(status)
 
69
        
 
70
    def __unrequest_all(self):
 
71
        if self.requested_status == self.STATUS_ALIVE:
 
72
            self.__try_run('dbus-send --system --type=method_call --dest=org.shr.ophonekitd.Usage /org/shr/ophonekitd/Usage org.shr.ophonekitd.Usage.ReleaseResource string:CPU')
 
73
        elif self.requested_status == self.STATUS_SCREEN_ON:
 
74
            self.__try_run('dbus-send --system --type=method_call --dest=org.shr.ophonekitd.Usage /org/shr/ophonekitd/Usage org.shr.ophonekitd.Usage.ReleaseResource string:Display')
 
75
                        
 
76
    def __request(self, status):
 
77
        if status == self.STATUS_ALIVE:
 
78
            self.__try_run('dbus-send --system --type=method_call --dest=org.shr.ophonekitd.Usage /org/shr/ophonekitd/Usage org.shr.ophonekitd.Usage.RequestResource string:CPU')
 
79
        elif status == self.STATUS_SCREEN_ON:
 
80
            self.__try_run('dbus-send --system --type=method_call --dest=org.shr.ophonekitd.Usage /org/shr/ophonekitd/Usage org.shr.ophonekitd.Usage.RequestResource string:Display')
 
81
                        
 
82
    def __try_run(self, command):
 
83
        try:
 
84
            os.system(command)
 
85
        except Exception as e:
 
86
            print "Could not prevent Standby: %s" % e
 
87
 
 
88
class Core():
 
89
    SETTINGS_DIR = os.path.expanduser('~/.agtl')
 
90
    DEFAULT_SETTINGS = {
 
91
        'download_visible': True,
 
92
        'download_notfound': True,
 
93
        'download_new': True,
 
94
        'download_nothing': False,
 
95
        'download_create_index': True,
 
96
        'download_run_after': False,
 
97
        'download_run_after_string': '',
 
98
        'download_output_dir': os.path.expanduser('~/caches/'),
 
99
        'map_position_lat': 49.7540,
 
100
        'map_position_lon': 6.66135,
 
101
        'map_zoom': 7,
 
102
        'download_resize': True,
 
103
        'download_resize_pixel': 400,
 
104
        'options_show_name': True,
 
105
        'options_username': "Username",
 
106
        'options_password': "Pass",
 
107
        'last_target_lat': 50,
 
108
        'last_target_lon': 10,
 
109
        'last_target_name': 'default',
 
110
        'download_noimages': False,
 
111
        'download_map_path': os.path.expanduser('~/Maps/OSM/'),
 
112
        'options_hide_found': False
 
113
    }
 
114
        
 
115
    def __init__(self, guitype, root):
 
116
        if not os.path.exists(self.SETTINGS_DIR):
 
117
            os.mkdir(self.SETTINGS_DIR)
 
118
 
 
119
 
 
120
        dataroot = os.path.join(root, 'data')
 
121
        
 
122
        #self.standbypreventer = Standbypreventer()
 
123
        # seems to crash dbus/fso/whatever
 
124
                        
 
125
        self.__read_config()
 
126
                
 
127
        #self.standbypreventer.set_status(Standbypreventer.STATUS_SCREEN_ON)
 
128
                
 
129
        self.downloader = downloader.FileDownloader(self.settings['options_username'], self.settings['options_password'])
 
130
                
 
131
        #pointprovider = LiveCacheProvider()
 
132
        self.pointprovider = provider.PointProvider("%s/caches.db" % self.SETTINGS_DIR, self.downloader, geocaching.GeocacheCoordinate, 'geocaches')
 
133
        #self.userpointprovider = provider.PointProvider("%s/caches.db" % self.SETTINGS_DIR, self.downloader, geo.Coordinate, 'userpoints')
 
134
        self.userpointprovider = None
 
135
        #pointprovider = PointProvider(':memory:', self.downloader)
 
136
        #reader = GpxReader(pointprovider)
 
137
        #reader.read_file('../../file.loc')
 
138
        
 
139
        self.gui = guitype(self, self.pointprovider, self.userpointprovider, dataroot)
 
140
        self.gui.write_settings(self.settings)
 
141
                
 
142
        self.gps_thread = gpsreader.GpsReader(self)
 
143
        gobject.timeout_add(1000, self.__read_gps)
 
144
        #self.downloader.upload_fieldnotes()
 
145
        self.gui.show()
 
146
                
 
147
                
 
148
                
 
149
    def __del__(self):
 
150
        self.settings = self.gui.read_settings()
 
151
        self.__write_config()
 
152
                
 
153
    #def search_value_terrain_change(self, a):
 
154
#               #print a, b, c
 
155
    #if self.search_elements['terrain']['upper'].get_adjustment().get_value() < self.search_elements['terrain']['lower'].get_adjustment().get_value():
 
156
    #   self.search_elements['terrain'][
 
157
#def search_value_diff_change(self, widget):
 
158
    #pass
 
159
                
 
160
                
 
161
 
 
162
                
 
163
                
 
164
                
 
165
# called by gui
 
166
    def on_cache_selected(self, cache):
 
167
        self.gui.show_cache(cache)
 
168
                
 
169
    # called by gui
 
170
    def on_start_search_simple(self, text):
 
171
        #m = re.search(r'/([NS]?)\s*(\d{1,2})\.(\d{1,2})\D+(\d+)\s*([WE]?)\s*(\d{1,3})\.(\d{1,2})\D+(\d+)', text, re.I)
 
172
        #if m != None:
 
173
        self.__try_show_cache_by_search('%' + text + '%')
 
174
                
 
175
    # called by gui
 
176
    def on_start_search_advanced(self, found=None, owner_search='', name_search='', size=None, terrain=None, diff=None, ctype=None):
 
177
                
 
178
                
 
179
        self.pointprovider.set_filter(found=found, owner_search=owner_search, name_search=name_search, size=size, terrain=terrain, diff=diff, ctype=ctype)
 
180
        points = self.pointprovider.get_points_filter()
 
181
        self.gui.display_results_advanced(points)
 
182
                                
 
183
 
 
184
    # called by gui
 
185
    def on_destroy(self):
 
186
        self.settings = self.gui.read_settings()
 
187
        self.__write_config()
 
188
 
 
189
    # called by gui
 
190
    def on_download(self, location):
 
191
        cd = geocaching.CacheDownloader(self.downloader)
 
192
        caches = cd.get_geocaches(location)
 
193
        for c in caches:
 
194
            self.pointprovider.add_point(c)
 
195
        self.pointprovider.save()
 
196
 
 
197
    # called by gui
 
198
    def on_download_cache(self, cache):
 
199
        self.gui.set_download_progress(0.5, "Downloading %s..." % cache.name)
 
200
        try:
 
201
            cd = geocaching.CacheDownloader(self.downloader)
 
202
            exporter = geocaching.HTMLExporter(self.downloader, self.settings['download_output_dir'], self.settings['download_noimages'])
 
203
            full = cd.update_coordinate(cache)
 
204
            self.pointprovider.add_point(full, True)
 
205
            exporter.export(full)
 
206
            self.pointprovider.save()
 
207
        except Exception as e:
 
208
            self.gui.show_error(e)
 
209
        finally:
 
210
            self.gui.hide_progress()
 
211
                
 
212
                
 
213
                
 
214
    # called by gui
 
215
    def on_download_descriptions(self, location, visibleonly=False):
 
216
        cd = geocaching.CacheDownloader(self.downloader)
 
217
        exporter = geocaching.HTMLExporter(self.downloader, self.settings['download_output_dir'], None, self.settings['download_noimages'])
 
218
                
 
219
        self.pointprovider.push_filter()
 
220
                        
 
221
        if self.settings['download_notfound'] or visibleonly:
 
222
            found = False
 
223
        else:
 
224
            found = None
 
225
                        
 
226
        if self.settings['download_new'] or visibleonly:
 
227
            has_details = False
 
228
        elif self.settings['download_nothing']:
 
229
            has_details = True
 
230
        else:
 
231
            has_details = None
 
232
                
 
233
                
 
234
        if self.settings['download_visible'] or visibleonly:
 
235
            self.pointprovider.set_filter(found=found, has_details=has_details, adapt_filter=True)
 
236
            caches = self.pointprovider.get_points_filter(location)
 
237
        else:
 
238
            self.pointprovider.set_filter(found=found, has_details=has_details, adapt_filter=False)
 
239
            caches = self.pointprovider.get_points_filter()
 
240
                
 
241
                
 
242
                
 
243
        count = len(caches)
 
244
        i = 0.0
 
245
        try:
 
246
            for cache in caches:
 
247
                self.gui.set_download_progress(i / count, "Downloading %s..." % cache.name)
 
248
                full = cd.update_coordinate(cache)
 
249
                self.pointprovider.add_point(full, True)
 
250
                exporter.export(full)
 
251
                i += 1.0
 
252
                                
 
253
        except Exception as e:
 
254
            self.gui.show_error(e)
 
255
        finally:
 
256
            self.gui.hide_progress()
 
257
        self.pointprovider.save()
 
258
                
 
259
        self.pointprovider.pop_filter()
 
260
                
 
261
        #if self.settings['download_create_index']:
 
262
        #       all_caches = pointprovider.get_points_filter(None, None, True)
 
263
        #       exporter.write_index(all_caches)
 
264
 
 
265
                
 
266
 
 
267
                        
 
268
    # called by gui
 
269
    def on_config_changed(self, new_settings):
 
270
        self.settings = new_settings
 
271
        self.downloader.update_userdata(self.settings['options_username'], self.settings['options_password'])
 
272
        self.__write_config()
 
273
 
 
274
 
 
275
    def on_notes_changed(self, cache, new_notes):
 
276
        self.pointprovider.update_field(cache, 'notes', new_notes)
 
277
 
 
278
    def on_fieldnotes_changed(self, cache, new_notes):
 
279
        self.pointprovider.update_field(cache, 'fieldnotes', new_notes)
 
280
 
 
281
                
 
282
    def on_upload_fieldnotes(self):
 
283
        self.gui.set_download_progress(0.5, "Uploading Fieldnotes...")
 
284
 
 
285
        caches = self.pointprovider.get_new_fieldnotes()
 
286
        fn = geocaching.FieldnotesUploader(self.downloader)
 
287
        try:
 
288
            for c in caches:
 
289
                fn.add_fieldnote(c)
 
290
            fn.upload()
 
291
                        
 
292
        except Exception as e:
 
293
            self.gui.show_error(e)
 
294
        else:
 
295
            #self.gui.show_success("Field notes uploaded successfully.")
 
296
            for c in caches:
 
297
                self.pointprovider.update_field(c, 'logas', geocaching.GeocacheCoordinate.LOG_NO_LOG)
 
298
        finally:
 
299
            self.gui.hide_progress()
 
300
                
 
301
    def __read_gps(self):
 
302
        gps_data = self.gps_thread.get_data()
 
303
        if (gps_data['position'] != None):
 
304
            self.gui.on_good_fix(gps_data)
 
305
        else:
 
306
            self.gui.on_no_fix(gps_data, self.gps_thread.status)
 
307
        return True
 
308
                
 
309
    def __read_config(self):
 
310
        filename = os.path.join(self.SETTINGS_DIR, 'config')
 
311
        if not os.path.exists(filename):
 
312
            self.settings = self.DEFAULT_SETTINGS
 
313
            return
 
314
        f = file(filename, 'r')
 
315
        string = f.read()
 
316
        self.settings = {}
 
317
        if string != '':
 
318
            tmp_settings = json.loads(string)
 
319
            for k, v in self.DEFAULT_SETTINGS.items():
 
320
                if k in tmp_settings.keys() != None:
 
321
                    self.settings[k] = tmp_settings[k]
 
322
                else:
 
323
                    self.settings[k] = self.DEFAULT_SETTINGS[k]
 
324
        else:
 
325
            self.settings = self.DEFAULT_SETTINGS
 
326
                
 
327
                
 
328
                
 
329
    def __try_show_cache_by_search(self, idstring):
 
330
        cache = self.pointprovider.find_by_string(idstring)
 
331
        if cache != None:
 
332
            self.gui.show_cache(cache)
 
333
            self.gui.set_center(cache)
 
334
            return True
 
335
        return False
 
336
                
 
337
    def __write_config(self):
 
338
        filename = os.path.join(self.SETTINGS_DIR, 'config')
 
339
        f = file(filename, 'w')
 
340
        f.write(json.dumps(self.settings, sort_keys=True, indent=4))
 
341
 
 
342
 
 
343
def determine_path ():
 
344
    """Borrowed from wxglade.py"""
 
345
    try:
 
346
        root = __file__
 
347
        if os.path.islink (root):
 
348
            root = os.path.realpath (root)
 
349
        return os.path.dirname(os.path.abspath (root))
 
350
    except:
 
351
        print "I'm sorry, but something is wrong."
 
352
        print "There is no __file__ variable. Please contact the author."
 
353
        sys.exit()
 
354
 
 
355
                        
 
356
def start():
 
357
    gtk.gdk.threads_init()
 
358
    core = Core(gui, determine_path())
 
359
 
 
360
 
 
361
if "--profile" in sys.argv:
 
362
    import cProfile
 
363
    command = """runit()"""
 
364
    cProfile.runctx(command, globals(), locals(), filename="Advancedcaching.profile")
 
365
    exit()
 
366
 
 
367
if __name__ == "__main__":
 
368
    gtk.gdk.threads_init()
 
369
    core = Core(gui, determine_path())
 
370
 
 
371
                
 
372