Porównaj commity

...

549 Commity
v0.1 ... master

Autor SHA1 Wiadomość Data
Christian T. Jacobs df629e7a64
Merge pull request #70 from WB5VQX/master
Corrected log deletion bug.
2019-02-22 20:59:28 +00:00
WB5VQX 5efe5849ff Corrected log deletion bug. 2019-02-16 20:58:59 -06:00
Christian Jacobs 71624162bb Updated year range. 2018-04-02 18:52:23 +01:00
Christian Jacobs f9837e14ba In turn. 2018-04-02 17:54:28 +01:00
Christian Jacobs 99b5746f52 Bumping version number to 1.1.0. 2018-04-02 17:38:32 +01:00
Christian Jacobs c6845c082e Updated dependency list. 2018-04-02 17:30:49 +01:00
Christian Jacobs 095743e3ba Preparing for v1.1.0 release. 2018-04-02 16:11:52 +01:00
Christian Jacobs ff8c6956fc Added the link to the screencast. 2018-04-02 16:11:40 +01:00
Christian Jacobs 42d4966d9f Updated screenshot. 2018-04-01 20:41:00 +01:00
Christian Jacobs 9cae123db1 Updating screenshots. 2018-04-01 20:31:04 +01:00
Christian Jacobs 591ed62869 More experimenting with colour schemes. 2018-04-01 18:41:19 +01:00
Christian Jacobs 108f0d00b5 Updated screenshots. 2018-03-31 22:44:30 +01:00
Christian Jacobs 833da88ae2 Remove hyphen in pin-point. 2018-03-31 22:36:02 +01:00
Christian Jacobs d41d20779b Added documentation on copy/pasting QSOs and the world map tool. 2018-03-31 22:32:56 +01:00
Christian Jacobs f597122721 Use annotations to label pinpoints. 2018-03-31 22:32:46 +01:00
Christian Jacobs 3f29d763e4 Renamed grey_line.png to world_map.png. 2018-03-31 21:54:13 +01:00
Christian Jacobs 5988771a02 More experimenting with colors. 2018-03-31 21:49:15 +01:00
Christian Jacobs 9609b9c3d4 Experimenting with the colors in the World Map. 2018-03-31 16:01:36 +01:00
Christian Jacobs fd41340109 Updated the screenshot of the Edit Record dialog. 2018-03-31 14:57:19 +01:00
Christian Jacobs c0212f72d7 Updating the World Map documentation. 2018-03-28 22:49:44 +01:00
Christian Jacobs 05dee365b3 Bump version number to v1.1.0. 2018-03-28 22:33:28 +01:00
Christian Jacobs f1236f70e6 Added a note about how the station locations are plotted based on GRIDSQUARE (or COUNTRY) field. 2018-03-28 21:21:24 +01:00
Christian Jacobs ed95a86710 Use the Maidenhead object that is already defined. 2018-03-28 21:17:06 +01:00
Christian Jacobs 7dd02c35c0 Only define the NavigationToolbar derived class if the necessary modules are installed. 2018-03-28 21:12:14 +01:00
Christian Jacobs d23dd54473 Import only those classes that are used in the unit tests. 2018-03-28 20:51:46 +01:00
Christian Jacobs 1fcdb4f6ee Added WorldMap unit tests. 2018-03-28 19:14:20 +01:00
Christian Jacobs 785d3b320f Added Maidenhead unit tests. 2018-03-28 18:32:04 +01:00
Christian Jacobs 6834673e28 Add option to return a 6-character Maidenhead locator. 2018-03-28 18:31:43 +01:00
Christian Jacobs b47ffa1366 Try the country field if the grid square field fails to provide the correct information. 2018-03-27 21:38:48 +01:00
Christian Jacobs d945d40064 Make use of GRIDSQUARE value when plotting a station's location on the world map. 2018-03-27 19:49:18 +01:00
Christian T. Jacobs ae8f45450a
Merge pull request #66 from merkato/patch-1
WSJT-X FT8 mode in adif.py
2018-03-22 20:42:20 +00:00
Tomasz Nycz b20e238ad9
WSJT-X FT8 mode in adif.py 2018-03-22 20:56:23 +01:00
Christian Jacobs 154673c189 Small docstring update. 2018-03-10 15:54:23 +00:00
Christian T. Jacobs 5198547c6c
Maidenhead (#65)
Added the option of showing Maidenhead grid squares on the World Map, and the option of shading in worked grid squares. Addresses issue #59. Note that this introduces a new class called Maidenhead, which is capable of converting between latitude-longitude coordinates and grid squares. However, this functionality isn't currently used.
2018-03-10 15:49:44 +00:00
Christian T. Jacobs f222d5cc30
Migrate to a world map / grey line that uses Cartopy (#64)
Migrating grey line functionality over to a Cartopy-based implementation to address issue #62.

Also renamed GreyLine to WorldMap, and bumped the version to v1.1.0-dev.
2018-02-24 13:24:39 +00:00
Christian Jacobs f283df065b Merge branch 'master' of https://github.com/ctjacobs/pyqso into copypaste 2018-02-23 17:04:09 +00:00
Christian Jacobs 26e871bcab Small improvement to the wording. 2018-02-13 21:05:36 +00:00
Christian Jacobs ee6018b04a Added a requirements.txt file for the purpose of installing dependencies. Addresses issue #63. 2018-02-13 21:03:25 +00:00
Christian Jacobs 89f1ca46b4 Small improvements to the Getting Started section. 2018-02-13 21:02:22 +00:00
Christian Jacobs 1ef87caf5e Adding more explanation about PyQSO's dependencies. 2018-02-13 21:01:19 +00:00
Christian Jacobs 946f03d95f Added basic copy/paste functionality for individual records. 2018-02-04 23:15:57 +00:00
Christian T. Jacobs 7a162b2a2d
Callsign map (#61)
Pinpoint selected callsigns on the grey line map by looking up the latitude-longitude coordinates based on the value in the COUNTRY field. A new right-click popup menu has been created for this purpose.
2018-01-18 20:52:44 +00:00
Christian T. Jacobs d06e326cbd Update list of supported ADIF fields. 2017-09-04 15:53:44 +01:00
Christian T. Jacobs 4550f841f7 Add support for satellite QSOs. Addresses issue #55. 2017-09-04 15:48:50 +01:00
Christian T. Jacobs 591fe60f87 Added v1.0.0 tag to the CHANGELOG. 2017-08-02 11:43:52 +01:00
Christian T. Jacobs b98421dd6d Set the default submode to the empty string when the default mode is changed. 2017-07-26 00:20:56 +01:00
Christian T. Jacobs 4e044e72f7 Update QSL Sent and QSL Rcvd options. 2017-07-23 16:19:35 +01:00
Christian T. Jacobs 02c34387e5 More ADIF is_valid tests. 2017-07-23 16:10:26 +01:00
Christian T. Jacobs 3fc6f3198a Check that the SUBMODE field is valid. 2017-07-23 13:49:08 +01:00
Christian T. Jacobs a09696b4a5 Allow whitespace (e.g. newline characters for the multiline NOTES field) when importing ADIF files. 2017-07-13 17:39:19 +01:00
Christian T. Jacobs e00af44173 Updated CHANGELOG. 2017-07-13 17:27:40 +01:00
Christian T. Jacobs 63563b9085 flake8 2017-07-13 17:24:42 +01:00
Christian T. Jacobs 1b98e7695e One more test resource file migration. 2017-07-13 17:23:27 +01:00
Christian T. Jacobs 8dc9ed6aac Handle \n characters in the NOTES field more naturally. 2017-07-13 17:21:26 +01:00
Christian T. Jacobs af57a915fd Put ADIF-related test resources in tests/res. 2017-07-13 17:21:01 +01:00
Christian T. Jacobs 4d00a79620 Use "getboolean" not "get" when checking config values. 2017-07-09 11:42:42 +01:00
Christian T. Jacobs f250d4c078 Preferences section title changed to "import_export". 2017-07-07 15:33:32 +01:00
Christian T. Jacobs 21367d02a2 Updated docstrings and renamed ADIFPage to ImportExportPage in the Preferences dialog. 2017-07-07 12:22:32 +01:00
Christian T. Jacobs f6af59a5fd Check for an empty CALL field earlier. 2017-07-07 12:22:18 +01:00
Christian T. Jacobs dd83014d9a Don't bother checking the length of the list, just check for "if(l)" where l is the list. 2017-07-07 12:21:41 +01:00
Christian T. Jacobs bdd828ddb4 Full stop in a comment line. 2017-07-07 12:21:22 +01:00
Christian T. Jacobs 80f60591b1 Another test of the strip function. 2017-07-07 12:21:00 +01:00
Christian T. Jacobs f4175ba40c Moar comments. 2017-07-06 23:14:28 +01:00
Christian T. Jacobs e1ef6e8c4d Support Python 2.x version of urllib. 2017-07-06 23:09:56 +01:00
Christian T. Jacobs ac888541a5 Add percent-encoding to CHANGELOG. 2017-07-06 22:46:21 +01:00
Christian T. Jacobs 00f4e7d12f Percent encode passwords. 2017-07-06 22:42:29 +01:00
Christian T. Jacobs adf0261bd2 More tests for prefix/suffix removal. 2017-07-06 22:17:24 +01:00
Christian T. Jacobs 59fad31959 Use callsign prefixes specified in Recommendation T/R 61-01. 2017-07-06 22:15:13 +01:00
Christian T. Jacobs 7835dc1ff6 Show an error message if the callsign field is empty. 2017-07-06 21:50:03 +01:00
Christian T. Jacobs 21d5dd21ef Updated CHANGELOG. 2017-07-06 21:43:07 +01:00
Christian T. Jacobs e3f364f085 Ignore empty callsign field when looking up. 2017-07-06 21:23:52 +01:00
Christian T. Jacobs 93d8177932 "iota" not "grid". 2017-07-06 21:23:45 +01:00
Christian T. Jacobs 85fb4f6397 This should be "iota", not "grid". 2017-07-06 21:23:27 +01:00
Christian T. Jacobs aa5094fa6f Use HTTPS when looking up via hamqth.com 2017-07-06 21:09:36 +01:00
Christian T. Jacobs 21e2df09ac Use "not username" instead of username == "" 2017-07-06 21:06:04 +01:00
Christian T. Jacobs c777c924bb Use " not ' for strings. 2017-07-06 21:05:36 +01:00
Christian T. Jacobs 660d993bc1 Assume the user wants a system-wide install. 2017-07-06 00:50:06 +01:00
Christian T. Jacobs 7e28366aae Only use pkg_resources. 2017-07-06 00:41:20 +01:00
Christian T. Jacobs a200eae434 Separate resources for tests and for the pyqso module. 2017-07-06 00:36:17 +01:00
Christian T. Jacobs 74256cd7b5 Re-ordering import statements. 2017-07-06 00:18:47 +01:00
Christian T. Jacobs e3cd2d2e39 More error handling for the task of finding the Glade file. 2017-07-06 00:16:32 +01:00
Christian T. Jacobs d1d053c74d Remove unnecessary "widget=None" arguments. 2017-07-06 00:13:40 +01:00
Christian T. Jacobs dac5c11af9 Use "if(logbook_path)" rather than "if(logbook_path is not None)" since we also don't want to consider the case where logbook_path is an empty string. 2017-07-06 00:11:08 +01:00
Christian T. Jacobs 6a2cc5decf Fall back to assumed directory structure if the Glade file cannot be found using pkg_resources. 2017-07-06 00:08:27 +01:00
Christian T. Jacobs 443d12ab44 Updated running instructions. 2017-07-05 23:53:28 +01:00
Christian T. Jacobs 29aa5b4465 pip3, not pip. 2017-07-05 23:46:47 +01:00
Christian T. Jacobs 1c74cfd71d Re-ordering the README section on installing and running. 2017-07-05 23:08:02 +01:00
Christian T. Jacobs 5cbb43c11c ../ in path. 2017-07-05 22:54:50 +01:00
Christian T. Jacobs c17b4f04fe Use pip3 in Makefile. 2017-07-05 22:34:01 +01:00
Christian T. Jacobs 0b8bae0f9d Install pip3 on Travis. 2017-07-05 22:28:49 +01:00
Christian T. Jacobs 5ab266d168 Try pip3 2017-07-05 22:26:10 +01:00
Christian T. Jacobs 56e07c5f19 Try using easy_install3 with Travis. 2017-07-05 22:15:39 +01:00
Christian T. Jacobs d34f1098aa Added a missing comma. 2017-07-05 22:09:47 +01:00
Christian T. Jacobs 43054154b2 Use setuptools instead of distutils. 2017-07-05 22:06:09 +01:00
Christian T. Jacobs 4a595d7cbe Use the pkg_resources module to find the Glade file for bin/pyqso. Also, don't use "/" to join bits of the path, just give each bit as a separate argument. 2017-07-05 21:50:40 +01:00
Christian T. Jacobs 9e184b9feb Full stops at the end of comment lines. 2017-07-04 19:46:27 +01:00
Christian T. Jacobs 185e8dc104 Comment updates and better error handling. 2017-07-04 17:02:59 +01:00
Christian T. Jacobs a62abf9024 Don't include test databases in data_files. 2017-07-04 17:02:49 +01:00
Christian T. Jacobs 28baab016d Full stop in comment. 2017-07-03 23:43:57 +01:00
Christian T. Jacobs a105afe106 Corrected "Close logbook" shortcut in the documentation. 2017-07-03 23:41:21 +01:00
Christian T. Jacobs 05e6b7da80 Added documentation on how to setup the QTH pinpointing functionality. 2017-07-03 23:38:19 +01:00
Christian T. Jacobs 6d0b02b83e Better error handling. 2017-07-03 22:35:28 +01:00
Christian T. Jacobs a4452f8c17 keyword args. 2017-07-03 21:54:57 +01:00
Christian T. Jacobs 52a8aa8d3f flake8 2017-07-03 21:50:13 +01:00
Christian T. Jacobs 622d180baa Scroll to the new record's row in the treeview (but don't select it) 2017-07-03 21:49:45 +01:00
Christian T. Jacobs b405590fe8 Better error handling. 2017-07-03 21:33:03 +01:00
Christian T. Jacobs 2e074df388 Updated unit tests. 2017-07-03 13:29:08 +01:00
Christian T. Jacobs e34253adb2 Better error handling. 2017-07-03 13:27:12 +01:00
Christian T. Jacobs 3e32142e8a Place the ADIF object outside the 'if' statement. 2017-07-03 01:10:11 +01:00
Christian T. Jacobs 77047d5670 Only create a new log once the records in the ADIF file have been read in. 2017-07-03 00:58:44 +01:00
Christian T. Jacobs 7fee6c42b2 More cases for the unit tests. 2017-07-03 00:50:13 +01:00
Christian T. Jacobs cf72d94035 Better error handling for importing/exporting logs. 2017-07-03 00:43:38 +01:00
Christian T. Jacobs b39d61cf33 Use "yearly" instead. 2017-07-03 00:43:31 +01:00
Christian T. Jacobs 1cd94f5b43 Capital letter. 2017-07-03 00:16:59 +01:00
Christian T. Jacobs b21f46f53c Set frequency unit to "MHz" in the unit test. 2017-07-02 15:24:10 +01:00
Christian T. Jacobs 7214b783b2 Handle empty frequency field separately. 2017-07-02 14:56:39 +01:00
Christian T. Jacobs f3bf4ffc8c Also handle ValueErrors when converting the frequency. This also handles the case of an empty frequency field. 2017-07-02 14:54:42 +01:00
Christian T. Jacobs 70cf060d66 Remove unused logging module import. 2017-06-30 12:32:07 +01:00
Christian T. Jacobs 2ddfc2d061 Removed unnecessary debugging statements. 2017-06-30 12:30:35 +01:00
Christian T. Jacobs f3a7888183 Added more links and updated documentation. 2017-06-30 12:29:58 +01:00
Christian T. Jacobs b099111218 Print logs on a landscape page. Also improved the page layout. 2017-06-28 20:23:31 +01:00
Christian T. Jacobs c00e0a7ecb Fixed direction of sorting. 2017-06-28 16:22:53 +01:00
Christian T. Jacobs 67d2050156 Improved comments. 2017-06-27 23:13:09 +01:00
Christian T. Jacobs 4becec41ed Better error handling for the case where a log is not selected. 2017-06-27 22:41:00 +01:00
Christian T. Jacobs b91c77f07b Consider key-press-event not key-release-event. 2017-06-27 22:04:32 +01:00
Christian T. Jacobs 7055f4f67d Added 'record count' feature. 2017-06-27 21:13:59 +01:00
Christian T. Jacobs f816554816 More unit tests and docstrings. 2017-06-27 20:10:40 +01:00
Christian T. Jacobs 66ecabd737 Updated CHANGELOG. 2017-06-27 20:10:32 +01:00
Christian T. Jacobs 2d42acde9c Fixed the QSO index used in the Gtk.ListStore. Just before a QSO is added with add_record it was assumed that it's index would be max(rowid)+1, which is not always the case. This led to inconsistencies between the Gtk.ListStore and the database. Indices used in the Gtk.ListStore are now obtained directly from the database after insertion. Addresses issue #56. 2017-06-27 20:10:20 +01:00
Christian T. Jacobs f3bacf9dc7 Don't pass None, None to edit_dialog - leave that up to the defaults in the keyword arguments. 2017-06-27 20:05:28 +01:00
Christian T. Jacobs 7f6c94982a More docstrings. 2017-06-27 20:04:45 +01:00
Christian T. Jacobs 879e49b496 Call logging.info rather than logging.debug in the 'info' auxiliary dialog function. 2017-06-27 20:03:44 +01:00
Christian T. Jacobs 4f61570828 Add logging statements for importing/exporting in ADIF format. 2017-06-27 20:03:06 +01:00
Christian T. Jacobs 6b7d42e6dd Show an error dialog if the printing operation is not successful. 2017-06-27 20:02:05 +01:00
Christian T. Jacobs 9a1371390e Full stops. 2017-06-25 16:58:20 +01:00
Christian T. Jacobs 75a8f0ce50 Duplicates are now defined by the CALL, QSO_DATE and TIME_ON fields. Didn't seem necessary to also consider FREQ and MODE. 2017-06-25 15:52:05 +01:00
Christian T. Jacobs 65a3fe68d9 Remove day, month and year from the Calendar widget in Glade to allow the calendar to default to the current date. 2017-06-25 14:22:54 +01:00
Christian T. Jacobs be7ad3bf1f Ignore test files with .gitignore. 2017-06-24 22:29:31 +01:00
Christian T. Jacobs 181312b2bc Re-order menu setup. 2017-06-24 22:27:51 +01:00
Christian T. Jacobs 4cf5a56c7e Move the Preferences menu item to the Logbook menu. 2017-06-24 22:24:00 +01:00
Christian T. Jacobs 3f467b2977 Clear out test files. 2017-06-24 22:00:58 +01:00
Christian T. Jacobs 7b1c452f3e Renaming tests for consistency reasons. 2017-06-24 21:31:21 +01:00
Christian T. Jacobs 5c1d3aeef0 flake8. 2017-06-24 21:03:31 +01:00
Christian T. Jacobs a09d5ab1ce More unit testing. 2017-06-24 20:56:04 +01:00
Christian T. Jacobs 459322689a Remove unnecessary imports. 2017-06-24 18:57:53 +01:00
Christian T. Jacobs 4478e117fa Added a Hamlib-based unit test. 2017-06-24 18:56:46 +01:00
Christian T. Jacobs b59d543dd2 The 'mode' is actually an int, so use Hamlib.rig_strrmode(mode) to convert it to its string representation. 2017-06-24 18:12:27 +01:00
Christian T. Jacobs 60a26bb2fa Comment update. 2017-06-24 18:04:21 +01:00
Christian T. Jacobs 34625292e2 ".lib" -> ".libs" 2017-06-24 18:04:08 +01:00
Christian T. Jacobs f29ece0033 Enforce an absolute logbook file path. 2017-06-24 17:27:10 +01:00
Christian T. Jacobs 73f785af7c flake8 2017-06-24 16:50:51 +01:00
Christian T. Jacobs 43b647b19e Added test database files in setup.py. 2017-06-24 16:50:30 +01:00
Christian T. Jacobs e407b9b3a1 Added the invalid database file for testing purposes. 2017-06-24 16:49:47 +01:00
Christian T. Jacobs 8bf0895da7 flake8 2017-06-24 16:41:33 +01:00
Christian T. Jacobs 69abd30027 Added a test for the Printer class. Note that this only checks that a PDF has actually been created. It does not check the contents of the PDF file. 2017-06-24 16:37:51 +01:00
Christian T. Jacobs 9a8fedf475 Use group: deprecated-2017Q2 to work-around the Travis build failures. 2017-06-24 15:38:38 +01:00
Christian T. Jacobs 6b1caa1a3c More unittests. 2017-06-24 15:08:20 +01:00
Christian T. Jacobs db1c050b78 Fix new logbook functionality by changing "if(not self.logs)" to "if(self.logs is None)", since the case of an empty log list should be handled in the 'else' branch. 2017-06-13 21:17:54 +01:00
Christian T. Jacobs a1d5640be3 Updated caption. 2017-06-12 12:13:11 +01:00
Christian T. Jacobs 55d2af808d Update caption. 2017-06-12 12:11:49 +01:00
Christian T. Jacobs 50f01bf3ca Updated screenshots. 2017-06-11 22:04:47 +01:00
Christian T. Jacobs 3ef2057dbe Indent code blocks. 2017-05-30 14:50:19 +01:00
Christian T. Jacobs 3754f2347e Also add in Hamlib-related PYTHONPATH information. 2017-05-30 14:46:23 +01:00
Christian T. Jacobs 490fda7128 Added the instructions for building and installing Hamlib bindings for Python 3. 2017-05-30 14:40:37 +01:00
Christian T. Jacobs 803a5d4430 Don't pad the statistics frame. 2017-05-30 13:20:47 +01:00
Christian T. Jacobs 9813344c58 Append PyQSO directory to path. 2017-05-30 13:09:17 +01:00
Christian T. Jacobs b698900fe5 Improved the QTH labelling on the grey line map. 2017-05-17 18:12:53 +01:00
Christian T. Jacobs 15f38b4c43 Remove some unnecessary calls to logging.error. 2017-05-17 17:36:33 +01:00
Christian T. Jacobs d5ff95edb1 Use a file chooser dialog to let the user find and set the default logbook file. 2017-05-17 17:18:05 +01:00
Christian T. Jacobs efb1f38e9a Updates to documentation. 2017-05-16 23:24:06 +01:00
Christian T. Jacobs 8213b32b0a Added a note for contesters regarding exporting to a Cabrillo file. 2017-05-16 18:40:01 +01:00
Christian T. Jacobs f6b029a269 Specify Python version 3.x in getting_started.rst. 2017-05-16 18:23:53 +01:00
Christian T. Jacobs 9efba69648 Mention amateur satellite contacts as well. 2017-05-16 17:57:29 +01:00
Christian T. Jacobs 49b544b463 Indent. 2017-05-09 17:31:32 +01:00
Christian T. Jacobs bce1f98776 Move the Telnet connection code to its own class. 2017-05-09 17:26:25 +01:00
Christian T. Jacobs 500e3f6266 Remove an old TODO. 2017-05-09 17:26:12 +01:00
Christian T. Jacobs 904d02ce23 Updated TODO. 2017-05-09 17:25:58 +01:00
Christian T. Jacobs b9fb712f16 Docstrings in the PreferencesDialog class. 2017-05-09 17:25:45 +01:00
Christian T. Jacobs 69b4333e2a Change invisible character to * 2017-05-09 17:25:27 +01:00
Christian T. Jacobs da9b31ea10 Fix DX cluster menu and update ellipsis in menu items. 2017-05-08 10:19:09 +01:00
Christian T. Jacobs bba65693ca Better error handling. 2017-05-07 16:38:36 +01:00
Christian T. Jacobs 37df41e93c Mention tooltips in the CHANGELOG. 2017-05-07 14:10:21 +01:00
Christian T. Jacobs 9f86e190ce Updated CHANGELOG. 2017-05-07 14:09:00 +01:00
Christian T. Jacobs bb4fa2a09c Add the option of a default frequency unit in the Preferences. Addresses issue #12. 2017-05-07 14:01:28 +01:00
Christian T. Jacobs 40d6869ef9 More tooltips. 2017-05-07 13:49:25 +01:00
Christian T. Jacobs 34dcc61b6f Added functionality for converting the frequency from one unit to another (e.g. from MHz to kHz). Partially addresses issue #12. 2017-05-07 01:44:58 +01:00
Christian T. Jacobs a11f7d275a Define "E" in adif.py. 2017-04-24 17:45:55 +01:00
Christian T. Jacobs b2b20a2edc Added another test for the autocomplete_band method. 2017-04-24 17:28:30 +01:00
Christian T. Jacobs 71e365ea22 Remove an unnecessary mock'd class. 2017-04-24 17:26:09 +01:00
Christian T. Jacobs a97993d7ae Added a test for the autocomplete_band method. 2017-04-24 17:23:20 +01:00
Christian T. Jacobs 2561f29fcc Added Cabrillo test files to 'make clean' 2017-04-24 17:06:33 +01:00
Christian T. Jacobs 6d978202f4 Include Cabrillo test file in .gitignore. 2017-04-24 17:05:33 +01:00
Christian T. Jacobs bd08213bd8 Added a test to check the correctness of the Cabrillo class' write method. 2017-04-24 17:04:29 +01:00
Christian T. Jacobs 8ccff558da Set submode to "". 2017-04-24 17:02:41 +01:00
Christian T. Jacobs aebab3eca7 Specify "model=". 2017-04-24 17:01:47 +01:00
Christian T. Jacobs 4276b544bc If the MODE is changed, then set the submode to an empty string. 2017-04-24 17:01:18 +01:00
Christian T. Jacobs 7c263c9fe2 Added "More unit tests" to the CHANGELOG. 2017-04-23 20:19:10 +01:00
Christian T. Jacobs 6b069e280e Added a unit test for the get_log_index method. 2017-04-23 20:04:38 +01:00
Christian T. Jacobs 3288a1f47d Combine a comment. 2017-04-23 20:00:19 +01:00
Christian T. Jacobs ae352f790d Comments. 2017-04-23 19:59:31 +01:00
Christian T. Jacobs 108f6850eb "result" -> "present" 2017-04-23 19:50:53 +01:00
Christian T. Jacobs 0ba9a6e3e0 flake8. 2017-04-23 19:50:08 +01:00
Christian T. Jacobs caff4ca18d Unit test for the filter_by_callsign method. 2017-04-23 19:43:19 +01:00
Christian T. Jacobs 911c3f2309 Docstrings. 2017-04-23 14:44:35 +01:00
Christian T. Jacobs 39ca881e2e Added tests for the comparison routines. 2017-04-23 14:37:59 +01:00
Christian T. Jacobs fda54fe070 Added a test for the CalendarDialog class. 2017-04-21 00:19:40 +01:00
Christian T. Jacobs 879db074c9 Docstring correction. 2017-04-20 23:56:12 +01:00
Christian T. Jacobs 110e5fe700 This should be "parent" not "application". 2017-04-20 23:55:56 +01:00
Christian T. Jacobs 868d7b2c9c Updated docstring. 2017-04-20 23:35:03 +01:00
Christian T. Jacobs 3809b4b852 Added a test for the Awards class. 2017-04-20 23:24:50 +01:00
Christian T. Jacobs 9194a71a99 homogeneous, spacing. 2017-04-20 23:10:06 +01:00
Christian T. Jacobs a6aa5813f5 Rename get_all_records to records and decorate it. 2017-04-20 22:57:17 +01:00
Christian T. Jacobs 8d8276ff33 Added tests for the Summary class. 2017-04-20 22:50:08 +01:00
Christian T. Jacobs 41acc8be30 Use new_log_name for consistency. 2017-04-15 01:37:52 +01:00
Christian T. Jacobs de85e53c64 Updated CHANGELOG. 2017-04-15 01:31:13 +01:00
Christian T. Jacobs 886cf159ec Updated pyqso.rst. 2017-04-15 01:23:20 +01:00
Christian T. Jacobs 39aa303959 Importing the modules required for the unit tests. 2017-04-15 01:19:44 +01:00
Christian T. Jacobs 3a5a1525a5 Moved all the unittests to a new directory called 'tests'. The command 'make test' now looks in the 'tests' directory. 2017-04-15 01:14:17 +01:00
Christian T. Jacobs 0953a2e431 Added log renaming test. 2017-04-15 01:08:40 +01:00
Christian T. Jacobs 64cb2b2c15 Comment updates. 2017-04-15 00:59:21 +01:00
Christian T. Jacobs 331d80a060 Create a new method called "rename" in the Log class. 2017-04-15 00:55:52 +01:00
Christian T. Jacobs 9a6a1a24ae Use a Gtk.Paned widget to allow the Toolbox to be resized. 2017-04-15 00:02:13 +01:00
Christian T. Jacobs c53c7ab9a3 Moved the blank/dummy page to blank.py 2017-04-14 23:14:27 +01:00
Christian T. Jacobs 68dfa0f9d6 Remove 'self' argument. 2017-04-14 22:22:52 +01:00
Christian T. Jacobs 7df20bd28b "find" -> "get". 2017-04-14 22:03:28 +01:00
Christian T. Jacobs 2a33f97505 Corrected rtypes. 2017-04-14 22:02:16 +01:00
Christian T. Jacobs 78033f9a01 Remove _ in front of methods for consistency reasons. 2017-04-14 21:45:59 +01:00
Christian T. Jacobs f122e3cfde More docstrings. 2017-04-14 21:38:42 +01:00
Christian T. Jacobs ae304e7fa9 Moving Summary page over to Glade. 2017-04-14 21:33:16 +01:00
Christian T. Jacobs 12ae7195f4 Moving code out of logbook.py into compare.py and summary.py. The functionality includes the Summary page and functions for comparing log records. 2017-04-14 19:48:09 +01:00
Christian T. Jacobs 522e461dee More tests. 2017-04-11 23:40:06 +01:00
Christian T. Jacobs eb263e9ea4 Added printer module. 2017-04-11 23:39:58 +01:00
Christian T. Jacobs c3bce781f1 Rename to record_count and log_count, and use decorators. 2017-04-11 23:06:44 +01:00
Christian T. Jacobs fa96db7219 Rename to print_records. 2017-04-11 22:53:51 +01:00
Christian T. Jacobs a3b3568d48 Move the log printing functionality to a new Printer class, defined in printer.py. 2017-04-11 22:47:16 +01:00
Christian T. Jacobs db80fac9fe Updated documentation following the addition of new features. 2017-04-10 23:32:25 +01:00
Christian T. Jacobs 93e76b9b84 Move test.db to the 'res' directory. 2017-04-05 23:18:23 +01:00
Christian T. Jacobs 0cdd59f3ef Always show callsigns in upper case. 2017-04-05 22:58:02 +01:00
Christian T. Jacobs 35922cd493 Moved the CabrilloExportDialog class to a separate file. 2017-04-05 22:54:26 +01:00
Christian T. Jacobs eb4672f73c Added Cabrillo support to the CHANGELOG. 2017-04-05 22:46:01 +01:00
Christian T. Jacobs 6407c4a9cc More work on the Cabrillo exporting functionality.
Added a dialog that allows the user to specify the callsign used during a contest, and the contest's name.
2017-04-05 22:42:43 +01:00
Christian T. Jacobs 76b673475e Moved Glade file and icon files to a new directory called 'res'. 2017-04-02 14:02:40 +01:00
Christian T. Jacobs 9e73b2abfa Set CABRILLO_VERSION instead. 2017-04-01 23:19:49 +01:00
Christian T. Jacobs 5454c8e296 Flake8. 2017-04-01 23:18:05 +01:00
Christian T. Jacobs 2d30163e7d Created a Cabrillo class for writing out QSO records to a file in Cabrillo format. This is a work-in-progress. 2017-04-01 23:07:52 +01:00
Christian T. Jacobs 74b393e0e1 Fixed comment. 2017-04-01 23:07:47 +01:00
Christian T. Jacobs 315997c1e5 Use " not ' in setup.py 2017-04-01 21:36:59 +01:00
Christian T. Jacobs 8a07c26fec Update unit test. 2017-04-01 18:17:08 +01:00
Christian T. Jacobs 531749270c Perform an initial count for the awards table. 2017-04-01 18:10:24 +01:00
Christian T. Jacobs c10abde42a Updated comment. 2017-04-01 17:55:03 +01:00
Christian T. Jacobs efc5f80be8 Updated CHANGELOG. 2017-04-01 17:54:58 +01:00
Christian T. Jacobs 0b63338367 Bumped up the version to 1.0.0. 2017-04-01 16:12:46 +01:00
Christian T. Jacobs 988cf6e854 Merge pull request #54 from ctjacobs/glade
Added Glade design of main window and dialogs. Addresses issue #47.
2017-04-01 15:54:05 +01:00
Christian T. Jacobs a3bf4d9c8e Added Glade design to CHANGELOG. 2017-04-01 15:47:04 +01:00
Christian T. Jacobs 6c782094e7 Fix instantiation of RecordDialog when editing a record. 2017-04-01 15:43:55 +01:00
Christian T. Jacobs 7a2aa12e47 Use a comma rather than placing my callsign in brackets after my name. 2017-04-01 15:20:33 +01:00
Christian T. Jacobs 3caf3f9274 flake8 2017-04-01 14:58:06 +01:00
Christian T. Jacobs 1f4f95bcba Connecting up the Preferences dialog. 2017-04-01 14:57:17 +01:00
Christian T. Jacobs 10d0b9d462 Rename "parent" -> "application". 2017-03-31 10:31:30 +01:00
Christian T. Jacobs 2565a7512d Renaming "parent" to "application". 2017-03-31 10:28:26 +01:00
Christian T. Jacobs 75a65891a9 "builder" -> "application". 2017-03-31 10:21:43 +01:00
Christian T. Jacobs 183d1c9d8d Rename "parent" to "application". 2017-03-31 10:06:11 +01:00
Christian T. Jacobs 2ef087c202 Added the View tab of the Preferences dialog in Glade. 2017-03-30 16:45:09 +01:00
Christian T. Jacobs e10a25bccf Added Hamlib tab in the Preferences dialog in Glade. 2017-03-30 08:16:23 +01:00
Christian T. Jacobs 66d3f45be8 Added the Records tab of the Preferences dialog in Glade. 2017-03-30 08:08:23 +01:00
Christian T. Jacobs d78f0f74d7 Added ADIF preferences in Glade. 2017-03-22 23:07:40 +00:00
Christian T. Jacobs b9c15c0e92 Include my middle name in the copyright lines and authors list. Also use my new callsign. 2017-03-20 13:06:01 +00:00
Christian T. Jacobs 9c954373b0 Added General tab of the Preferences dialog in Glade. 2017-03-16 18:34:06 +00:00
Christian T. Jacobs 95bad0fe72 Added the start of the Preferences dialog in Glade. 2017-03-11 23:26:52 +00:00
Christian T. Jacobs 36de2328c4 If the Return key is pressed in the RecordDialog, record the QSO details. Addresses issue #53. 2017-03-02 10:45:49 +00:00
Christian T. Jacobs a6d5839527 Fixed auxiliary dialog calls. 2017-03-02 10:14:21 +00:00
Christian T. Jacobs 296997ec4e Fixed unit test in logbook.py. 2017-03-02 09:56:45 +00:00
Christian T. Jacobs 09a2d3e78b Connected up the record dialog. 2017-03-01 10:16:03 +00:00
Christian T. Jacobs 60bfb3520e Added the About dialog box in Glade. 2017-03-01 00:59:27 +00:00
Christian T. Jacobs 005d5385b4 Added the Glade version of the RecordDialog. 2017-03-01 00:40:17 +00:00
Christian T. Jacobs d5e0f2e007 Import mock. 2017-02-24 00:32:59 +00:00
Christian T. Jacobs 00a86c57bc flake8. 2017-02-24 00:27:03 +00:00
Christian T. Jacobs 1eea1d5917 Renaming calendar.py to calendar_dialog.py to avoid naming conflicts. Also moved LogName to its own file log_name_dialog.py once again. 2017-02-24 00:20:43 +00:00
Christian T. Jacobs e168a417d1 flake8 2017-02-24 00:11:20 +00:00
Christian T. Jacobs 7fdedc51b4 Spacing. 2017-02-24 00:05:42 +00:00
Christian T. Jacobs f19d99b92c Moved the Calendar class to its own separate file (calendar.py). 2017-02-24 00:04:54 +00:00
Christian T. Jacobs cbe93856b4 Added the CalendarDialog to Glade. 2017-02-24 00:04:40 +00:00
Christian T. Jacobs b89acae882 Removed the old log_name_dialog.py file. Moved the LogName class to log.py. 2017-02-23 23:38:29 +00:00
Christian T. Jacobs 0c3f76deb8 Destroy dialog windows, but use add_objects_from_file to rebuild them in the existing Gtk.Builder object. 2017-02-23 22:40:47 +00:00
Christian T. Jacobs e04b604bf1 Small fixes. 2017-02-21 20:41:53 +00:00
Christian T. Jacobs 6a8c2c1798 Remove useless code. 2017-02-21 19:38:59 +00:00
Christian T. Jacobs 3f0995086b Mock Gtk.Builder class. 2017-02-21 19:37:24 +00:00
Christian T. Jacobs 03eeb614ae Move Logbook class over to Glade constructs. 2017-02-21 19:36:25 +00:00
Christian T. Jacobs 6dc8488e00 flake8 2017-02-21 19:27:23 +00:00
Christian T. Jacobs f266e6def8 More moving of toolbar over to Glade. 2017-02-21 19:16:13 +00:00
Christian T. Jacobs fdc3a5f051 Moving the toolbar over to Glade. 2017-02-21 18:48:50 +00:00
Christian T. Jacobs be1ae2af4d Don't pass in the parent PyQSO window into all the tools. 2017-02-21 18:16:02 +00:00
Christian T. Jacobs 7cd34fb59a Fix re-drawing of grey line on tab change. 2017-02-21 17:57:47 +00:00
Christian T. Jacobs 0456d1b3ec Fixed DX cluster unit test. 2017-02-21 17:48:42 +00:00
Christian T. Jacobs f976d840e2 flake8 2017-02-21 16:47:35 +00:00
Christian T. Jacobs 7b3f8d067b Moving the menu bar over to Glade. 2017-02-21 16:45:58 +00:00
Christian T. Jacobs 98cfa7b9e1 Added the LogNameDialog in Glade. 2017-02-21 15:28:55 +00:00
Christian T. Jacobs 3eb3275d35 Porting toolbox tools over to Glade. 2017-02-21 14:54:04 +00:00
Christian T. Jacobs 304d35fe0f flake8 2017-02-15 23:21:11 +00:00
Christian T. Jacobs e977bc5e0f flake8 2017-02-15 23:19:22 +00:00
Christian T. Jacobs c9ffb5e11e More work on using Glade. Also bumped the version to 1.0.0 (in development). 2017-02-15 23:17:51 +00:00
Christian T. Jacobs 295eb79b91 Consolidating all glade files into a single project. 2017-02-15 19:25:08 +00:00
Christian T. Jacobs ba6b570583 Created the Telnet connection dialog in Glade, and hooked it up to the DX cluster. 2017-02-15 18:04:49 +00:00
Christian T. Jacobs 389ab91072 Added the start of the main window, toolbox and DX cluster frame designed with Glade. 2017-02-12 23:25:53 +00:00
Christian T. Jacobs 8d219a25da Updated CHANGELOG. 2017-02-10 19:05:58 +00:00
Christian T. Jacobs c8c9ae681e Linting. 2017-02-10 18:55:42 +00:00
Christian T. Jacobs 5cc525c5c7 Updated copyright year. 2017-02-10 18:54:21 +00:00
Christian T. Jacobs d70762ae01 Pin-point QTH on grey line map. Addresses issue #42. 2017-02-10 18:50:34 +00:00
Christian T. Jacobs 9baf2aaddd Use username and port information (in addition to hostname) when creating an identifier for a DX cluster bookmark. Addresses issue #43. 2017-02-08 16:36:56 +00:00
Christian T. Jacobs abaa467a88 Bumped version to 0.4. 2017-02-08 15:47:52 +00:00
Christian T. Jacobs ce46c14096 Replace any characters that cannot be decoded with a replacement marker in the DX cluster frame. Addresses issue #45. 2017-02-07 20:33:41 +00:00
Christian T. Jacobs 08d21627e2 If the Return key is pressed when the focus is on the command box, then send whatever command the user has entered. Addresses issue #44. 2017-02-07 17:22:06 +00:00
Christian T. Jacobs e733af215e Flake8. 2017-02-07 16:43:11 +00:00
Christian T. Jacobs 1e185318f7 Allow the user to specify a default logbook that should be opened, if desired. Addresses issue #48. 2017-02-07 16:39:43 +00:00
Christian T. Jacobs 79d3451d56 Use has_option here. 2017-02-07 16:24:16 +00:00
Christian T. Jacobs 2524cd5d94 Move Hamlib autofill code to its own function. 2017-02-07 15:54:34 +00:00
Christian T. Jacobs df27c359ac Also auto-fill the Mode field using Hamlib, if desired. Addresses issue #49. 2017-02-07 15:31:16 +00:00
Christian T. Jacobs 948f1260cd Merge pull request #51 from ctjacobs/python2-support
Continue to support Python 2.x modules
2017-02-07 14:44:37 +00:00
Christian T. Jacobs a65e34db65 Continue to support Python 2.x modules. Thanks to @gaionim (IU2HDS) for this patch. Fixes issue #50. 2017-02-07 14:17:14 +00:00
Christian T. Jacobs 4124c4c040 Fixed CHANGELOG tag and link. 2016-05-28 20:58:36 +01:00
Christian T. Jacobs 047cea4cf5 Release changes as 0.3. 2016-05-28 20:35:24 +01:00
Christian T. Jacobs 426c2dac29 Updated copyright notices. 2016-05-28 20:32:00 +01:00
Christian T. Jacobs a6edcf1fd6 Updated version. 2016-05-28 19:36:25 +01:00
Christian T. Jacobs 709d15af8b "log" -> "logbook". 2016-05-28 19:32:53 +01:00
Christian T. Jacobs 72485d3bc7 Added a screenshot of the Summary page/tab. 2016-05-28 19:22:41 +01:00
Christian T. Jacobs 520ffb79de Updated DX cluster screenshot. 2016-05-28 19:14:57 +01:00
Christian T. Jacobs 591ac35bb5 Updated screenshots for the documentation. 2016-05-28 19:09:34 +01:00
Christian T. Jacobs 4c18f2099b Fix mode count. 2016-05-28 17:12:10 +01:00
Christian T. Jacobs 9456476961 Added contact info in the documentation. 2016-05-28 17:04:39 +01:00
Christian T. Jacobs b9901196db Changed canvas size to 800 x 250. 2016-05-28 16:56:37 +01:00
Christian T. Jacobs 238564d044 Specify parent window. 2016-05-28 16:29:47 +01:00
Christian T. Jacobs b29eebe0b4 Convert from dict_keys to list. 2016-05-28 16:24:37 +01:00
Christian T. Jacobs b52ec714a7 More updates. 2016-05-28 15:11:40 +01:00
Christian T. Jacobs 7e0c3f581b Updated dependencies section of the README. 2016-05-28 15:10:58 +01:00
Christian T. Jacobs 9bc16c35e9 Documentation updates. 2016-05-28 14:46:07 +01:00
Christian T. Jacobs 1abf785d0e flake8 fixes. 2016-05-28 14:23:31 +01:00
Christian T. Jacobs 662ebb3c06 Update the documentation to refer to 'python3'. 2016-05-28 14:19:28 +01:00
Christian T. Jacobs 9ddaa56b73 Make this option clearer. 2016-05-28 14:19:19 +01:00
Christian T. Jacobs 4b96f9591d Update contact email address. 2016-01-30 00:18:46 +00:00
Christian T. Jacobs 1c6a4d518a Use @echo. 2016-01-27 20:28:50 +00:00
Christian T. Jacobs 82cfacc63b Updating CHANGELOG to include PEP 8 compliance. 2016-01-27 18:44:54 +00:00
Christian T. Jacobs 8b5ea87b79 Flake8 fixes. 2016-01-27 18:15:06 +00:00
Christian T. Jacobs 03d322df21 Run flake8 in before_script. 2016-01-27 18:12:55 +00:00
Christian T. Jacobs 7d68b0aa73 Don't test with flake8 in 'make test'. 2016-01-27 18:12:26 +00:00
Christian T. Jacobs f24cb30c82 Exclude more directories from flake8. 2016-01-27 17:17:03 +00:00
Christian T. Jacobs 0e62c91380 Also install python3-flake8. 2016-01-27 16:58:42 +00:00
Christian T. Jacobs d02239bd30 Consistency in Makefile. 2016-01-27 16:49:15 +00:00
Christian T. Jacobs b29f0e54ca Added a tox.ini file with flake8 settings. 2016-01-27 16:48:19 +00:00
Christian T. Jacobs ad938a3d9a Also run flake8 checks. 2016-01-27 16:33:30 +00:00
Christian T. Jacobs c993704e84 Make the code pep8 compliant, using the autopep8 tool. Note that we are ignoring the following: E501,F403,E226,E402,W503. 2016-01-27 16:23:09 +00:00
Christian T. Jacobs 1e5a657ca7 Merge pull request #41 from ctjacobs/keep-open
Keep the 'Add Record' dialog open
2016-01-24 21:31:29 +00:00
Christian Jacobs 1c47846289 Keep the 'Add Record' dialog open after adding a new QSO, if the user wants this. 2016-01-24 21:29:35 +00:00
Christian T. Jacobs 5f7056ed53 Merge pull request #40 from ctjacobs/summary-graph
Annual statistics
2016-01-24 16:53:48 +00:00
Christian Jacobs 98f27a36e2 Collect contacts together by month in the bar chart. 2016-01-24 16:48:10 +00:00
Christian Jacobs 6de0a1f451 Change to have_matplotlib. 2016-01-24 15:33:15 +00:00
Christian Jacobs 56b476e66d Only try to plot statistics if the necessary matplotlib module exists. 2016-01-24 15:31:15 +00:00
Christian Jacobs 23a325367c Handle unspecified modes. 2016-01-24 15:22:33 +00:00
Christian Jacobs cc436c4a42 Handle empty logs. 2016-01-24 15:19:51 +00:00
Christian Jacobs f03f31c65b Hook the statistics up to the preferences. 2016-01-24 15:12:14 +00:00
Christian Jacobs c610b9f13e Only show the progress up to the end of the current month. 2016-01-24 15:05:02 +00:00
Christian Jacobs 76f038a39b Replot statistics for a user-specified year. 2016-01-24 14:50:42 +00:00
Christian Jacobs a5f4d80654 Only perform one SQL query. 2016-01-24 02:08:40 +00:00
Christian Jacobs 608007d616 Add a combo box to select which year we want PyQSO to generate statistics for. 2016-01-24 02:03:48 +00:00
Christian Jacobs 3d40955b36 Make the statistics an option in the Preferences. 2016-01-23 00:26:55 +00:00
Christian Jacobs 524c6a0054 Use matplotlib.dates to do the plotting of the QSO count. 2016-01-22 20:36:50 +00:00
Christian Jacobs b9ce2153de Started to add graphs to the Summary page of the logbook. 2016-01-11 19:29:42 +00:00
Christian Jacobs 07274c6f60 Use gtk3cairo backend. 2016-01-11 19:29:34 +00:00
Christian Jacobs 7c173206e1 Wrap os.makedirs in a try-except block. 2015-11-29 22:34:48 +00:00
Christian Jacobs a115e0f27d Update the path to the preferences file in the documentation. 2015-11-29 22:26:48 +00:00
Christian Jacobs 7d941ce2fe Write configuration files to ~/.config to keep the user's home directory uncluttered. 2015-11-29 22:25:41 +00:00
Christian Jacobs cc933a3a9c Merge pull request #36 from ctjacobs/cluster-bookmarks
DX cluster bookmarking
2015-11-28 17:18:37 +00:00
Christian Jacobs 2a66389dc3 Store the bookmarks file path in BOOKMARKS_FILE. 2015-11-28 16:55:28 +00:00
Christian Jacobs 3b72e0773b Update CHANGELOG. 2015-11-28 16:47:19 +00:00
Christian Jacobs efbc51d6bf Use "label=" in MenuItem to avoid deprecation warnings. 2015-11-28 16:42:43 +00:00
Christian Jacobs d6588c5761 Implement bookmarking. 2015-11-28 16:41:23 +00:00
Christian Jacobs 362c9fa5e5 Split up the "Connect" menu into "New..." and "From Bookmark". 2015-11-28 14:53:33 +00:00
Christian Jacobs e1e4784a07 Let's call this the command box instead. 2015-11-28 14:42:57 +00:00
Christian Jacobs 6f7d15cb33 Use a MenuBar instead of a row of buttons in the DX cluster tool. 2015-11-28 14:36:18 +00:00
Christian Jacobs 4164977747 If there is an encoding error when writing/reading a character to/from an ADIF file, then replace the character with a replacement marker. 2015-11-23 20:22:35 +00:00
Christian Jacobs 04305bfd42 Added classifiers to the setup.py metadata. 2015-11-23 00:04:13 +00:00
Christian Jacobs 8a70fbc369 Unit tests for the DXCluster class. 2015-11-22 23:04:02 +00:00
Christian Jacobs 05664b4f04 Moar docstrings. 2015-11-22 23:03:48 +00:00
Christian Jacobs ea8777841a Added more unit tests for qrz.com and hamqth.com lookups. 2015-11-22 21:54:20 +00:00
Christian Jacobs f9fdc32891 Fixed Telnet DX cluster functionality following the move to Python 3. This involved encoding/decoding from str/bytes. 2015-11-22 01:16:08 +00:00
Christian Jacobs 2fcdc4833c Remove old print statement. 2015-11-22 00:50:51 +00:00
Christian Jacobs dcd94634e8 Remove the deprecated_mode method. 2015-11-22 00:50:29 +00:00
Christian Jacobs 4b1f83eeef Comment updates. 2015-11-22 00:46:56 +00:00
Christian Jacobs 534166bb9c Updated CHANGELOG. 2015-11-22 00:44:30 +00:00
Christian Jacobs 905c352af0 Included deprecated MODE values, and included the 630m band in the BANDS list.
Also bumped the ADIF version to 3.0.4.
2015-11-22 00:39:06 +00:00
Christian Jacobs e957ae5864 Fixes following the move to Python 3. Also added a default Submode field in the Preferences dialog. 2015-11-17 01:03:59 +00:00
Christian Jacobs ef9ca21ccb Add a Submode field to the Record dialog. 2015-11-17 01:03:50 +00:00
Christian Jacobs de01ceefdf Added empty strings to the tuples containing the SUBMODES. Also added a method to 'update' a deprecated mode. 2015-11-17 01:02:11 +00:00
Christian Jacobs 07954c18a8 Updated the list of MODES and their corresponding SUBMODES. Note that this list is now actually a dictionary - see the comment. 2015-11-16 21:26:14 +00:00
Christian Jacobs 2b029d16e3 Use my new Intermediate Licence callsign, 2E0ICL. 2015-11-05 00:23:23 +00:00
njohnsn fc94c8d511 Convert to Python 3 using 2to3.
Also update Travis CI settings for Python 3, add new package dependencies and update the documentation.
2015-11-05 00:23:19 +00:00
Christian Jacobs 02d7b5446a Autogenerate the PyQSO module documentation. 2015-10-04 01:04:05 +01:00
Christian Jacobs 6ceac47c9a Also mention hamqth.com in the features list. 2015-10-04 00:55:04 +01:00
Christian Jacobs ce900209b0 Generalise the callsign lookup button and documentation, since PyQSO now also supports hamqth.com. 2015-10-04 00:52:53 +01:00
Christian Jacobs 394dc1a345 Removed more unused imports. 2015-10-04 00:35:48 +01:00
Christian Jacobs 0cb85b0bb6 Updated the change log. 2015-10-04 00:33:32 +01:00
Christian Jacobs 165edd5023 Bumped the version number to 0.3(-dev). 2015-10-04 00:32:00 +01:00
Christian Jacobs 45abb28e38 Improved docstrings. 2015-10-04 00:16:55 +01:00
Christian Jacobs bf26af984d Merge pull request #32 from dnet/cleanup2015930
Cleanup
2015-10-01 18:37:38 +01:00
Christian Jacobs 794d999587 lastrowid only gets set *after* issuing an INSERT statement, but PyQSO needs the index of the last row beforehand. Therefore, determine the index of the last row using a SELECT statement instead. 2015-10-01 18:27:11 +01:00
András Veres-Szentkirályi 7d8b702bce auxiliary_dialogs: extracted common dialog code 2015-09-30 12:03:07 +02:00
András Veres-Szentkirályi e92c294dd4 use datetime.strftime instead of manual formatting 2015-09-30 11:53:40 +02:00
András Veres-Szentkirályi 9094d197e9 simplified increment syntax 2015-09-30 11:48:44 +02:00
András Veres-Szentkirályi 5054c99e7c simplified logbook loading 2015-09-30 11:43:49 +02:00
András Veres-Szentkirályi 3f9434cd2e removed unread variables 2015-09-30 10:57:11 +02:00
András Veres-Szentkirályi 500ca5977a removed unused imports 2015-09-30 10:56:56 +02:00
Christian Jacobs 37685c9a4c When calling add_record with multiple records in a list, insert all the records in one go using executemany.
This seems to bring a significant performance benefit, and addresses issue #29.
2015-08-12 00:58:00 +01:00
Christian Jacobs c6002fbd7d Match *.ADI files too. 2015-08-11 17:31:51 +01:00
Christian Jacobs e567c7a077 Corrected a typo in the CHANGELOG. 2015-05-04 23:24:46 +01:00
Christian Jacobs 4448f450ba Added currently unreleased changes to the CHANGELOG. 2015-05-04 23:23:26 +01:00
Christian Jacobs 819a6a0e47 Another debug statement involving the merging of the COMMENT and NOTES fields. 2015-05-04 23:14:27 +01:00
Christian Jacobs c1d4333662 Compile the regular expression before using it in the loop over tokens. 2015-05-04 23:11:03 +01:00
Christian Jacobs 5e1376eddb Merge the COMMENT field with the NOTES field, if desired and applicable. 2015-05-04 23:00:42 +01:00
Christian Jacobs dc32c2c23d Add an ADIF tab to the Preferences dialog. 2015-04-29 22:45:58 +01:00
Christian Jacobs 7529accdeb Change logging level to warning here. 2015-04-29 21:53:54 +01:00
Christian Jacobs 6a90e9a0bd Change logging level to warning here. 2015-04-29 21:52:18 +01:00
Christian Jacobs 160aa2133d Corrected a typo in a comment. 2015-04-29 16:07:36 +01:00
Christian Jacobs a8083630c7 Look for the 'search' node instead of a 'callsign' node. 2015-04-29 15:59:23 +01:00
Christian Jacobs 3002f2439e Support for callsign lookups using the HamQTH.com database. 2015-04-28 23:04:03 +01:00
Christian Jacobs 620e2e0954 Added a link to the keyboard shortcuts page. 2015-04-28 21:53:23 +01:00
Christian Jacobs eec02777d5 Added a table of keyboard shortcuts. 2015-04-28 21:39:47 +01:00
Christian Jacobs 00c365568b Remove the "www" part of the URL. 2015-04-16 15:12:19 +01:00
Christian Jacobs 838da2779b Added a link to the project page in the documentation. 2015-04-16 15:09:50 +01:00
Christian Jacobs 1fdfc428a7 More helpful info messages. 2015-04-14 22:09:53 +01:00
Christian Jacobs 2c5b7d9c55 If the GreyLine dependencies are not satisfied, print a warning rather than an error message. 2015-04-14 21:33:18 +01:00
Christian Jacobs edbc9ebdec Add more debugging statements when importing the GreyLine dependencies. 2015-04-14 21:32:42 +01:00
Christian Jacobs d0ef8ccf9a Remove the version number from the main window's title.
The version number can be found in the About dialog.
2015-04-02 12:13:12 +01:00
Christian Jacobs 233b996784 Include the total number of QSOs in the Summary page. Addresses issue #23. 2015-04-02 08:57:27 +01:00
Christian Jacobs 141e92056a Updated CHANGELOG links. 2015-03-07 13:24:48 +00:00
Christian Jacobs feab93d799 Put this comment on one line. 2015-03-07 00:42:44 +00:00
Christian Jacobs af670d0acf "Buttons" -> "Button". 2015-03-07 00:42:12 +00:00
Christian Jacobs 07d1a4fabc Remove ADIF test files from the PyQSO 'base' directory too. 2015-03-07 00:03:34 +00:00
Christian Jacobs 3945834450 Display a more helpful error message if the logs fail to load properly. 2015-03-06 23:45:27 +00:00
Christian Jacobs 163fdcaa67 Remove the unnecessary "File:" lines at the start of each file. 2015-03-06 23:37:59 +00:00
Christian Jacobs 410f9955ee Remove the unnecessary "File:" lines at the start of each file. 2015-03-06 23:37:00 +00:00
Christian Jacobs f9b97a6b26 Remove the unnecessary "File:" lines at the top of each .py file. 2015-03-06 23:35:14 +00:00
Christian Jacobs ab5a034d07 Added a description of the project. 2015-03-06 23:32:34 +00:00
Christian Jacobs 3cc4f83a22 Added my middle initial. 2015-03-06 23:31:46 +00:00
Christian Jacobs fed2cab3ed Updated the documentation regarding the "Ignore prefix and/or suffix" option. 2015-03-06 22:37:42 +00:00
Christian Jacobs 45cf8fddff Bug fix for the IGNORE_PREFIX_SUFFIX option. The data type that is read in is a string. 2015-03-06 22:33:46 +00:00
Christian Jacobs 9e2748632b Specified the author email address in setup.py. 2015-03-04 19:24:00 +00:00
Christian Jacobs 94de94c975 Handle any exceptions raised when connecting to the server. 2015-03-03 15:27:32 +00:00
Christian Jacobs b5f72e2ede Fixed the error handling when looking up a callsign that does not have an entry on qrz.com. 2015-03-03 14:31:51 +00:00
Christian Jacobs 209354fcf3 Corrected the indentation of a comment line. 2015-03-01 22:03:43 +00:00
Christian Jacobs 7b3c2634aa Move the code which locates duplicate records into a new method called 'get_duplicates'.
Also added a unit test for this new method.
2015-03-01 21:55:24 +00:00
Christian Jacobs 2bc2ee190d Improve an error message in the GreyLine module. 2015-03-01 14:50:47 +00:00
Christian Jacobs e63184fec8 Temporarily use 'print' instead. 2015-03-01 14:39:24 +00:00
Christian Jacobs 1b9eea5aa6 Print out the matplotlib version in use. 2015-03-01 14:36:27 +00:00
Christian Jacobs 3c5f9ecf43 Print the exception message. 2015-03-01 14:28:47 +00:00
Christian Jacobs dca3ed118c Added unit tests for the Logbook class. 2015-03-01 14:21:18 +00:00
Christian Jacobs c4924447c6 Added some unit tests for the CallsignLookup class. 2015-02-28 23:05:04 +00:00
Christian Jacobs 5a5954bfe7 Updated the logbook screenshot following changes to the labels. 2015-02-28 20:12:29 +00:00
Christian Jacobs 93b0ac0624 Updated the record dialog screenshot following changes to the labels. 2015-02-28 19:50:07 +00:00
Christian Jacobs 861c5c4821 Rename "TX RST" and "RX RST" to "RST Sent" and "RST Received" in the record dialog. 2015-02-28 19:48:10 +00:00
Christian Jacobs dd58927741 Added more fixes to the CHANGELOG. 2015-02-28 16:21:33 +00:00
Christian Jacobs 6781c30be1 Handle UnicodeDecodeError exceptions. 2015-02-28 16:19:52 +00:00
Christian Jacobs a2e0d3ddfb Corrected the image caption. 2015-02-28 16:19:43 +00:00
Christian Jacobs c6a98a25be Updated the logbook screenshot. 2015-02-28 15:57:48 +00:00
Christian Jacobs db9a084f20 Updated the logbook screenshot. 2015-02-28 15:27:04 +00:00
Christian Jacobs b2a39c24b3 Updated the images in the documentation. 2015-02-28 14:53:02 +00:00
Christian Jacobs db514158ac More unit tests and docstrings for the ADIF module. 2015-02-27 08:39:09 +00:00
Christian Jacobs e71fa56044 Added a CHANGELOG. 2015-02-19 21:49:34 +00:00
Christian Jacobs 637413a8ec Reordered directory clean-ups. 2015-02-16 10:58:12 +00:00
Christian Jacobs a18a43daa8 Tell Git to ignore the ADIF files generated for the unittests. 2015-02-16 10:56:16 +00:00
Christian Jacobs 5703769b1f Small improvements to @echo statements in the Makefile. 2015-02-16 10:46:35 +00:00
Christian Jacobs 99724ae10e Handle the case where the user tries to add/edit/delete a record, but the Summary page is selected. 2015-02-16 10:39:16 +00:00
Christian Jacobs 90e2941ee0 Add titles to the auxiliary dialogs. 2015-02-16 10:36:04 +00:00
Christian Jacobs 22e817feb8 Tell Git to ignore build directories. 2015-02-16 08:19:00 +00:00
Christian Jacobs aa74a23b13 Updated the log's name in the image caption. 2015-02-13 18:08:47 +00:00
Christian Jacobs f2c7f05398 Updated the screenshot of the log window. 2015-02-13 18:04:19 +00:00
Christian Jacobs ecf8376ea0 Get Travis to build the documentation too. 2015-02-08 21:50:41 +00:00
Christian Jacobs f5b0ccb0cb Get Travis to install python-sphinx too. 2015-02-08 21:46:02 +00:00
Christian Jacobs 2d0e33ceb7 Perform extra passes to ensure that all duplicate records are removed. There might be a better way to do this. 2015-02-08 20:05:15 +00:00
Christian Jacobs c5160967fa \Z was matching literal 'Z' characters, even when double-escaped, when importing ADIF records. Not quite sure what's going on there, but I don't think the \Z is necessary anyway, so let's remove it. 2015-02-08 17:11:11 +00:00
Christian Jacobs 7ec8ebbfcd Updated documentation on the preferences dialog. 2015-02-08 16:25:00 +00:00
Christian Jacobs 0f1bffc5ea Bump the version to 0.2 in preparation for release. 2015-02-08 15:54:37 +00:00
Christian Jacobs 0ef0a47ef5 Corrected the build directory's name. 2015-02-08 15:50:46 +00:00
Christian Jacobs a656b443a9 Remove the "Indices and tables" section. 2015-02-08 15:46:22 +00:00
Christian Jacobs 3938025084 Add the pyqso modules. 2015-02-08 15:36:19 +00:00
Christian Jacobs ea14556249 Include sphinx-apidoc in the build. 2015-02-08 15:19:25 +00:00
Christian Jacobs 34c622edd1 Added another link to the ADIF website. 2015-02-08 15:04:22 +00:00
Christian Jacobs e268c9b426 Updated the section on creating/opening logbooks. 2015-02-08 15:01:33 +00:00
Christian Jacobs 8f9f6756cc Use ".. code-block:: bash" formatting. 2015-02-08 14:38:51 +00:00
Christian Jacobs 71e9232932 Formatting fixes to the .rst documentation files. 2015-02-08 14:36:28 +00:00
Christian Jacobs 4dcfb23dd7 Make sure html_domain_indices is set to True. 2015-02-08 14:21:16 +00:00
Christian Jacobs b5b56cf04b Fixed up the Introduction. 2015-02-08 14:20:56 +00:00
Christian Jacobs f49ac8738e Make the path to the test.db file relative to the adif.py file. 2015-02-08 13:47:24 +00:00
Christian Jacobs bf4caef61a Use 'unittest discover' when running 'make unittest'. 2015-02-08 13:46:56 +00:00
Christian Jacobs dc349eff13 Added a link to PyQSO's Read the Docs page. 2015-02-08 12:56:37 +00:00
Christian Jacobs b5da94d3d8 Added the documentation build status. 2015-02-08 12:47:24 +00:00
Christian Jacobs 5d7cd07e27 Added sections to the index page. 2015-02-08 12:44:02 +00:00
Christian Jacobs ec24953755 Added .PHONY targets. 2015-02-08 12:41:37 +00:00
Christian Jacobs 0ba745b6a9 Updated the Makefile commands. 2015-02-08 12:39:31 +00:00
Christian Jacobs 9ba6cf2ded Renamed 'doc' to 'docs'. 2015-02-08 12:39:24 +00:00
Christian Jacobs abd759d7d9 Added python-sphinx as a dependency (if the user wants to build the documentation). 2015-02-08 12:37:05 +00:00
Christian Jacobs 602ab78aa1 Converted the .tex file into .rst using Pandoc. Removed the old .tex source file.
Also moved the 'images' directory into the new 'source' directory.
2015-02-08 12:35:16 +00:00
Christian Jacobs 71dd49e594 Added the files generated by sphinx-quickstart. 2015-02-08 12:11:08 +00:00
Christian Jacobs 7f4f5144e8 Added contact information. 2015-02-08 03:03:38 +00:00
Christian Jacobs aaa9b5310b Added my callsign. 2015-02-08 03:01:43 +00:00
Christian Jacobs 10f10ba472 Try using xvfb. 2015-02-08 02:45:41 +00:00
Christian Jacobs c322689685 Removing more packages. 2015-02-08 02:40:27 +00:00
Christian Jacobs a36d23ce75 Export DISPLAY. 2015-02-08 02:32:24 +00:00
Christian Jacobs b165fe0968 Revert extra packages. 2015-02-08 02:24:18 +00:00
Christian Jacobs c3e2ffb2a8 Install PyGObject. 2015-02-08 02:18:47 +00:00
Christian Jacobs d1e77e16a6 Remove gi.repository. 2015-02-08 02:11:35 +00:00
Christian Jacobs 06bcc7821d Use system site packages. 2015-02-08 02:08:28 +00:00
Christian Jacobs da47ba6800 pip install gi 2015-02-08 02:04:33 +00:00
Christian Jacobs d3998e5035 More things for Travis to install. 2015-02-08 02:00:18 +00:00
Christian Jacobs e86917aeb4 Maybe python3-gi? 2015-02-08 01:54:52 +00:00
Christian Jacobs 267d1d7f1a Don't silence apt-get. 2015-02-08 01:50:02 +00:00
Christian Jacobs 732976e9e0 Install python-gi. 2015-02-08 01:30:36 +00:00
Christian Jacobs daabb5b75f Install python-gobject. 2015-02-08 01:26:26 +00:00
Christian Jacobs 6c8ace14cd Added build status. 2015-02-08 01:21:51 +00:00
Christian Jacobs 74af1ec718 Added a Travis CI configuration file. 2015-02-08 01:17:08 +00:00
Christian Jacobs eaefff86c0 Allow default values for power and mode, but remove the work-in-progress for the default frequency unit. 2015-02-08 01:09:05 +00:00
Christian Jacobs 510e1ea283 Add the program name. 2015-02-08 00:45:13 +00:00
Christian Jacobs 63c3fb7fbc Fix logging to file. 2015-02-07 22:56:57 +00:00
Christian Jacobs a5abe6e775 Remove a terrible debugging statement. 2015-02-07 21:47:38 +00:00
Christian Jacobs c20ad39f46 Use argparse instead of optparse. 2015-02-07 21:44:49 +00:00
Christian Jacobs 2c5c046a7a Clear the contents of the file, in case the file exists already. 2015-02-07 21:44:34 +00:00
Christian Jacobs 69d1a95f51 Docstrings and comments. 2015-02-07 21:28:55 +00:00
Christian Jacobs d428fc7953 Use set_do_overwrite_confirmation(True), rather than handling the confirm-overwrite signal ourselves. 2015-02-07 21:25:06 +00:00
Christian Jacobs e6e8570c1b Separate the Create and Open functionality for logbooks. Addresses issue #20.
The menu and toolbar now have separate "Create Logbook" and "Open Logbook" buttons.
2015-02-07 21:22:16 +00:00
Christian Jacobs 4c28af97c0 Specify the Agg backend for matplotlib. Fixes issue #21. 2015-02-06 23:52:09 +00:00
Christian Jacobs e49ec6bdec Merge pull request #17 from legovini/master
Fix creation of empty GtkTreeModel
2014-05-18 17:59:08 +01:00
Paride Legovini 9473318e9a Fix creation of empty GtkTreeModel 2014-05-18 10:17:09 +08:00
Christian Jacobs c6cf24086c Ignore all .pyc files. 2014-05-13 18:21:54 +01:00
Christian Jacobs 1e5744568a Added a button next to the "Time" field in the records dialog to insert the current date and time. 2014-05-13 18:20:39 +01:00
Christian Jacobs 81b746133e Merge the two 'if' statements. 2014-05-13 16:38:48 +01:00
Christian Jacobs 9400aca4d7 Also force all callsigns to be in upper case when imported from an ADIF file. 2014-05-13 16:36:12 +01:00
Christian Jacobs 8a6824ced7 Always show the callsigns in upper case. 2014-05-13 16:28:30 +01:00
Christian Jacobs 7f6e5e7a62 Added the option of removing any prefixes or suffixes from the full_callsign.
Also moved the QRZ.com login details frame to the Records tab.
2014-05-13 16:27:31 +01:00
Christian Jacobs 42d6130d0e Handle 'configuration option not found' exceptions. 2014-03-31 10:44:46 +01:00
Christian Jacobs af9a283849 Don't use the callsign's length. 2014-03-31 00:58:21 +01:00
Christian Jacobs 2977dad8ab Updated some comments. 2014-03-27 10:12:58 +00:00
Christian Jacobs 6dada62d28 Added the option to choose the default unit of frequency. Not fully implemented yet. 2014-03-27 10:09:38 +00:00
Christian Jacobs 65bd7175fb Removing any prefixes and/or suffixes (e.g. "/M" or "/P") from the callsign before performing a lookup. 2014-03-27 10:08:46 +00:00
Christian Jacobs 0743093f24 Give users the option of using UTC when the Date and Time fields are automatically completed. 2014-03-24 03:06:47 +00:00
Christian Jacobs 8f2017c6ef Small updates to some comments. 2014-03-23 17:19:48 +00:00
Christian Jacobs 5676a86e11 Improved error handling. 2014-03-23 17:17:59 +00:00
Christian Jacobs f187fe7fa4 Using the frequency ranges in the ADIF specification to determine the band, instead of the previous approach (using the band which was closest to the calculated wave length). 2014-03-23 17:11:11 +00:00
Christian Jacobs ed68b63108 Small improvements to the autocomplete_band code. 2014-03-23 02:43:11 +00:00
Christian Jacobs e143483f72 Added the option to autocomplete the Band field. 2014-03-23 01:54:24 +00:00
Christian Jacobs 4f70af2985 Added a function to autocomplete the Band field based on the Frequency field. 2014-03-23 01:24:45 +00:00
Christian Jacobs 2913b813d5 Move to version 0.2a-dev. 2014-03-22 22:05:08 +00:00
84 zmienionych plików z 12960 dodań i 3498 usunięć

4
.gitignore vendored 100644
Wyświetl plik

@ -0,0 +1,4 @@
*.pyc
pyqso.debug
build/
docs/build

31
.travis.yml 100644
Wyświetl plik

@ -0,0 +1,31 @@
sudo: required
dist: trusty
language: python
python:
- "3.4"
virtualenv:
system_site_packages: true
before_install:
- sudo apt-get update -qq
- sudo apt-get install -yq xvfb python3 python3-pip gir1.2-gtk-3.0 python3-gi-cairo python3-flake8 python3-numpy python3-matplotlib python3-sphinx python-libhamlib2
- "export DISPLAY=:99.0"
- "sh -e /etc/init.d/xvfb start"
install:
- sudo make install
before_script:
- export PYTHONPATH=`pwd`:$PYTHONPATH
- echo $PYTHONPATH
- flake8 pyqso
- flake8 tests
- flake8 bin
script:
- make test
- make docs
- sudo make clean

119
CHANGELOG.md 100644
Wyświetl plik

@ -0,0 +1,119 @@
# Change Log
## [1.1.0] - 2018-04-02
### Added
- Support for the SAT_NAME, SAT_MODE, PROP_MODE, and GRIDSQUARE ADIF fields for the purposes of satellite QSO logging.
- Pinpointing of callsigns on the world map by looking up the latitude-longitude coordinates based on the value in the GRIDSQUARE field (or COUNTRY field if the GRIDSQUARE is not specified). A new right-click popup menu has been created for this purpose.
- A separate World Map tab in the Preferences dialog.
- A navigation bar for the World Map tool.
- The option of showing Maidenhead grid squares on the World Map, and the option of shading in worked grid squares.
- Basic copy/paste functionality for individual records.
- A requirements.txt file for the purpose of installing dependencies.
### Changed
- Renamed the GreyLine class to WorldMap, since it now does more than just grey line plotting.
- Improved the section on dependencies in the README.
### Fixed
- Updated the list of supported ADIF fields.
## [1.0.0] - 2017-08-02
### Added
- Pin-pointing of QTH on grey line map.
- Default logbook.
- Continued support for Python 2.x modules. Thanks to @gaionim (IU2HDS) for this patch.
- Auto-filling of the Mode field using Hamlib.
- Glade design of main window and dialogs.
- Exporting of logs in the Cabrillo format.
- More unit tests.
- More tooltips.
- The option to enter the frequency in Hz, kHz, MHz, or GHz in the Add/Edit Record dialog. Frequencies are still displayed in MHz in the logbook.
- Record/QSO count feature.
### Changed
- Using username and port information (in addition to hostname) when creating an identifier for a DX cluster bookmark.
- Pressing the Return key after entering a DX cluster command will send the command to the Telnet server.
- Pressing the Return key after entering QSO information via the record dialog will add the QSO to the log.
- Moved all unit tests to a dedicated tests directory.
- Duplicate QSOs are now defined as having the same CALL, QSO_DATE and TIME_ON values. FREQ and MODE are no longer considered.
- Improved the runtime performance of duplicate QSO removal.
- Logs are now printed on a landscape page so that more QSO details can be included. The page layout has been improved.
- Better handling of "\n" characters in the NOTES field.
### Fixed
- Any characters in the DX cluster server's reponse that cannot be decoded are now replaced with a replacement marker in the DX cluster frame.
- Fixed the QSO index used in the Gtk.ListStore. Just before a QSO is added with add_record it was assumed that it's index would be max(rowid)+1, which is not always the case. This led to inconsistencies between the Gtk.ListStore and the database. Indices used in the Gtk.ListStore are now obtained directly from the database after insertion.
- Direction of sorting.
- IOTA data retrieval when looking up callsigns using hamqth.com.
- Use percent-encoding when connecting to a callsign database.
## [0.3] - 2016-05-28
### Added
- Support for callsign lookups using the HamQTH.com database.
- Added a table of keyboard shortcuts to the documentation.
- More helpful messages regarding missing dependencies.
- Added the option of merging the COMMENT field with the NOTES field when importing records from an ADIF file.
- Bookmarking of Telnet-based DX cluster servers.
### Changed
- Ported the codebase over to Python 3 using 2to3 (thanks to Neil Johnson).
- The Summary page now also contains the total number of QSOs in the logbook.
- Improvements to docstrings.
- Various code cleanups (thanks to András Veres-Szentkirályi).
- Brought the list of valid modes up-to-date.
- Updated the list of bands and their frequency ranges.
- Configuration files are now written to ~/.config to keep the user's home directory uncluttered.
- The codebase is now compliant with the PEP 8 Python coding conventions (except for E501,F403,E226,E402,W503).
- Updated the documentation.
## [0.2] - 2015-03-07
### Added
- Travis CI configuration file for automated building and testing.
- Button to add the current date and time.
- Option to specify default values for the power and mode fields.
- Allow UTC time to be used when creating records.
- Allow prefixes/suffixes to be removed when looking up a callsign (e.g. "MYCALL" would be extracted from "F/MYCALL/QRP").
### Changed
- Migrated the documentation to a Sphinx-based setup.
- Separate the Create and Open functionality for logbooks.
- In the record dialog, the labels "TX RST" and "RX RST" have been changed to "RST Sent" and "RST Received". The underlying ADIF field names remain the same (RST_SENT and RST_RCVD).
### Fixed
- Logging debug messages to file.
- 'Z' characters in callsigns were being ignored when importing ADIF files. This has now been fixed.
- Specifed the Agg backend for matplotlib to workaround a bug in Ubuntu 14.10.
- Sorting the date and time fields in the correct chronological order.
- Removal of duplicate records.
- Error handling when looking up a callsign that does not have an entry on qrz.com.
- Handling of ConfigParser.NoOptionError exceptions when trying to load preferences.
- Handling of UnicodeDecodeError exceptions when parsing the output from DX cluster servers.
## [0.1] - 2014-03-22
### Changed
- The 'Notes' column is no longer automatically resized.
- The BEL character is now handled properly in the DX cluster tool.
- QSOs can now be sorted in the correct chronological order.
### Fixed
- Fixed the ADIF export functionality. Previously, only markers were being written and the actual record data was being skipped.
## [0.1b] - 2013-10-04
### Added
- Basic logging functionality.
- Import and export in ADIF format.
- Log printing.
- Basic support for Hamlib.
- Telnet-based DX cluster support.
- Progress tracker for the DXCC award.
- Greyline plotter.
- QSO filtering and sorting.
- Duplicate record removal.
[1.1.0]: https://github.com/ctjacobs/pyqso/compare/v1.0.0...v1.1.0
[1.0.0]: https://github.com/ctjacobs/pyqso/compare/v0.3...v1.0.0
[0.3]: https://github.com/ctjacobs/pyqso/compare/v0.2...v0.3
[0.2]: https://github.com/ctjacobs/pyqso/compare/v0.1...v0.2
[0.1]: https://github.com/ctjacobs/pyqso/compare/v0.1b...v0.1

Wyświetl plik

@ -1,7 +1,6 @@
#!/usr/bin/env python
# File: Makefile
#!/bin/sh
# Copyright (C) 2013 Christian Jacobs.
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
@ -18,25 +17,26 @@
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
input: clean install documentation
.PHONY: input clean install docs test
input: clean install docs
install:
@echo **********Installing PyQSO
python setup.py install
@echo "*** Installing PyQSO"
pip3 install .
manual:
@echo **********Compiling the user manual
cd doc; pdflatex manual.tex; cd ..
docs:
@echo "*** Building the documentation"
cd docs; make html; cd ..
unittest:
@echo **********Running the unit tests
cd pyqso; for file in *.py; do (python $$file); done; cd ..
test:
@echo "*** Running the unit tests"
python3 -m unittest discover --start-directory=tests --pattern=*.py --verbose
clean:
@echo **********Cleaning build directory
@echo "*** Cleaning docs directory"
cd docs; make clean; cd ..
@echo "*** Cleaning pyqso directory"
rm -f ADIF.test_*.adi Cabrillo.test_*.log Printer.test_*.pdf Logbook.test_*.db; cd pyqso; rm -f *.pyc ADIF.test_*.adi Cabrillo.test_*.log; cd ..
@echo "*** Removing build directory"
rm -rf build
@echo **********Cleaning pyqso directory
cd pyqso; rm -rf *.pyc ADIF.test_read.adi ADIF.test_write*.adi; cd ..
@echo **********Cleaning doc directory
cd doc; rm -rf *.log *.aux *.dvi *.pdf *.ps *.toc *.out; cd ..

101
README.md
Wyświetl plik

@ -1,5 +1,4 @@
File: README.md
Copyright (C) 2013 Christian Jacobs.
Copyright (C) 2013-2018 Christian Thomas Jacobs.
This file is part of PyQSO.
@ -16,53 +15,75 @@
You should have received a copy of the GNU General Public License
along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
PyQSO
=====
# PyQSO
PyQSO is a contact logging tool for amateur radio operators.
Installation and running
------------------------
[![Build Status](https://travis-ci.org/ctjacobs/pyqso.svg)](https://travis-ci.org/ctjacobs/pyqso)
[![Documentation Status](https://readthedocs.org/projects/pyqso/badge/?version=latest)](https://readthedocs.org/projects/pyqso/?badge=latest)
Assuming that the current working directory is PyQSO's base directory (the directory that the Makefile is in), PyQSO can be installed via the terminal with the following command:
## Dependencies
`make install`
Note: 'sudo' may be needed for this. Once installed, the following command will run PyQSO:
`pyqso`
Alternatively, PyQSO can be run (without installing) with:
`python bin/pyqso`
from PyQSO's base directory.
Documentation
-------------
The PyQSO user manual is stored as a LaTeX source file in the doc/ directory. It can be compiled with the following command:
`make manual`
which will produce the manual.pdf file.
Dependencies
------------
PyQSO depends on the following Debian packages:
As the name suggests, PyQSO is written primarily in the [Python](https://www.python.org/) programming language (version 3.x). The graphical user interface has been developed using the [GTK+ library](https://www.gtk.org/) through the [PyGObject bindings](https://pygobject.readthedocs.io). Therefore, in order to run PyQSO, the Python interpreter must be present on your system along with support for GTK+. On many Linux-based systems this can be accomplished by installing the following Debian packages:
* python3
* gir1.2-gtk-3.0
* python2.7
* python-gi-cairo (for log printing purposes)
* python3-gi-cairo
The following extra packages are necessary to enable the grey line tool:
Several extra packages are necessary to enable the full functionality of PyQSO. Many of these (specified in the `requirements.txt` file) can be readily installed system-wide using the Python package manager by issuing the following command in the terminal:
* python-mpltoolkits.basemap
* python-numpy
* python-matplotlib (version 1.3.0 or later)
sudo pip3 install -U -r requirements.txt
The following extra package is necessary to enable Hamlib support:
but the complete list is given below:
* python-libhamlib2
* python3-matplotlib (version 1.3.0 or later)
* python3-numpy
* libxcb-render0-dev
* [cartopy](http://scitools.org.uk/cartopy/), for drawing the world map. This package in turn depends on python3-scipy, python3-cairocffi, cython, libproj-dev (version 4.9.0 or later), and libgeos-dev (version 3.3.3 or later).
* [geocoder](https://pypi.python.org/pypi/geocoder), for QTH lookups.
* python3-sphinx, for building the documentation.
* python3-hamlib, for Hamlib support.
### Hamlib support
There currently does not exist a Python 3-compatible Debian package for [Hamlib](http://www.hamlib.org). This library must be built manually to enable Hamlib support. As per the instructions on the [Hamlib mailing list](https://sourceforge.net/p/hamlib/mailman/message/35692744/), run the following commands in the Hamlib root directory (you may need to run `sudo apt-get install build-essential autoconf automake libtool` beforehand):
export PYTHON=/usr/bin/python3
autoreconf --install
./configure --with-python-binding
make
sudo make install
You will also need to append the Hamlib `bindings` and `bindings/.libs` directories to the `PYTHONPATH`:
export PYTHONPATH=$PYTHONPATH:/path/to/hamlib/bindings:/path/to/hamlib/bindings/.libs
## Installing and running
Assuming that the current working directory is PyQSO's base directory (the directory that the `Makefile` is in), PyQSO can be run without installation by issuing the following command in the terminal:
python3 bin/pyqso
If the Python package manager `pip3` is available on your system then PyQSO can be installed system-wide using:
sudo make install
Once installed, the following command will run PyQSO:
pyqso
## Documentation
Guidance on how to use PyQSO is available on [Read the Docs](http://pyqso.readthedocs.io/) and in the screencast below.
[![PyQSO: A Logging Tool for Amateur Radio Operators](https://img.youtube.com/vi/sVdZl9KnDsk/0.jpg)](https://www.youtube.com/watch?v=sVdZl9KnDsk)
The documentation can also be built locally with the following command:
make docs
which will produce an HTML version of the documentation in `docs/build/html` that can be opened in a web browser.
## Contact
If you have any comments or questions about PyQSO please send them via email to Christian Jacobs, M0UOS, at <christian@christianjacobs.uk>.

241
bin/pyqso
Wyświetl plik

@ -1,7 +1,6 @@
#!/usr/bin/env python
# File: pyqso.py
#!/usr/bin/env python3
# Copyright (C) 2012 Christian Jacobs.
# Copyright (C) 2012-2018 Christian Thomas Jacobs.
# This file is part of PyQSO.
@ -18,149 +17,159 @@
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk, GObject, Gdk, GdkPixbuf
import logging
import optparse
import ConfigParser
from gi import require_version
require_version('Gtk', '3.0')
require_version('PangoCairo', '1.0')
from gi.repository import Gtk, Gdk, GdkPixbuf
import argparse
try:
import configparser
except ImportError:
import ConfigParser as configparser
import os
import os.path
import sys
import signal
import pkg_resources
# This will help Python find the PyQSO modules
# that need to be imported below.
import logging
logging.basicConfig(level=logging.INFO)
logging.info("PyQSO version 1.1.0")
# This will help Python find the PyQSO modules that need to be imported below.
pyqso_path = os.path.join(os.path.realpath(os.path.dirname(__file__)), os.pardir)
sys.path.insert(0, pyqso_path)
# PyQSO modules
# PyQSO modules.
from pyqso.adif import *
from pyqso.logbook import *
from pyqso.menu import *
from pyqso.popup import *
from pyqso.toolbar import *
from pyqso.toolbox import *
from pyqso.preferences_dialog import *
class PyQSO(Gtk.Window):
""" The PyQSO application class. """
def __init__(self, logbook_path):
""" Set up the main (root) window, start the event loop, and open a logbook (if the logbook's path is specified by the user in the command line). """
# Call the constructor of the super class (Gtk.Window)
Gtk.Window.__init__(self, title="PyQSO 0.1")
# Get any application-specific preferences from the configuration file
config = ConfigParser.ConfigParser()
# Check that the configuration file actually exists (and is readable)
# otherwise, we will resort to the defaults.
have_config = (config.read(os.path.expanduser("~/.pyqso.ini")) != [])
self.set_size_request(800, 600) # Default to an 800 x 600 resolution.
self.set_position(Gtk.WindowPosition.CENTER)
possible_icon_paths = [os.path.join(pyqso_path, "icons", "log_64x64.png")]
for icon_path in possible_icon_paths:
try:
self.set_icon_from_file(icon_path)
except Exception, error:
print error.message
class PyQSO:
# Kills the application if the close button is clicked on the main window itself.
self.connect("delete-event", Gtk.main_quit)
vbox_outer = Gtk.VBox()
self.add(vbox_outer)
""" The PyQSO application class. """
self.statusbar = Gtk.Statusbar()
context_id = self.statusbar.get_context_id("Status")
self.statusbar.push(context_id, "No logbook is currently open.")
# Create a Logbook so we can add/remove/edit logs and records,
# once connected to the SQLite database.
self.logbook = Logbook(self)
self.logbook.set_scrollable(True)
def __init__(self, logbook_path=None):
""" Set up the main (root) window, start the event loop, and open a logbook (if the logbook's path is specified by the user in the command line).
self.toolbox = Toolbox(self)
:arg str logbook_path: An optional argument containing the path of the logbook file to open. If no value is provided, this defaults to None and no logbook is opened.
"""
# Set up menu and tool bars
# These classes depend on the Logbook and Toolbox class,
# so pack the logbook and toolbox after the menu and toolbar.
self.menu = Menu(self)
self.toolbar = Toolbar(self)
# Get the PyQSO main window defined in the Glade file.
self.builder = Gtk.Builder()
glade_file_path = pkg_resources.resource_filename("pyqso", os.path.join("res", "pyqso.glade"))
self.builder.add_from_file(glade_file_path)
self.window = self.builder.get_object("pyqso")
vbox_outer.pack_start(self.menu, False, False, 0)
vbox_outer.pack_start(self.toolbar, False, False, 0)
vbox_outer.pack_start(self.logbook, True, True, 0)
vbox_outer.pack_start(self.toolbox, True, True, 0)
vbox_outer.pack_start(self.statusbar, False, False, 0)
# Check that the directory for holding PyQSO configuration files exists. If it doesn't, create it now.
config_directory = os.path.expanduser('~/.config/pyqso')
if not os.path.exists(config_directory):
try:
os.makedirs(config_directory)
except Exception as e:
logging.error("An error occurred whilst creating a directory for PyQSO configuration files. Try creating the directory '~/.config/pyqso' manually.")
logging.exception(e)
self.show_all()
# Get any application-specific preferences from the configuration file.
config = configparser.ConfigParser()
if(have_config):
if(config.get("general", "show_toolbox") == "False"):
# Check that the configuration file actually exists (and is readable)
# otherwise, we will resort to the defaults.
have_config = (config.read(config_directory + "/preferences.ini") != [])
# Kills the application if the close button is clicked on the main window itself.
self.window.connect("delete-event", Gtk.main_quit)
self.statusbar = self.builder.get_object("statusbar")
context_id = self.statusbar.get_context_id("Status")
self.statusbar.push(context_id, "No logbook is currently open.")
# Create a Logbook so we can add/remove/edit logs and records,
# once connected to the SQLite database.
self.logbook = Logbook(self)
self.toolbox = Toolbox(self)
# Set up the menu and toolbar. These classes depend on the Logbook and Toolbox class.
self.menu = Menu(self)
self.popup = Popup(self)
self.toolbar = Toolbar(self)
# Clipboard for copy/paste operations.
self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
# Show the main window.
self.window.show_all()
if(have_config):
if(not config.getboolean("general", "show_toolbox")):
self.toolbox.toggle_visible_callback()
else:
# Hide the Toolbox by default.
self.toolbox.toggle_visible_callback()
else:
# Hide the Toolbox by default
self.toolbox.toggle_visible_callback()
if(logbook_path is not None):
self.logbook.open(widget=None, path=logbook_path)
if(logbook_path):
logging.info("Opening logbook: %s" % logbook_path)
self.logbook.open(path=logbook_path)
else:
# If no logbook path is specified at the command line,
# then check if the user wants to open a default logbook.
(section, option) = ("general", "default_logbook")
if(have_config and config.has_option(section, option)):
open_default_logbook = config.getboolean(section, option)
(section, option) = ("general", "default_logbook_path")
if(open_default_logbook and config.has_option(section, option)):
logbook_path = config.get(section, option)
if(logbook_path is not None and logbook_path != ""):
logging.info("Opening the default logbook: %s" % logbook_path)
self.logbook.open(path=logbook_path)
return
return
def show_about(self, widget):
""" Show the About dialog, which includes license information. This method returns None after the user destroys the dialog. """
about = Gtk.AboutDialog()
about.set_modal(True)
about.set_transient_for(parent=self)
about.set_program_name("PyQSO")
about.set_version("0.1")
about.set_authors(["Christian Jacobs"])
about.set_license("""This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
def show_about(self, widget):
""" Show the About dialog, which includes license information. """
glade_file_path = pkg_resources.resource_filename("pyqso", os.path.join("res", "pyqso.glade"))
self.builder.add_objects_from_file(glade_file_path, ("about_dialog",))
about = self.builder.get_object("about_dialog")
about.run()
about.destroy()
return
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.""")
about.set_comments("PyQSO: A contact logging tool for amateur radio operators.")
possible_icon_paths = [os.path.join(pyqso_path, "icons", "log_64x64.png")]
for icon_path in possible_icon_paths:
try:
about.set_logo(GdkPixbuf.Pixbuf.new_from_file_at_scale(icon_path, 64, 64, False))
except Exception, error:
print error.message
about.run()
about.destroy()
return
def show_preferences(self, widget):
""" Show the Preferences dialog. Any changes made by the user after clicking the 'Ok' button are saved in the .cfg file. This method returns None after the user destroys the dialog. """
preferences = PreferencesDialog(self)
response = preferences.run()
if(response == Gtk.ResponseType.OK):
preferences.commit()
preferences.destroy()
return
def show_preferences(self, widget):
""" Show the Preferences dialog. Any changes made by the user after clicking the 'Ok' button are saved in the configuration file. """
preferences = PreferencesDialog(self)
response = preferences.dialog.run()
if(response == Gtk.ResponseType.OK):
preferences.commit()
preferences.dialog.destroy()
return
if(__name__ == "__main__"):
# Get any command line arguments
parser = optparse.OptionParser()
parser.add_option("-d", "--debug", action="store_true", default=False, help="Enable debugging. All debugging messages will be written to pyqso.debug.")
parser.add_option("-l", "--logbook", action="store", type="string", dest="logbook", default=None, help="Path to the Logbook file.")
(options, args) = parser.parse_args()
# Get any command line arguments.
parser = argparse.ArgumentParser(prog="pyqso")
parser.add_argument("-d", "--debug", action="store_true", default=False, help="Enable debugging. All debugging messages will be written to pyqso.debug.")
parser.add_argument("-l", "--logbook", action="store", type=str, metavar="/path/to/my_logbook_file.db", default=None, help="Path to a Logbook file. If this file does not already exist, then it will be created.")
args = parser.parse_args()
# Set up debugging output
if(options.debug):
logging.basicConfig(level=logging.DEBUG, filename="pyqso.debug",
format="%(asctime)s %(levelname)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S")
# Output debugging messages to a file.
if(args.debug):
# Get the root logger.
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# Add a file handler.
handler = logging.FileHandler("pyqso.debug", mode="w")
formatter = logging.Formatter(fmt="%(asctime)s %(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler.setFormatter(formatter)
logger.addHandler(handler)
signal.signal(signal.SIGINT, signal.SIG_DFL) # Exit PyQSO if a SIGINT signal is captured.
application = PyQSO(options.logbook) # Populate the main window and show it
Gtk.main() # Start up the event loop!
# Enforce an absolute logbook file path.
if(args.logbook):
args.logbook = os.path.abspath(args.logbook)
signal.signal(signal.SIGINT, signal.SIG_DFL) # Exit PyQSO if a SIGINT signal is captured.
application = PyQSO(args.logbook) # Populate the main window and show it.
Gtk.main() # Start up the event loop!

Plik binarny nie jest wyświetlany.

Przed

Szerokość:  |  Wysokość:  |  Rozmiar: 12 KiB

Plik binarny nie jest wyświetlany.

Przed

Szerokość:  |  Wysokość:  |  Rozmiar: 48 KiB

Plik binarny nie jest wyświetlany.

Przed

Szerokość:  |  Wysokość:  |  Rozmiar: 41 KiB

Plik binarny nie jest wyświetlany.

Przed

Szerokość:  |  Wysokość:  |  Rozmiar: 64 KiB

Plik binarny nie jest wyświetlany.

Przed

Szerokość:  |  Wysokość:  |  Rozmiar: 58 KiB

Wyświetl plik

@ -1,258 +0,0 @@
% PyQSO User Manual
% Copyright (C) 2013 Christian Jacobs.
% This file is part of PyQSO.
% PyQSO is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% PyQSO is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
\documentclass[11pt, a4paper]{report}
\usepackage[margin=1.2in]{geometry}
\usepackage{graphicx}
\usepackage{hyperref}
\hypersetup{
colorlinks=false,
pdfborder={0 0 0},
}
\setlength{\parskip}{0.25cm}
\begin{document}
\begin{titlepage}
\begin{center}
\vspace*{5cm}
\huge{PyQSO User Manual}\\\vspace*{5cm}
\LARGE{Version 0.1}
\end{center}
\end{titlepage}
\tableofcontents
\chapter{Introduction}\label{chap:introduction}
\section{Overview}
PyQSO is a logging tool for amateur radio operators. It provides a simple graphical interface through which users can manage information about the contacts/QSOs they make with other operators on the air. All information is stored in a light-weight SQL database. Other key features include:
\begin{itemize}
\item Customisable interface (e.g. only show callsign and frequency information).
\item Import and export logs in ADIF format.
\item Perform callsign lookups and auto-fill data fields using the qrz.com database.
\item Sort the logs by individual fields.
\item Print a hard-copy of logs, or print to PDF.
\item Connect to Telnet-based DX clusters.
\item Progress tracker for the DXCC award.
\item Grey line plotter.
\item Filter out QSOs based on the callsign field (e.g. only display contacts with callsigns beginning with ``M6'').
\item Remove duplicate QSOs.
\item Basic support for the Hamlib library.
\end{itemize}
The source code for PyQSO is available for download at:
\texttt{https://github.com/ctjacobs/pyqso}
\section{Data storage model}
Many amateur radio operators choose to store all the contacts they ever make in a single \textit{logbook}, whereas others keep a separate logbook for each year, for example. Each logbook may be divided up to form multiple distinct \textit{logs}, perhaps one for casual repeater contacts and another for DX'ing. Finally, each log can contain multiple \textit{records}. PyQSO is based around this three-tier model for data storage, going from logbooks at the top to individual records at the bottom.
Rather than storing each log in a separate file, a single database can hold several logs together; in PyQSO, a database is therefore analogous to a logbook. Within a database the user can create multiple tables which are analogous to the logs. Within each table the user can create/modify/delete records which are analogous to the records in each log.
\section{Licensing}
PyQSO is free software, released under the GNU General Public License. Please see the file called COPYING for more information.
\section{Structure of this manual}
The structure of this manual is as follows. Chapter \ref{chap:getting_started} is all about getting started with PyQSO -- from the installation process through to creating a new logbook (or opening an existing one). Chapter \ref{chap:log_management} explains how to create a log in the logbook, as well as the basic operations that users can perform with existing logs, such as printing, importing from/exporting to ADIF format, and sorting. Chapter \ref{chap:record_management} deals with the bottom layer of the three-tier model -- the creation, deletion, and modification of QSO records in a log. Chapter \ref{chap:toolbox} introduces the PyQSO toolbox which contains three tools that are useful to amateur radio operators: a DX cluster, a grey line plotter, and an awards progress tracker. Finally, Chapter \ref{chap:preferences} explains how users can set up Hamlib support and show/hide various fields in a log, along with several other user preferences that can be set via the Preferences dialog window.
\chapter{Getting started}\label{chap:getting_started}
\section{System requirements}
It is recommended that users run PyQSO on the Linux operating system, since all development and testing of PyQSO takes place there.
As the name suggests, PyQSO is written primarily in the Python programming language. The graphical user interface has been built using the GTK+ library through the PyGObject bindings. PyQSO also uses an SQLite embedded database to manage all the contacts an amateur radio operator makes. Users must therefore make sure that the Python interpreter and any additional software dependencies are satisfied before PyQSO can be run successfully. The list of software packages that PyQSO depends on is provided in the README file.
\section{Installation and running}
Assuming that the current working directory is PyQSO's base directory (the directory that the Makefile is in), PyQSO can be installed via the terminal with the following command:
\texttt{make install}
\noindent Note: `sudo' may be needed for this. Once installed, the following command will run PyQSO:
\texttt{pyqso}
\noindent Alternatively, PyQSO can be run (without installing) with:
\texttt{python bin/pyqso}
\noindent from PyQSO's base directory.
\subsection{Command-line options}
There are several options available when executing PyQSO from the command-line.
\subsubsection{Open a specified logbook file}
In addition to being able to open a new or existing logbook through the graphical interface, users can also specify a logbook file to open at the command line with the \texttt{-l} or \texttt{--logbook} option. For example, to open a logbook file called \texttt{mylogbook.db}, use the following command:
\texttt{pyqso --logbook /path/to/mylogbook.db}
\noindent If the file does not already exist, PyQSO will create it.
\subsubsection{Debugging mode}
Running PyQSO with the \texttt{-d} or \texttt{--debug} flag enables the debugging mode:
\texttt{pyqso --debug}
\noindent All debugging-related messages are written to a file called pyqso.debug, located in the current working directory.
\section{Opening a new or existing logbook}
Logbooks are SQL databases, and as such they are accessed with a database connection. To create a connection and open the logbook, click \texttt{Open a New or Existing Logbook...} in the \texttt{Logbook} menu, and either:
\begin{itemize}
\item Find and select an existing logbook database file (which usually has a \texttt{.db} file extension), and click \texttt{Open} to create the database connection; or
\item Create a new database by entering a (non-existing) file name and clicking \texttt{Open}. The logbook database file (and a connection to it) will then be created automatically.
\end{itemize}
Once the database connection has been established, the database file name will appear in the status bar. All logs in the logbook will be opened automatically, and the interface will look something like the one shown in Figure \ref{fig:log_view_with_awards}.
\begin{figure}
\centering
\includegraphics[width=1\columnwidth]{images/log_with_awards.png}
\caption{The PyQSO main window, showing the records in a log called \texttt{repeater\_contacts}, and the awards tool in the toolbox below it.}
\label{fig:log_view_with_awards}
\end{figure}
\section{Closing a logbook}
A logbook can be closed (along with its corresponding database connection) by clicking the \texttt{Close Logbook} button in the toolbar, or by clicking \texttt{Close Logbook} in the \texttt{Logbook} menu.
\chapter{Log management}\label{chap:log_management}
\noindent\textbf{Note 1:} All the operations described below assume that a logbook is already open.
\noindent\textbf{Note 2:} Any modifications made to the logs are permanent. Users should make sure they keep up-to-date backups.
\section{Creating a new log}
To create a new log, click \texttt{New Log} in the \texttt{Logbook} menu and enter the desired name of the log (e.g. repeater\_contacts, dx, mobile\_log). Alternatively, use the shortcut key combination \texttt{Ctrl + N}.
The log name must be unique (i.e. it cannot already exist in the logbook). Furthermore, it can only be composed of alphanumeric characters and the underscore character, and the first character in the name must not be a number.
Note: When logs are stored in the database file, field/column names from the ADIF standard are used. However, please note that only the following subset of all the ADIF fields is considered: CALL, QSO\_DATE, TIME\_ON, FREQ, BAND, MODE, TX\_PWR, RST\_SENT, RST\_RCVD, QSL\_SENT, QSL\_RCVD, NOTES, NAME, ADDRESS, STATE, COUNTRY, DXCC, CQZ, ITUZ, IOTA. Visit http://adif.org/ for more information about these fields.
\section{Renaming a log}
To rename the currently selected log, click \texttt{Rename Selected Log} in the \texttt{Logbook} menu. Remember that the log's new name cannot be the same as another log in the logbook.
\section{Deleting a log}
To delete the currently selected log, click \texttt{Delete Selected Log} in the \texttt{Logbook} menu. As with all database operations in PyQSO, this is permanent and cannot be undone.
\section{Importing and exporting a log}
While PyQSO stores logbooks in SQL format, it is possible to export individual logs in the well-known ADIF format. Select the log to export, and click \texttt{Export Log} in the \texttt{Logbook} menu.
Similarly, records can be imported from an ADIF file. Upon importing, users can choose to store the records in a new log, or append them to an existing log in the logbook. To import, click \texttt{Import Log} in the \texttt{Logbook} menu.
Note that all data must conform to the ADIF standard, otherwise it will be ignored.
\section{Printing a log}
Due to restrictions on the page width, only a selection of field names will be printed: callsign, date, time, frequency, and mode.
\section{Filtering by callsign}
Entering an expression such as \texttt{xyz} into the \texttt{Filter by callsign} box will instantly filter out all records whose callsign field does not contain \texttt{xyz}.
\section{Sorting by field}
To sort a log by a particular field name, left-click the column header that contains that field name. By default, it is the \texttt{Index} field that is sorted in ascending order.
\chapter{Record management}\label{chap:record_management}
\noindent\textbf{Note:} Any modifications made to the records are permanent. Users should make sure they keep up-to-date backups.
\section{Creating a new record (QSO)}
A new QSO can be added by either:
\begin{itemize}
\item Clicking the \texttt{Add Record} button in the toolbar.
\item Pressing \texttt{Ctrl + R}.
\item Clicking \texttt{Add Record...} in the \texttt{Records} menu.
\end{itemize}
A dialog window will appear where details of the QSO can be entered (see Figure \ref{fig:edit_record}). Note that the current date and time are filled in automatically. When ready, click \texttt{OK} to save the changes.
\begin{figure}
\centering
\includegraphics[width=1\columnwidth]{images/edit_record.png}
\caption{Record dialog used to add new records and edit existing ones.}
\label{fig:edit_record}
\end{figure}
\subsection{Callsign lookup}
PyQSO can also resolve station-related information (e.g. the operator's name, address, and ITU Zone) by clicking the \texttt{Lookup on qrz.com} button adjacent to the Callsign data entry box. Note that the user must first supply their qrz.com account information in the preferences dialog window.
\section{Editing a record}
An existing record can be edited by:
\begin{itemize}
\item Double-clicking on it.
\item Selecting it and clicking the \texttt{Edit Record} button in the toolbar.
\item Selecting it and clicking \texttt{Edit Selected Record...} in the \texttt{Records} menu.
\end{itemize}
This will bring up the same dialog window as before.
\section{Deleting a record}
An existing record can be deleted by:
\begin{itemize}
\item Selecting it and clicking the \texttt{Delete Record} button in the toolbar.
\item Selecting it and pressing the \texttt{Delete} key.
\item Selecting it and clicking \texttt{Delete Selected Record...} in the \texttt{Records} menu.
\end{itemize}
\section{Removing duplicate records}
PyQSO can find and delete duplicate records in a log. A record is a duplicate of another if its data in the Callsign, Date, Time, Frequency, and Mode fields are the same. Click \texttt{Remove Duplicate Records} in the \texttt{Records} menu.
\chapter{Toolbox}\label{chap:toolbox}
The toolbox is hidden by default. To show it, click \texttt{Toolbox} in the \texttt{View} menu.
\section{DX cluster}
A DX cluster is essentially a server through which amateur radio operators can report and receive updates about QSOs that are in progress across the bands. PyQSO is able to connect to a DX cluster that operates using the Telnet protocol to provide a text-based alert service. As a result of the many different Telnet-based software products that DX clusters run, PyQSO currently outputs the raw data received from the DX cluster rather than trying to parse it in some way.
Click on the \texttt{Connect to Telnet Server} button and enter the DX server details in the dialog that appears. If no port is specified, PyQSO will use the default value of 23. A username and password may also need to be supplied. Once connected, the server output will appear in the DX cluster frame (see Figure \ref{fig:dx_cluster}). A command can also be sent to the server by typing it into the entry box and clicking the adjacent \texttt{Send Command} button.
\begin{figure}
\centering
\includegraphics[width=1\columnwidth]{images/dx_cluster.png}
\caption{The DX cluster frame.}
\label{fig:dx_cluster}
\end{figure}
\section{Grey line}
The grey line tool (see Figure \ref{fig:grey_line}) can be used to check which parts of the world are in darkness. The position of the grey line is automatically updated every 30 minutes.
\begin{figure}
\centering
\includegraphics[width=1\columnwidth]{images/grey_line.png}
\caption{The grey line tool.}
\label{fig:grey_line}
\end{figure}
\section{Awards}
The awards progress tracker (see Figure \ref{fig:awards}) updates its data each time a record is added, deleted, or modified. Currently only the DXCC award is supported (visit http://www.arrl.org/dxcc for more information).
\begin{figure}
\centering
\includegraphics[width=1\columnwidth]{images/awards.png}
\caption{The award progress tracker.}
\label{fig:awards}
\end{figure}
\chapter{Preferences}\label{chap:preferences}
PyQSO user preferences are stored in a configuration file located at \texttt{\textasciitilde/.pyqso.ini}, where \texttt{\textasciitilde} denotes the user's home directory.
\section{General}
Under the \texttt{General} tab, the user can choose to show the toolbox (see Chapter \ref{chap:toolbox}) when PyQSO is started.
The user can also enter their login details to access the qrz.com database. Note that these details are currently stored in plain text (unencrypted) format.
\section{View}
Not all the available fields have to be displayed in the logbook. The user can choose to hide a subset of them by unchecking them in the \texttt{View} tab. PyQSO must be restarted in order for any changes to take effect.
\section{Hamlib support}\label{sect:hamlib}
PyQSO features rudimentary support for the Hamlib library. The name and path of the radio device connected to the user's computer can be specified in the \texttt{Hamlib} tab of the preferences dialog. Upon adding a new record to the log, PyQSO will use Hamlib to retrieve the current frequency that the radio device is set to and automatically fill in the Frequency field.
\bibliographystyle{plainnat}
\end{document}

180
docs/Makefile 100644
Wyświetl plik

@ -0,0 +1,180 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help clean apidoc html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
apidoc:
sphinx-apidoc ../pyqso -o source/ -f -T
html: apidoc
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PyQSO.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PyQSO.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/PyQSO"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PyQSO"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."

242
docs/make.bat 100644
Wyświetl plik

@ -0,0 +1,242 @@
@ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source
set I18NSPHINXOPTS=%SPHINXOPTS% source
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. xml to make Docutils-native XML files
echo. pseudoxml to make pseudoxml-XML files for display purposes
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
%SPHINXBUILD% 2> nul
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\PyQSO.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\PyQSO.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdf" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf
cd %BUILDDIR%/..
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdfja" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf-ja
cd %BUILDDIR%/..
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
if "%1" == "xml" (
%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The XML files are in %BUILDDIR%/xml.
goto end
)
if "%1" == "pseudoxml" (
%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
goto end
)
:end

269
docs/source/conf.py 100644
Wyświetl plik

@ -0,0 +1,269 @@
# -*- coding: utf-8 -*-
#
# PyQSO documentation build configuration file, created by
# sphinx-quickstart on Sun Feb 8 12:09:34 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
print os.path.abspath(".")
sys.path.insert(0, os.path.abspath('../../'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.mathjax',
'sphinx.ext.ifconfig',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'PyQSO'
copyright = u'2015-2018, Christian Thomas Jacobs'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.1.0'
# The full version, including alpha/beta/rc tags.
release = '1.1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = []
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'PyQSOdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'PyQSO.tex', u'PyQSO Documentation',
u'Christian Thomas Jacobs, M0UOS', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'pyqso', u'PyQSO Documentation',
[u'Christian Thomas Jacobs, M0UOS'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'PyQSO', u'PyQSO Documentation',
u'Christian Thomas Jacobs, M0UOS', 'PyQSO', 'A contact logging tool for amateur radio operators.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}

Wyświetl plik

@ -0,0 +1,103 @@
Getting started
===============
Demonstration
-------------
The screencast below demonstrates how to install, configure and use PyQSO (focussing on version 1.0.0 only). Detailed instructions are also available in the sections that follow.
.. raw:: html
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; height: auto;">
<iframe src="https://www.youtube.com/embed/sVdZl9KnDsk" frameborder="0" allowfullscreen style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></iframe>
</div>
System requirements
-------------------
It is recommended that users run PyQSO on the Linux operating system,
since all development and testing of PyQSO takes place there.
As the name suggests, PyQSO is written primarily in the `Python <https://www.python.org/>`_
programming language (version 3.x). The graphical user interface has been developed using
the `GTK+ library <https://www.gtk.org/>`_ through the `PyGObject bindings <https://pygobject.readthedocs.io>`_. PyQSO also uses an
`SQLite <https://www.sqlite.org/>`_ embedded database to manage all the contacts an amateur radio
operator makes. Users must therefore make sure that the Python
interpreter is installed and that any additional software dependencies are satisfied
before PyQSO can be run successfully. The list of software packages that
PyQSO depends on is provided in the ``README.md`` file.
Installation and running
------------------------
Assuming that the current working directory is PyQSO's base directory (the directory that the ``Makefile`` is in), PyQSO can be run without installation by issuing the following command in the terminal:
.. code-block:: bash
python3 bin/pyqso
If the ``pip3`` package manager is available on your system then PyQSO can be installed system-wide using:
.. code-block:: bash
sudo make install
Once installed, the following command will run PyQSO:
.. code-block:: bash
pyqso
Command-line options
~~~~~~~~~~~~~~~~~~~~
There are several options available when executing PyQSO from the
command-line.
Open a specified logbook file
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
In addition to being able to open a new or existing logbook through the
graphical interface, users can also specify a logbook file to open at
the command line with the ``-l`` or ``--logbook`` option. For example, to
open a logbook file called ``mylogbook.db``, use the following command:
.. code-block:: bash
pyqso --logbook /path/to/mylogbook.db
If the file does not already exist, PyQSO will create it.
Debugging mode
^^^^^^^^^^^^^^
Running PyQSO with the ``-d`` or ``--debug`` flag enables the debugging
mode:
.. code-block:: bash
pyqso --debug
All debugging-related messages are written to a file called ``pyqso.debug``,
located in the current working directory.
Creating and opening a logbook
------------------------------
A PyQSO-based logbook is essentially an SQL database. To create a new database/logbook file, click ``Create a New Logbook...`` in the ``Logbook`` menu, choose the directory where you want the file to be saved, and enter the file's name (e.g. ``my_new_logbook.db``). The new logbook will then be opened automatically. If you would like to open an *existing* logbook file, click ``Open an Existing Logbook...`` in the ``Logbook`` menu. Note that logbook files usually have a ``.db`` file extension.
Once the logbook has been opened, its name will appear in the status bar. All logs in the logbook will be opened automatically, and the interface will look something like the one shown in figure:logbook_.
.. _figure:logbook:
.. figure:: images/logbook.png
:align: center
The PyQSO main window, showing the records in a log called ``SO50`` (for contacts via the `amateur radio satellite <https://www.amsat.org/>`_ SO-50), and the World Map tool in the toolbox below it.
Closing a logbook
-----------------
A logbook can be closed by clicking the ``Close Logbook`` button in the toolbar, or by clicking ``Close Logbook`` in the ``Logbook`` menu.

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 10 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 58 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 54 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 202 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 51 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 154 KiB

Wyświetl plik

@ -0,0 +1,21 @@
.. PyQSO documentation master file, created by
sphinx-quickstart on Sun Feb 8 12:09:34 2015.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to PyQSO's documentation!
=================================
Contents:
.. toctree::
:maxdepth: 2
introduction
getting_started
log_management
record_management
toolbox
preferences
shortcuts
pyqso

Wyświetl plik

@ -0,0 +1,69 @@
Introduction
============
Overview
--------
`PyQSO <http://christianjacobs.uk/pyqso>`_ is a logging tool for amateur radio operators. It provides a
simple graphical interface through which users can manage information
about the contacts/QSOs they make with other operators on the air. All
information is stored in a light-weight SQL database. Other key features
include:
- Customisable interface (e.g. only show callsign and frequency information).
- Import logs in `ADIF <http://www.adif.org/>`_ format, and export logs in ADIF or `Cabrillo <http://wwrof.org/cabrillo/>`_ format.
- Perform callsign lookups and auto-fill data fields using the `qrz.com <http://www.qrz.com/>`_ and `hamqth.com <http://www.hamqth.com/>`_ online databases.
- Sort the logs by individual fields.
- Print a hard-copy of logs, or print to PDF.
- Connect to Telnet-based DX clusters.
- Progress tracker for the `DXCC <http://www.arrl.org/dxcc/>`_ award.
- World map with grey line and Maidenhead grid squares.
- Filter QSOs based on callsign (e.g. only display contacts with callsigns beginning with "M6").
- Remove duplicate QSOs.
- Basic support for the `Hamlib <http://hamlib.sourceforge.net/>`_ library.
The source code for PyQSO, written in `Python <https://www.python.org/>`_ (version 3.x), is available for download from the `GitHub repository <https://github.com/ctjacobs/pyqso>`_.
Data storage model
------------------
Many amateur radio operators choose to store all the contacts they ever
make in a single *logbook*, whereas others keep a separate logbook for
each year, for example. Each logbook may be divided up to form multiple
distinct *logs*, perhaps one for casual repeater contacts, another for satellite contacts, and another
for DX'ing. Finally, each log can contain multiple *records*. PyQSO is
based around this three-tier model for data storage, going from logbooks
at the top to individual records at the bottom.
Rather than storing each log in a separate file, a single database can
hold several logs together; in PyQSO, a database is therefore analogous
to a logbook. Within a database the user can create multiple tables
which are analogous to the logs. Within each table the user can
create/modify/delete records which are analogous to the records in each
log.
Licensing
---------
PyQSO is free software, released under the `GNU General Public License <http://www.gnu.org/licenses/gpl-3.0.en.html>`_. Please see the file called ``COPYING`` for more information. A copyright year range of the form YYYY-ZZZZ specifies every single year from YYYY to ZZZZ inclusive (for example, 2012-2017 means 2012, 2013, 2014, 2015, 2016, 2017).
Contact
-------
If you have any comments or questions about PyQSO, please send them via email to Christian Jacobs, M0UOS, at christian@christianjacobs.uk. Bug reports and feature requests can be made via the `issue tracker <https://github.com/ctjacobs/pyqso/issues>`_.
Structure of this documentation
-------------------------------
The structure of this documentation is as follows. The section on `Getting Started <getting_started.html>`_ provides information on the PyQSO installation process through to creating a new logbook (or opening an existing one). The `Log Management <log_management.html>`_ section explains how to create a log in the logbook, as well as the basic operations that users can perform with existing logs, such as printing, importing/exporting logs, and sorting. The `Record Management <record_management.html>`_ section deals with the bottom layer of the three-tier model - the creation, deletion, and modification of QSO records in a log. The `Toolbox <toolbox.html>`_ section introduces the PyQSO toolbox which contains three tools that are useful to amateur radio operators: a DX cluster, a world map, and an awards progress tracker. Finally, the `Preferences <preferences.html>`_ section explains how users can set up Hamlib support and show/hide various fields in a log, along with several other user preferences that can be set via the Preferences dialog window. A `keyboard shortcuts list <shortcuts.html>`_ is also available for reference.

Wyświetl plik

@ -0,0 +1,79 @@
Log management
==============
**Note 1:** All the operations described below assume that a logbook is
already open.
**Note 2:** Any modifications made to the logs are permanent. Users
should make sure they keep up-to-date backups.
Creating a new log
------------------
To create a new log, click ``New Log`` in the ``Logbook`` menu and enter
the desired name of the log in the dialog window that appears (e.g. repeater\_contacts, dx, mobile\_log).
Alternatively, use the shortcut key combination ``Ctrl + N``.
The log name must be unique (i.e. it cannot already exist in the
logbook). Furthermore, it can only be composed of alphanumeric
characters and the underscore character, and the first character in the
name must not be a number.
**Note:** When logs are stored in the database file, field/column names from
the ADIF standard are used. However, please note that only the following
subset of all the ADIF fields is considered: CALL, QSO\_DATE, TIME\_ON,
FREQ, BAND, MODE, SUBMODE, PROP\_MODE, TX\_PWR, RST\_SENT, RST\_RCVD, QSL\_SENT, QSL\_RCVD,
NOTES, NAME, ADDRESS, STATE, COUNTRY, DXCC, CQZ, ITUZ, IOTA, GRIDSQUARE, SAT\_NAME, SAT\_MODE. Visit the `ADIF website <http://adif.org/>`_ for more information about these fields.
Renaming a log
--------------
To rename the currently selected log, click ``Rename Selected Log...`` in
the ``Logbook`` menu. Remember that the log's new name cannot be the
same as another log in the logbook.
Deleting a log
--------------
To delete the currently selected log, click ``Delete Selected Log`` in
the ``Logbook`` menu. As with all database operations in PyQSO, this is
permanent and cannot be undone.
Exporting a log
---------------
While PyQSO stores logbooks in SQL format, it is possible to export
individual logs in the well-known `ADIF <http://www.adif.org/>`_ and `Cabrillo <http://wwrof.org/cabrillo/>`_ formats. Select the log to export,
and click ``Export Log as ADIF...`` or ``Export Log as Cabrillo...`` in the ``Logbook`` menu.
**Note for contesters:** Cabrillo records typically require contest QSO information in the form ``CALL RST EXCH``, where ``EXCH`` denotes exchange information (e.g. a serial number or US state). No dedicated field exists in PyQSO to store exchange information so the RST fields should be used to store both the RST report *and* exchange information, separated by a space. The ``RST Sent`` field should therefore contain the RST and exchange information that you give to the other station (e.g. 59 001), and the ``RST Received`` field should contain the RST and exchange information that the other station gives you (e.g. 57 029). The export process asks for your callsign (this should be the callsign used during the contest) and the contest's name which can be selected from a drop-down list. If the contest name does not appear in this list, you may enter its name manually.
Importing a log
---------------
Records can be imported from an ADIF file. Upon importing,
users can choose to store the records in a new log, or append them to an
existing log in the logbook. To import, click ``Import Log...`` in the
``Logbook`` menu.
Note that each QSO record being imported must conform to the ADIF standard, otherwise the record will be ignored.
Printing a log
--------------
The log that is currently selected can be printed out on paper or printed to a PDF file by clicking ``Print Log...`` in the ``Logbook`` menu. Each page uses a landscape orientation to maximise the amount of QSO information per line. The following data is included: Index, Callsign, Date, Time, Frequency, Mode, RST Sent, and RST Received.
Filtering by callsign
---------------------
Entering an expression such as ``xyz`` into the ``Filter by callsign``
box will instantly filter out all records whose callsign field does not
contain ``xyz``.
Sorting by field
----------------
To sort a log by a particular field name, click the column header
that contains that field name. By default, it is the ``Index`` field
that is sorted in ascending order.

Wyświetl plik

@ -0,0 +1,66 @@
Preferences
===========
PyQSO user preferences are stored in a configuration file located at
``~/.config/pyqso/preferences.ini``, where ``~`` denotes the user's home directory.
General
-------
Under the ``General`` tab, the user can choose to:
- Always show the toolbox (see the `Toolbox <toolbox.html>`_ section) when PyQSO is started.
- Display yearly logbook statistics on the Summary page when a logbook is opened (see figure:summary_).
- Open a default logbook file.
- Keep the ``Add Record`` dialog window open after a new QSO is added, in preparation for the next QSO.
.. _figure:summary:
.. figure:: images/summary.png
:align: center
The Summary page which appears after a logbook is opened. This presents some basic logbook statistics.
View
----
Not all the available fields have to be displayed in the logbook. The user can choose to hide a subset by unchecking them in the ``View`` tab. PyQSO must be restarted in order for any changes to take effect.
Records
-------
The records tab comprises options concerning the Add/Edit Record dialog window. It allows users to:
- Use the UTC timezone when autocompleting the date and time fields.
- Choose whether the band should be automatically determined from the frequency field.
- Specify default values for the Power, Mode, and Submode fields.
- Enter the QSO's frequency in a unit other than MHz (note that the frequency will always be presented in MHz in the main window, regardless of this preference).
- Specify the callsign lookup settings.
Callsign lookup
~~~~~~~~~~~~~~~
The user can enter their login details to access the `qrz.com <http://qrz.com/>`_ or `hamqth.com <http://hamqth.com/>`_ database and perform callsign lookups. Note that these details are currently stored in plain text (unencrypted) format.
If the ``Ignore callsign prefixes and/or suffixes`` box is checked, then PyQSO will perform the callsign lookup whilst ignoring all prefixes (i.e. anything before a preceding "/" in the callsign) and the suffixes "P", "M", "A", "PM", "MM", "AM", and "QRP". For example, if the callsign to be looked up is F/MYCALL/QRP, only MYCALL will be looked up. If you get 'Callsign not found' errors, try enabling this option.
Import/Export
-------------
PyQSO currently supports the ``NOTES`` field in the ADIF specification, but not the ``COMMENTS`` field. When a user imports a log in ADIF format, they can choose to merge any existing text in the ``COMMENTS`` field with the ``NOTES`` field by checking the 'merge' checkbox. This way, no information in the ``COMMENTS`` field is discarded during the import process.
Hamlib support
--------------
PyQSO features rudimentary support for the `Hamlib <http://hamlib.sourceforge.net/>`_ library. The name and path of the radio device connected to the user's computer can be specified in the ``Hamlib`` tab of the preferences dialog. Upon adding a new record to the log, PyQSO will use Hamlib to retrieve the current frequency and mode that the radio device is set to and automatically fill in the Frequency and Mode fields.
World Map
---------
The user can pinpoint their QTH on the world map by specifying the latitude-longitude coordinates (or looking them up based on the QTH's name, e.g. city name) in the ``World Map`` tab. Maidenhead grid squares can also be rendered, with worked grid squares shaded, which is particularly useful for satellite operating.

Wyświetl plik

@ -0,0 +1,190 @@
pyqso package
=============
Submodules
----------
pyqso.adif module
-----------------
.. automodule:: pyqso.adif
:members:
:undoc-members:
:show-inheritance:
pyqso.auxiliary_dialogs module
------------------------------
.. automodule:: pyqso.auxiliary_dialogs
:members:
:undoc-members:
:show-inheritance:
pyqso.awards module
-------------------
.. automodule:: pyqso.awards
:members:
:undoc-members:
:show-inheritance:
pyqso.blank module
------------------
.. automodule:: pyqso.blank
:members:
:undoc-members:
:show-inheritance:
pyqso.cabrillo module
---------------------
.. automodule:: pyqso.cabrillo
:members:
:undoc-members:
:show-inheritance:
pyqso.cabrillo_export_dialog module
-----------------------------------
.. automodule:: pyqso.cabrillo_export_dialog
:members:
:undoc-members:
:show-inheritance:
pyqso.calendar_dialog module
----------------------------
.. automodule:: pyqso.calendar_dialog
:members:
:undoc-members:
:show-inheritance:
pyqso.callsign_lookup module
----------------------------
.. automodule:: pyqso.callsign_lookup
:members:
:undoc-members:
:show-inheritance:
pyqso.compare module
--------------------
.. automodule:: pyqso.compare
:members:
:undoc-members:
:show-inheritance:
pyqso.dx_cluster module
-----------------------
.. automodule:: pyqso.dx_cluster
:members:
:undoc-members:
:show-inheritance:
pyqso.grey_line module
----------------------
.. automodule:: pyqso.grey_line
:members:
:undoc-members:
:show-inheritance:
pyqso.log module
----------------
.. automodule:: pyqso.log
:members:
:undoc-members:
:show-inheritance:
pyqso.log_name_dialog module
----------------------------
.. automodule:: pyqso.log_name_dialog
:members:
:undoc-members:
:show-inheritance:
pyqso.logbook module
--------------------
.. automodule:: pyqso.logbook
:members:
:undoc-members:
:show-inheritance:
pyqso.menu module
-----------------
.. automodule:: pyqso.menu
:members:
:undoc-members:
:show-inheritance:
pyqso.preferences_dialog module
-------------------------------
.. automodule:: pyqso.preferences_dialog
:members:
:undoc-members:
:show-inheritance:
pyqso.printer module
--------------------
.. automodule:: pyqso.printer
:members:
:undoc-members:
:show-inheritance:
pyqso.record_dialog module
--------------------------
.. automodule:: pyqso.record_dialog
:members:
:undoc-members:
:show-inheritance:
pyqso.summary module
--------------------
.. automodule:: pyqso.summary
:members:
:undoc-members:
:show-inheritance:
pyqso.telnet_connection_dialog module
-------------------------------------
.. automodule:: pyqso.telnet_connection_dialog
:members:
:undoc-members:
:show-inheritance:
pyqso.toolbar module
--------------------
.. automodule:: pyqso.toolbar
:members:
:undoc-members:
:show-inheritance:
pyqso.toolbox module
--------------------
.. automodule:: pyqso.toolbox
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: pyqso
:members:
:undoc-members:
:show-inheritance:

Wyświetl plik

@ -0,0 +1,81 @@
Record management
=================
**Note:** Any modifications made to the records are permanent. Users
should make sure they keep up-to-date backups.
Creating a new record (QSO)
---------------------------
A new QSO can be added by either:
- Clicking the ``Add Record`` button in the toolbar.
- Pressing ``Ctrl + R``.
- Clicking ``Add Record...`` in the ``Records`` menu.
A dialog window will appear where details of the QSO can be entered (see
figure:edit_record_). Note that the current date and time
are filled in automatically. When ready, click ``OK`` or press the Enter key to save the
changes.
.. _figure:edit_record:
.. figure:: images/edit_record.png
:align: center
Record dialog used to add new records and edit existing ones.
Callsign lookup
~~~~~~~~~~~~~~~
PyQSO can also resolve station-related information (e.g. the operator's
name, address, and ITU Zone) by clicking the ``Callsign lookup``
button adjacent to the Callsign data entry box. Note that the user must
first supply their `qrz.com <http://qrz.com/>`_ or `hamqth.com <http://hamqth.com/>`_ account information in the preferences dialog
window.
Editing a record
----------------
An existing record can be edited by:
- Double-clicking on it.
- Selecting it and clicking the ``Edit Record`` button in the toolbar.
- Selecting it and clicking ``Edit Selected Record...`` in the
``Records`` menu.
This will bring up the same dialog window as before.
Copying/pasting a record
------------------------
An existing record can be copied and pasted by:
- Selecting it and right-clicking to bring up the popup menu.
- Selecting ``Copy``.
- Right-clicking again and selecting ``Paste``. This will duplicate the record, with the duplicate becoming the latest record in the selected log.
Deleting a record
-----------------
An existing record can be deleted by:
- Selecting it and clicking the ``Delete Record`` button in the
toolbar.
- Selecting it and pressing the ``Delete`` key.
- Selecting it and clicking ``Delete Selected Record...`` in the
``Records`` menu.
Removing duplicate records
--------------------------
PyQSO can find and delete duplicate records in a log. A record is a
duplicate of another if its data in the Callsign, Date, and Time fields are the same. Click ``Remove Duplicate Records`` in the
``Records`` menu.

Wyświetl plik

@ -0,0 +1,16 @@
Keyboard shortcuts
==================
============== ===========
Description Shortcut
============== ===========
Open logbook Ctrl + O
Close logbook Ctrl + W
New log Ctrl + N
Print log Ctrl + P
Quit Ctrl + Q
Add record Ctrl + R
Edit record Ctrl + E
Delete record Delete
============== ===========

Wyświetl plik

@ -0,0 +1,62 @@
Toolbox
=======
The toolbox is hidden by default. To show it, click ``Toolbox`` in the
``View`` menu.
DX cluster
----------
A DX cluster is essentially a server through which amateur radio
operators can report and receive updates about QSOs that are in progress
across the bands. PyQSO is able to connect to a DX cluster that operates
using the Telnet protocol to provide a text-based alert service. As a
result of the many different Telnet-based software products that DX
clusters run, PyQSO currently outputs the raw data received from the DX
cluster rather than trying to parse it in some way.
Click on ``Connect to Telnet Server`` then ``New...`` in the ``Connection`` menu, and enter the DX server
details in the dialog that appears. If no port is specified, PyQSO will
use the default value of 23. A username and password may also need to be
supplied. Frequently used servers can be bookmarked for next time; bookmarked server details are stored in ``~/.config/pyqso/bookmarks.ini``, where ``~`` denotes the user's home directory.
Once connected, the server output will appear in the DX
cluster frame (see figure:dx_cluster_). A command can also
be sent to the server by typing it into the entry box beneath the server output and clicking the
adjacent ``Send Command`` button (or pressing the Enter key).
.. _figure:dx_cluster:
.. figure:: images/dx_cluster.png
:align: center
The DX cluster frame.
World map
---------
The world map tool (see figure:world_map_) can be used to plot the QTH of your station and stations that you have contacted. It also features a grey line to check which parts of the world are in darkness. The position of the grey line is automatically updated every 30 minutes.
The user's QTH can be pinpointed on the map by specifying the QTH's location (e.g. city name) and latitude-longitude coordinates in the preferences. If the `geocoder <https://pypi.python.org/pypi/geocoder>`_ library is installed then these coordinates can be filled in for you by clicking the lookup button after entering the QTH's name, otherwise the coordinates will need to be entered manually.
The location of a worked station may also be plotted by right-clicking on the relevant QSO in the main window and selecting ``Pinpoint`` from the popup menu.
.. _figure:world_map:
.. figure:: images/world_map.png
:align: center
The world map tool with the user's QTH (e.g. Southampton) pinpointed in red, and several other worked stations pinpointed in yellow. Worked grid squares are shaded purple.
Awards
------
The awards progress tracker (see figure:awards_) updates its data
each time a record is added, deleted, or modified. Currently only the
DXCC award is supported (visit the `ARRL DXCC website <http://www.arrl.org/dxcc>`_ for more
information).
.. _figure:awards:
.. figure:: images/awards.png
:align: center
The award progress tracker.

Wyświetl plik

@ -1,7 +1,6 @@
#!/usr/bin/env python
# File: adif.py
#!/usr/bin/env python3
# Copyright (C) 2012 Christian Jacobs.
# Copyright (C) 2012-2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
@ -20,57 +19,71 @@
import re
import logging
import unittest
from datetime import datetime
import calendar
try:
import configparser
except ImportError:
import ConfigParser as configparser
from os.path import expanduser
# ADIF field names and their associated data types available in PyQSO.
AVAILABLE_FIELD_NAMES_TYPES = {"CALL": "S",
"QSO_DATE": "D",
"TIME_ON": "T",
"FREQ": "N",
"BAND": "E",
"MODE": "E",
"TX_PWR": "N",
"RST_SENT": "S",
"RST_RCVD": "S",
"QSL_SENT": "S",
"QSL_RCVD": "S",
"NOTES": "M",
"NAME": "S",
"ADDRESS": "S",
"STATE": "S",
"COUNTRY": "S",
"DXCC": "N",
"CQZ": "N",
"ITUZ": "N",
"IOTA": "C"}
AVAILABLE_FIELD_NAMES_TYPES = {"CALL": "S",
"QSO_DATE": "D",
"TIME_ON": "T",
"FREQ": "N",
"BAND": "E",
"MODE": "E",
"SUBMODE": "E",
"PROP_MODE": "E",
"TX_PWR": "N",
"RST_SENT": "S",
"RST_RCVD": "S",
"QSL_SENT": "S",
"QSL_RCVD": "S",
"NOTES": "M",
"NAME": "S",
"ADDRESS": "S",
"STATE": "S",
"COUNTRY": "S",
"DXCC": "N",
"CQZ": "N",
"ITUZ": "N",
"IOTA": "C",
"GRIDSQUARE": "S",
"SAT_NAME": "S",
"SAT_MODE": "S"}
# Note: The logbook uses the ADIF field names for the database column names.
# This list is used to display the columns in a logical order.
AVAILABLE_FIELD_NAMES_ORDERED = ["CALL", "QSO_DATE", "TIME_ON", "FREQ", "BAND", "MODE", "TX_PWR",
AVAILABLE_FIELD_NAMES_ORDERED = ["CALL", "QSO_DATE", "TIME_ON", "FREQ", "BAND", "MODE", "SUBMODE", "PROP_MODE", "TX_PWR",
"RST_SENT", "RST_RCVD", "QSL_SENT", "QSL_RCVD", "NOTES", "NAME",
"ADDRESS", "STATE", "COUNTRY", "DXCC", "CQZ", "ITUZ", "IOTA"]
"ADDRESS", "STATE", "COUNTRY", "DXCC", "CQZ", "ITUZ", "IOTA", "GRIDSQUARE", "SAT_NAME", "SAT_MODE"]
# Define the more user-friendly versions of the field names.
AVAILABLE_FIELD_NAMES_FRIENDLY = {"CALL":"Callsign",
"QSO_DATE":"Date",
"TIME_ON":"Time",
"FREQ":"Frequency (MHz)",
"BAND":"Band",
"MODE":"Mode",
"TX_PWR":"TX Power (W)",
"RST_SENT":"TX RST",
"RST_RCVD":"RX RST",
"QSL_SENT":"QSL Sent",
"QSL_RCVD":"QSL Received",
"NOTES":"Notes",
"NAME":"Name",
"ADDRESS":"Address",
"STATE":"State",
"COUNTRY":"Country",
"DXCC":"DXCC",
"CQZ":"CQ Zone",
"ITUZ":"ITU Zone",
"IOTA":"IOTA Designator"}
AVAILABLE_FIELD_NAMES_FRIENDLY = {"CALL": "Callsign",
"QSO_DATE": "Date",
"TIME_ON": "Time",
"FREQ": "Frequency (MHz)",
"BAND": "Band",
"MODE": "Mode",
"SUBMODE": "Submode",
"PROP_MODE": "Propagation Mode",
"TX_PWR": "TX Power (W)",
"RST_SENT": "RST Sent",
"RST_RCVD": "RST Received",
"QSL_SENT": "QSL Sent",
"QSL_RCVD": "QSL Received",
"NOTES": "Notes",
"NAME": "Name",
"ADDRESS": "Address",
"STATE": "State",
"COUNTRY": "Country",
"DXCC": "DXCC",
"CQZ": "CQ Zone",
"ITUZ": "ITU Zone",
"IOTA": "IOTA Designator",
"GRIDSQUARE": "Grid Square",
"SAT_NAME": "Satellite Name",
"SAT_MODE": "Satellite Mode"}
# A: AwardList
# B: Boolean
@ -82,409 +95,440 @@ AVAILABLE_FIELD_NAMES_FRIENDLY = {"CALL":"Callsign",
# M: Multi-line string
# G: Multi-line international string
# L: Location
# E: Enumerated
DATA_TYPES = ["A", "B", "N", "S", "I", "D", "T", "M", "G", "L", "E"]
ADIF_VERSION = "1.0"
# All the valid modes listed in the ADIF specification. This is a dictionary with the key-value pairs holding the MODE and SUBMODE(s) respectively.
MODES = {"": ("",),
"AM": ("",),
"ATV": ("",),
"CHIP": ("", "CHIP64", "CHIP128"),
"CLO": ("",),
"CONTESTI": ("",),
"CW": ("", "PCW"),
"DIGITALVOICE": ("",),
"DOMINO": ("", "DOMINOEX", "DOMINOF"),
"DSTAR": ("",),
"FAX": ("",),
"FM": ("",),
"FSK441": ("",),
"FT8": ("",),
"HELL": ("", "FMHELL", "FSKHELL", "HELL80", "HFSK", "PSKHELL"),
"ISCAT": ("", "ISCAT-A", "ISCAT-B"),
"JT4": ("", "JT4A", "JT4B", "JT4C", "JT4D", "JT4E", "JT4F", "JT4G"),
"JT6M": ("",),
"JT9": ("",),
"JT44": ("",),
"JT65": ("", "JT65A", "JT65B", "JT65B2", "JT65C", "JT65C2"),
"MFSK": ("", "MFSK4", "MFSK8", "MFSK11", "MFSK16", "MFSK22", "MFSK31", "MFSK32", "MFSK64", "MFSK128"),
"MT63": ("",),
"OLIVIA": ("", "OLIVIA 4/125", "OLIVIA 4/250", "OLIVIA 8/250", "OLIVIA 8/500", "OLIVIA 16/500", "OLIVIA 16/1000", "OLIVIA 32/1000"),
"OPERA": ("", "OPERA-BEACON", "OPERA-QSO"),
"PAC": ("", "PAC2", "PAC3", "PAC4"),
"PAX": ("", "PAX2"),
"PKT": ("",),
"PSK": ("", "FSK31", "PSK10", "PSK31", "PSK63", "PSK63F", "PSK125", "PSK250", "PSK500", "PSK1000", "PSKAM10", "PSKAM31", "PSKAM50", "PSKFEC31", "QPSK31", "QPSK63", "QPSK125", "QPSK250", "QPSK500"),
"PSK2K": ("",),
"Q15": ("",),
"ROS": ("", "ROS-EME", "ROS-HF", "ROS-MF"),
"RTTY": ("", "ASCI"),
"RTTYM": ("",),
"SSB": ("", "LSB", "USB"),
"SSTV": ("",),
"THOR": ("",),
"THRB": ("", "THRBX"),
"TOR": ("", "AMTORFEC", "GTOR"),
"V4": ("",),
"VOI": ("",),
"WINMOR": ("",),
"WSPR": ("",)
}
# A dictionary of all the deprecated MODE values.
MODES_DEPRECATED = {"AMTORFEC": ("",),
"ASCI": ("",),
"CHIP64": ("",),
"CHIP128": ("",),
"DOMINOF": ("",),
"FMHELL": ("",),
"FSK31": ("",),
"GTOR": ("",),
"HELL80": ("",),
"HFSK": ("",),
"JT4A": ("",),
"JT4B": ("",),
"JT4C": ("",),
"JT4D": ("",),
"JT4E": ("",),
"JT4F": ("",),
"JT4G": ("",),
"JT65A": ("",),
"JT65B": ("",),
"JT65C": ("",),
"MFSK8": ("",),
"MFSK16": ("",),
"PAC2": ("",),
"PAC3": ("",),
"PAX2": ("",),
"PCW": ("",),
"PSK10": ("",),
"PSK31": ("",),
"PSK63": ("",),
"PSK63F": ("",),
"PSK125": ("",),
"PSKAM10": ("",),
"PSKAM31": ("",),
"PSKAM50": ("",),
"PSKFEC31": ("",),
"PSKHELL": ("",),
"QPSK31": ("",),
"QPSK63": ("",),
"QPSK125": ("",),
"THRBX": ("",)
}
# Include all deprecated modes.
MODES.update(MODES_DEPRECATED)
# All the bands listed in the ADIF specification.
BANDS = ["", "2190m", "630m", "560m", "160m", "80m", "60m", "40m", "30m", "20m", "17m", "15m", "12m", "10m", "6m", "4m", "2m", "1.25m", "70cm", "33cm", "23cm", "13cm", "9cm", "6cm", "3cm", "1.25cm", "6mm", "4mm", "2.5mm", "2mm", "1mm"]
# The lower and upper frequency bounds (in MHz) for each band in BANDS.
BANDS_RANGES = [(None, None), (0.136, 0.137), (0.472, 0.479), (0.501, 0.504), (1.8, 2.0), (3.5, 4.0), (5.102, 5.4065), (7.0, 7.3), (10.0, 10.15), (14.0, 14.35), (18.068, 18.168), (21.0, 21.45), (24.890, 24.99), (28.0, 29.7), (50.0, 54.0), (70.0, 71.0), (144.0, 148.0), (222.0, 225.0), (420.0, 450.0), (902.0, 928.0), (1240.0, 1300.0), (2300.0, 2450.0), (3300.0, 3500.0), (5650.0, 5925.0), (10000.0, 10500.0), (24000.0, 24250.0), (47000.0, 47200.0), (75500.0, 81000.0), (119980.0, 120020.0), (142000.0, 149000.0), (241000.0, 250000.0)]
PROPAGATION_MODES = ["", "AS", "AUE", "AUR", "BS", "ECH", "EME", "ES", "F2", "FAI", "INTERNET", "ION", "IRL", "MS", "RPT", "RS", "SAT", "TEP", "TR"]
ADIF_VERSION = "3.0.4"
class ADIF:
""" The ADIF class supplies methods for reading, parsing, and writing log files in the Amateur Data Interchange Format (ADIF). For more information, visit http://adif.org/ """
def __init__(self):
# Class for I/O of files using the Amateur Data Interchange Format (ADIF).
logging.debug("New ADIF instance created!")
def read(self, path):
""" Read an ADIF file with a specified path (given in the 'path' argument), and then parse it.
The output is a list of dictionaries (one dictionary per QSO), with each dictionary containing field-value pairs,
e.g. {FREQ:145.500, BAND:2M, MODE:FM}. """
logging.debug("Reading in ADIF file with path: %s..." % path)
text = ""
try:
f = open(path, 'r')
text = f.read()
f.close() # Close the file, otherwise "bad things" might happen!
except IOError as e:
logging.error("I/O error %d: %s" % (e.errno, e.strerror))
except:
logging.error("Unknown error occurred when reading the ADIF file.")
""" The ADIF class supplies methods for reading, parsing, and writing log files in the Amateur Data Interchange Format (ADIF).
For more information, visit http://adif.org/ """
records = self._parse_adi(text)
if(records == []):
logging.warning("No records found in the file. Empty file or wrong file type?")
return records
def _parse_adi(self, text):
""" Parse some raw text (defined in the 'text' argument) for ADIF field data.
Outputs a list of dictionaries (one dictionary per QSO). Each dictionary contains the field-value pairs,
e.g. {FREQ:145.500, BAND:2M, MODE:FM}. """
def __init__(self):
""" Initialise class for I/O of files using the Amateur Data Interchange Format (ADIF). """
return
logging.debug("Parsing text from the ADIF file...")
def read(self, path):
""" Read an ADIF file and parse it.
records = []
:arg str path: The path to the ADIF file to read.
:returns: A list of dictionaries (one dictionary per QSO), with each dictionary containing field-value pairs, e.g. {FREQ:145.500, BAND:2M, MODE:FM}. If the file cannot be read, the method returns None.
:rtype: list
:raises IOError: If the ADIF file does not exist or cannot be read (e.g. due to lack of read permissions).
"""
logging.debug("Reading in ADIF file with path: %s..." % path)
# Separate the text at the <eor> or <eoh> markers.
tokens = re.split('(<eor>|<eoh>)', text, flags=re.IGNORECASE)
tokens.pop() # Anything after the final <eor> marker should be ignored.
# The header might tell us the number of records, but let's not assume
# this and simply ignore it instead (if it exists).
if(re.search('<eoh>', text, flags=re.IGNORECASE) is not None):
# There is a header present, so let's ignore everything
# up to and including the <eoh> marker. Note that
# re.search has been used here to handle any case sensitivity.
# Previously we were checking for <eoh>. <EOH> is also valid
# but wasn't been detected before.
while len(tokens) > 0:
t = tokens.pop(0)
if(re.match('<eoh>', t, flags=re.IGNORECASE) is not None):
break
n_eor = 0
n_record = 0
records = []
for t in tokens:
if(re.match('<eor>', t, flags=re.IGNORECASE) is not None):
n_eor = n_eor + 1
continue
else:
n_record = n_record + 1
# Each record will have field names and corresponding
# data entries. Store this in a dictionary.
# Note: This is based on the code written by OK4BX.
# (http://web.bxhome.org/blog/ok4bx/2012/05/adif-parser-python)
fields_and_data_dictionary = {}
fields_and_data = re.findall('<(.*?):(\d*).*?>([^<\t\n\r\f\v\Z]+)', t)
for fd in fields_and_data:
# Let's force all field names to be in upper case.
# This will help us later when comparing the field names
# against the available field names in the ADIF specification.
field_name = fd[0].upper()
field_data = fd[2][:int(fd[1])]
text = ""
with open(path, mode="r", errors="replace") as f:
text = f.read()
# Combo boxes are used later on and these are case sensitive,
# so adjust the field data accordingly.
if(field_name == "BAND"):
field_data = field_data.lower()
elif(field_name == "MODE"):
field_data = field_data.upper()
records = self.parse_adi(text)
if(field_name in AVAILABLE_FIELD_NAMES_ORDERED):
field_data_type = AVAILABLE_FIELD_NAMES_TYPES[field_name]
if(self.is_valid(field_name, field_data, field_data_type)):
# Only add the field if it is a standard ADIF field and it holds valid data.
fields_and_data_dictionary[field_name] = field_data
if(records == []):
logging.warning("No records found in the file. Empty file or wrong file type?")
records.append(fields_and_data_dictionary)
assert n_eor == n_record
logging.info("Read %d QSOs from %s in ADIF format." % (len(records), path))
return records
logging.debug("Finished parsing text.")
return records
def parse_adi(self, text):
""" Parse some raw text (defined in the 'text' argument) for ADIF field data.
:arg str text: The raw text from the ADIF file to parse.
:returns: A list of dictionaries (one dictionary per QSO). Each dictionary contains the field-value pairs, e.g. {"FREQ": "145.500", "BAND": "2M", "MODE": "FM"}.
:rtype: list
"""
logging.debug("Parsing text from the ADIF file...")
records = []
# ADIF-related configuration options
config = configparser.ConfigParser()
have_config = (config.read(expanduser("~/.config/pyqso/preferences.ini")) != [])
(section, option) = ("import_export", "merge_comment")
if(have_config and config.has_option(section, option) and config.getboolean(section, option)):
merge_comment = True
else:
merge_comment = False
# Separate the text at the <eor> or <eoh> markers.
tokens = re.split("(<eor>|<eoh>)", text, flags=re.IGNORECASE)
tokens.pop() # Anything after the final <eor> marker should be ignored.
# The header might tell us the number of records, but let's not assume
# this and simply ignore it instead (if it exists).
if(re.search("<eoh>", text, flags=re.IGNORECASE) is not None):
# There is a header present, so let's ignore everything
# up to and including the <eoh> marker.
while len(tokens) > 0:
t = tokens.pop(0)
if(re.match("<eoh>", t, flags=re.IGNORECASE) is not None):
break
n_eor = 0
n_record = 0
records = []
pattern = re.compile("<(.*?):(\d*).*?>([^<]+)")
for t in tokens:
if(re.match("<eor>", t, flags=re.IGNORECASE) is not None):
n_eor += 1
continue
else:
n_record += 1
# Each record will have field names and corresponding
# data entries. Store this in a dictionary.
# Note: This is based on the code written by OK4BX.
# (http://web.bxhome.org/blog/ok4bx/2012/05/adif-parser-python)
fields_and_data_dictionary = {}
fields_and_data = pattern.findall(t)
comment = None
for fd in fields_and_data:
# Let's force all field names to be in upper case.
# This will help us later when comparing the field names
# against the available field names in the ADIF specification.
field_name = fd[0].upper()
# Only read in the number of characters specified by the data length.
field_data = fd[2][:int(fd[1])]
# Combo boxes are used later on and these are case sensitive,
# so adjust the field data accordingly.
if(field_name == "BAND"):
field_data = field_data.lower()
elif(field_name == "CALL" or field_name == "MODE" or field_name == "SUBMODE"):
field_data = field_data.upper()
elif(field_name == "COMMENT"):
# Keep a copy of the COMMENT field data, in case we want to merge
# it with the NOTES field.
comment = field_data
if(field_name in AVAILABLE_FIELD_NAMES_ORDERED):
field_data_type = AVAILABLE_FIELD_NAMES_TYPES[field_name]
if(self.is_valid(field_name, field_data, field_data_type)):
# Only add the field if it is a standard ADIF field and it holds valid data.
fields_and_data_dictionary[field_name] = field_data
# Merge the COMMENT field with the NOTES field, if desired and applicable.
if(merge_comment):
if("NOTES" in list(fields_and_data_dictionary.keys()) and comment):
logging.debug("Merging COMMENT field with NOTES field...")
fields_and_data_dictionary["NOTES"] += "\n" + comment
logging.debug("Merged fields.")
elif(comment):
# Create the NOTES entry, but only store the contents of the COMMENT field.
logging.debug("The COMMENT field is present, but not the NOTES field. The NOTES field will be created and will only hold the COMMENT.")
fields_and_data_dictionary["NOTES"] = comment
else:
pass
records.append(fields_and_data_dictionary)
assert n_eor == n_record
logging.debug("Finished parsing text.")
return records
def write(self, records, path):
""" Write an ADIF file containing all the QSOs in the 'records' list.
:arg list records: The list of QSO records to write.
:arg str path: The desired path of the ADIF file to write to.
:returns: None
:raises IOError: If the ADIF file cannot be written (e.g. due to lack of write permissions).
"""
logging.debug("Writing records to an ADIF file...")
with open(path, mode="w", errors="replace") as f: # Open file for writing
# First write a header containing program version, number of records, etc.
dt = datetime.now()
f.write("""Amateur radio log file. Generated on %s. Contains %d record(s).
def write(self, records, path):
""" Write an ADIF file containing all the QSOs in the 'records' list. The desired path is specified in the 'path' argument.
This method returns None. """
logging.debug("Writing records to an ADIF file...")
try:
f = open(path, 'w') # Open file for writing
# First write a header containing program version, number of records, etc.
dt = datetime.now()
f.write("""Amateur radio log file. Generated on %s. Contains %d record(s).
<adif_ver:%d>%s
<programid:5>PyQSO
<programversion:3>0.1
<programversion:5>1.1.0
<eoh>\n""" % (dt, len(records), len(str(ADIF_VERSION)), ADIF_VERSION))
# Then write each log to the file.
for r in records:
for field_name in AVAILABLE_FIELD_NAMES_ORDERED:
if(not(field_name.lower() in r.keys() or field_name.upper() in r.keys())):
# If the field_name does not exist in the record, then skip past it.
# Only write out the fields that exist and that have some data in them.
continue
else:
if( (r[field_name] != "NULL") and (r[field_name] != "") ):
f.write("<%s:%d>%s\n" % (field_name.lower(), len(r[field_name]), r[field_name]))
f.write("<eor>\n")
logging.debug("Finished writing records to the ADIF file.")
f.close()
# Then write each record to the file.
for r in records:
for field_name in AVAILABLE_FIELD_NAMES_ORDERED:
if(not(field_name.lower() in list(r.keys()) or field_name.upper() in list(r.keys()))):
# If the field_name does not exist in the record, then skip past it.
# Only write out the fields that exist and that have some data in them.
continue
else:
if((r[field_name] != "NULL") and (r[field_name] != "")):
f.write("<%s:%d>%s\n" % (field_name.lower(), len(r[field_name]), r[field_name]))
f.write("<eor>\n")
except IOError as e:
logging.error("I/O error %d: %s" % (e.errno, e.strerror))
except:
logging.error("Unknown error occurred when writing the ADIF file.")
logging.debug("Finished writing records to the ADIF file.")
f.close()
return
logging.info("Wrote %d QSOs to %s in ADIF format." % (len(records), path))
return
def is_valid(self, field_name, data, data_type):
""" Validate the data in a field (with name 'field_name') with respect to the ADIF specification.
This method returns either True or False to indicate whether the data is valid or not. """
def is_valid(self, field_name, data, data_type):
""" Validate the data in a field with respect to the ADIF specification.
logging.debug("Validating the following data in field '%s': %s" % (field_name, data))
:arg str field_name: The name of the ADIF field.
:arg str data: The data of the ADIF field to validate.
:arg str data_type: The type of data to be validated. See http://www.adif.org/304/ADIF_304.htm#Data_Types for the full list with descriptions.
:returns: True or False to indicate whether the data is valid or not.
:rtype: bool
"""
# Allow an empty string, in case the user doesn't want
# to fill in this field.
if(data == ""):
return True
logging.debug("Validating the following data in field '%s': %s" % (field_name, data))
if(data_type == "N"):
# Allow a decimal point before and/or after any numbers,
# but don't allow a decimal point on its own.
m = re.match(r"-?(([0-9]+\.?[0-9]*)|([0-9]*\.?[0-9]+))", data)
if(m is None):
# Did not match anything.
return False
else:
# Make sure we match the whole string,
# otherwise there may be an invalid character after the match.
return (m.group(0) == data)
elif(data_type == "B"):
# Boolean
m = re.match(r"(Y|N)", data)
if(m is None):
return False
else:
return (m.group(0) == data)
elif(data_type == "D"):
# Date
pattern = re.compile(r"([0-9]{4})")
m_year = pattern.match(data, 0)
if((m_year is None) or (int(m_year.group(0)) < 1930)):
# Did not match anything.
return False
else:
pattern = re.compile(r"([0-9]{2})")
m_month = pattern.match(data, 4)
if((m_month is None) or int(m_month.group(0)) > 12 or int(m_month.group(0)) < 1):
# Did not match anything.
return False
else:
pattern = re.compile(r"([0-9]{2})")
m_day = pattern.match(data, 6)
days_in_month = calendar.monthrange(int(m_year.group(0)), int(m_month.group(0)))
if((m_day is None) or int(m_day.group(0)) > days_in_month[1] or int(m_day.group(0)) < 1):
# Did not match anything.
return False
else:
# Make sure we match the whole string,
# otherwise there may be an invalid character after the match.
return (len(data) == 8)
elif(data_type == "T"):
# Time
pattern = re.compile(r"([0-9]{2})")
m_hour = pattern.match(data, 0)
if((m_hour is None) or (int(m_hour.group(0)) < 0) or (int(m_hour.group(0)) > 23)):
# Did not match anything.
return False
else:
pattern = re.compile(r"([0-9]{2})")
m_minutes = pattern.match(data, 2)
if((m_minutes is None) or int(m_minutes.group(0)) < 0 or int(m_minutes.group(0)) > 59):
# Did not match anything.
return False
else:
if(len(data) == 4):
# HHMM format
return True
pattern = re.compile(r"([0-9]{2})")
m_seconds = pattern.match(data, 4)
if((m_seconds is None) or int(m_seconds.group(0)) < 0 or int(m_seconds.group(0)) > 59):
# Did not match anything.
return False
else:
# Make sure we match the whole string,
# otherwise there may be an invalid character after the match.
return (len(data) == 6) # HHMMSS format
#FIXME: Need to make sure that the "S" and "M" data types accept ASCII-only characters
# in the range 32-126 inclusive.
elif(data_type == "S"):
# String
m = re.match(r"(.+)", data)
if(m is None):
return False
else:
return (m.group(0) == data)
elif(data_type == "I"):
# IntlString
m = re.match(ur"(.+)", data, re.UNICODE)
if(m is None):
return False
else:
return (m.group(0) == data)
elif(data_type == "G"):
# IntlMultilineString
m = re.match(ur"(.+(\r\n)*.*)", data, re.UNICODE)
if(m is None):
return False
else:
return (m.group(0) == data)
elif(data_type == "M"):
# MultilineString
#m = re.match(r"(.+(\r\n)*.*)", data)
#if(m is None):
# return False
#else:
# return (m.group(0) == data)
return True
elif(data_type == "L"):
# Location
pattern = re.compile(r"([EWNS]{1})", re.IGNORECASE)
m_directional = pattern.match(data, 0)
if(m_directional is None):
# Did not match anything.
return False
else:
pattern = re.compile(r"([0-9]{3})")
m_degrees = pattern.match(data, 1)
if((m_degrees is None) or int(m_degrees.group(0)) < 0 or int(m_degrees.group(0)) > 180):
# Did not match anything.
return False
else:
pattern = re.compile(r"([0-9]{2}\.[0-9]{3})")
m_minutes = pattern.match(data, 4)
if((m_minutes is None) or float(m_minutes.group(0)) < 0 or float(m_minutes.group(0)) > 59.999):
# Did not match anything.
return False
else:
# Make sure we match the whole string,
# otherwise there may be an invalid character after the match.
return (len(data) == 10)
elif(data_type == "E" or data_type == "A"):
# Enumeration, AwardList.
if(field_name == "MODE"):
modes = ["", "AM", "AMTORFEC", "ASCI", "ATV", "CHIP64", "CHIP128", "CLO", "CONTESTI", "CW", "DSTAR", "DOMINO", "DOMINOF", "FAX", "FM", "FMHELL", "FSK31", "FSK441", "GTOR", "HELL", "HELL80", "HFSK", "ISCAT", "JT44", "JT4A", "JT4B", "JT4C", "JT4D", "JT4E", "JT4F", "JT4G", "JT65", "JT65A", "JT65B", "JT65C", "JT6M", "MFSK8", "MFSK16", "MT63", "OLIVIA", "PAC", "PAC2", "PAC3", "PAX", "PAX2", "PCW", "PKT", "PSK10", "PSK31", "PSK63", "PSK63F", "PSK125", "PSKAM10", "PSKAM31", "PSKAM50", "PSKFEC31", "PSKHELL", "Q15", "QPSK31", "QPSK63", "QPSK125", "ROS", "RTTY", "RTTYM", "SSB", "SSTV", "THRB", "THOR", "THRBX", "TOR", "V4", "VOI", "WINMOR", "WSPR"]
return (data in modes)
elif(field_name == "BAND"):
bands = ["", "2190m", "560m", "160m", "80m", "60m", "40m", "30m", "20m", "17m", "15m", "12m", "10m", "6m", "4m", "2m", "1.25m", "70cm", "33cm", "23cm", "13cm", "9cm", "6cm", "3cm", "1.25cm", "6mm", "4mm", "2.5mm", "2mm", "1mm"]
return (data in bands)
else:
# Allow an empty string or None, in case the user doesn't want
# to fill in this field.
if(not data):
return True
else:
return True
class TestADIF(unittest.TestCase):
if(data_type == "N"):
# Allow a decimal point before and/or after any numbers,
# but don't allow a decimal point on its own.
m = re.match(r"-?(([0-9]+\.?[0-9]*)|([0-9]*\.?[0-9]+))", data)
if(m is None):
# Did not match anything.
return False
else:
# Make sure we match the whole string,
# otherwise there may be an invalid character after the match.
return (m.group(0) == data)
def setUp(self):
self.adif = ADIF()
elif(data_type == "B"):
# Boolean
m = re.match(r"(Y|N)", data)
if(m is None):
return False
else:
return (m.group(0) == data)
def test_adif_read(self):
f = open("ADIF.test_read.adi", 'w')
f.write("""Some test ADI data.<eoh>
elif(data_type == "D"):
# Date
pattern = re.compile(r"([0-9]{4})")
m_year = pattern.match(data, 0)
if((m_year is None) or (int(m_year.group(0)) < 1930)):
# Did not match anything.
return False
else:
pattern = re.compile(r"([0-9]{2})")
m_month = pattern.match(data, 4)
if((m_month is None) or int(m_month.group(0)) > 12 or int(m_month.group(0)) < 1):
# Did not match anything.
return False
else:
pattern = re.compile(r"([0-9]{2})")
m_day = pattern.match(data, 6)
days_in_month = calendar.monthrange(int(m_year.group(0)), int(m_month.group(0)))
if((m_day is None) or int(m_day.group(0)) > days_in_month[1] or int(m_day.group(0)) < 1):
# Did not match anything.
return False
else:
# Make sure we match the whole string,
# otherwise there may be an invalid character after the match.
return (len(data) == 8)
<call:4>TEST<band:3>40m<mode:2>CW
<qso_date:8:d>20130322<time_on:4>1955<eor>""")
f.close()
records = self.adif.read("ADIF.test_read.adi")
expected_records = [{'TIME_ON': '1955', 'BAND': '40m', 'CALL': 'TEST', 'MODE': 'CW', 'QSO_DATE': '20130322'}]
print "Imported records: ", records
print "Expected records: ", expected_records
assert(len(records) == 1)
assert(len(records[0].keys()) == len(expected_records[0].keys()))
assert(records == expected_records)
elif(data_type == "T"):
# Time
pattern = re.compile(r"([0-9]{2})")
m_hour = pattern.match(data, 0)
if((m_hour is None) or (int(m_hour.group(0)) < 0) or (int(m_hour.group(0)) > 23)):
# Did not match anything.
return False
else:
pattern = re.compile(r"([0-9]{2})")
m_minutes = pattern.match(data, 2)
if((m_minutes is None) or int(m_minutes.group(0)) < 0 or int(m_minutes.group(0)) > 59):
# Did not match anything.
return False
else:
if(len(data) == 4):
# HHMM format
return True
pattern = re.compile(r"([0-9]{2})")
m_seconds = pattern.match(data, 4)
if((m_seconds is None) or int(m_seconds.group(0)) < 0 or int(m_seconds.group(0)) > 59):
# Did not match anything.
return False
else:
# Make sure we match the whole string,
# otherwise there may be an invalid character after the match.
return (len(data) == 6) # HHMMSS format
def test_adif_write(self):
records = [{"CALL":"TEST123", "QSO_DATE":"20120402", "TIME_ON":"1234", "FREQ":"145.500", "BAND":"2m", "MODE":"FM", "RST_SENT":"59", "RST_RCVD":"59"},
{"CALL":"TEST123", "QSO_DATE":"20130312", "TIME_ON":"0101", "FREQ":"145.750", "BAND":"2m", "MODE":"FM"}]
self.adif.write(records, "ADIF.test_write.adi")
# FIXME: Need to make sure that the "S" and "M" data types accept ASCII-only characters
# in the range 32-126 inclusive.
elif(data_type == "S"):
# String
m = re.match(r"(.+)", data)
if(m is None):
return False
else:
return (m.group(0) == data)
f = open("ADIF.test_write.adi", 'r')
text = f.read()
print "File 'ADIF.test_write.adi' contains the following text:", text
assert("""
<adif_ver:3>1.0
<programid:5>PyQSO
<programversion:3>0.1
<eoh>
<call:7>TEST123
<qso_date:8>20120402
<time_on:4>1234
<freq:7>145.500
<band:2>2m
<mode:2>FM
<rst_sent:2>59
<rst_rcvd:2>59
<eor>
<call:7>TEST123
<qso_date:8>20130312
<time_on:4>0101
<freq:7>145.750
<band:2>2m
<mode:2>FM
<eor>
""" in text) # Ignore the header line here, since it contains the date and time the ADIF file was written, which will change each time 'make unittest' is run.
f.close()
elif(data_type == "I"):
# IntlString
m = re.match(r"(.+)", data, re.UNICODE)
if(m is None):
return False
else:
return (m.group(0) == data)
def test_adif_write_sqlite3_Row(self):
import sqlite3
self.connection = sqlite3.connect("./unittest_resources/test.db")
self.connection.row_factory = sqlite3.Row
elif(data_type == "G"):
# IntlMultilineString
m = re.match(r"(.+(\r\n)*.*)", data, re.UNICODE)
if(m is None):
return False
else:
return (m.group(0) == data)
c = self.connection.cursor()
c.execute("SELECT * FROM test")
records = c.fetchall()
print records
elif(data_type == "M"):
# MultilineString
# m = re.match(r"(.+(\r\n)*.*)", data)
# if(m is None):
# return False
# else:
# return (m.group(0) == data)
return True
self.adif.write(records, "ADIF.test_write_sqlite3_Row.adi")
elif(data_type == "L"):
# Location
pattern = re.compile(r"([EWNS]{1})", re.IGNORECASE)
m_directional = pattern.match(data, 0)
if(m_directional is None):
# Did not match anything.
return False
else:
pattern = re.compile(r"([0-9]{3})")
m_degrees = pattern.match(data, 1)
if((m_degrees is None) or int(m_degrees.group(0)) < 0 or int(m_degrees.group(0)) > 180):
# Did not match anything.
return False
else:
pattern = re.compile(r"([0-9]{2}\.[0-9]{3})")
m_minutes = pattern.match(data, 4)
if((m_minutes is None) or float(m_minutes.group(0)) < 0 or float(m_minutes.group(0)) > 59.999):
# Did not match anything.
return False
else:
# Make sure we match the whole string,
# otherwise there may be an invalid character after the match.
return (len(data) == 10)
f = open("ADIF.test_write_sqlite3_Row.adi", 'r')
text = f.read()
print "File 'ADIF.test_write_sqlite3_Row.adi' contains the following text:", text
assert("""
<adif_ver:3>1.0
<programid:5>PyQSO
<programversion:3>0.1
<eoh>
<call:7>TEST123
<qso_date:8>20120402
<time_on:4>1234
<freq:7>145.500
<band:2>2m
<mode:2>FM
<rst_sent:2>59
<rst_rcvd:2>59
<eor>
<call:7>TEST456
<qso_date:8>20130312
<time_on:4>0101
<freq:7>145.750
<band:2>2m
<mode:2>FM
<eor>
""" in text) # Ignore the header line here, since it contains the date and time the ADIF file was written, which will change each time 'make unittest' is run.
f.close()
self.connection.close()
def test_adif_is_valid(self):
assert(self.adif.is_valid("CALL", "TEST123", "S") == True)
assert(self.adif.is_valid("QSO_DATE", "20120402", "D") == True)
assert(self.adif.is_valid("TIME_ON", "1230", "T") == True)
assert(self.adif.is_valid("TX_PWR", "5", "N") == True)
if(__name__ == '__main__'):
unittest.main()
elif(data_type == "E" or data_type == "A"):
# Enumeration, AwardList.
if(field_name == "MODE"):
return (data in list(MODES.keys()))
elif(field_name == "SUBMODE"):
submodes = [submode for mode in list(MODES.keys()) for submode in MODES[mode]]
return (data in submodes)
elif(field_name == "BAND"):
return (data in BANDS)
else:
return True
else:
return True

Wyświetl plik

@ -1,7 +1,6 @@
#!/usr/bin/env python
# File: auxiliary_dialogs.py
#!/usr/bin/env python3
# Copyright (C) 2013 Christian Jacobs.
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
@ -18,32 +17,56 @@
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk, GObject
from gi.repository import Gtk
import logging
def error(parent, message):
""" Display an error message. """
logging.error(message)
dialog = Gtk.MessageDialog(parent, Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, message)
dialog.run()
dialog.destroy()
return
""" Display an error message.
:arg parent: The Gtk parent window/dialog.
:arg str message: The message to display to the user.
"""
logging.error(message)
handle_gtk_dialog(parent, Gtk.MessageType.ERROR, message, "Error")
def info(parent, message):
""" Display some information. """
logging.debug(message)
dialog = Gtk.MessageDialog(parent, Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.INFO, Gtk.ButtonsType.OK, message)
dialog.run()
dialog.destroy()
return
""" Display some information.
:arg parent: The Gtk parent window/dialog.
:arg str message: The message to display to the user.
"""
logging.info(message)
handle_gtk_dialog(parent, Gtk.MessageType.INFO, message, "Information")
def question(parent, message):
""" Ask the user a question. The dialog comes with 'Yes' and 'No' response buttons. """
dialog = Gtk.MessageDialog(parent, Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.QUESTION, Gtk.ButtonsType.YES_NO,
message)
response = dialog.run()
dialog.destroy()
return response
""" Ask the user a question. The dialog comes with 'Yes' and 'No' response buttons.
:arg parent: The Gtk parent window/dialog.
:arg str message: The message to display to the user.
:returns: The 'yes'/'no' response from the user.
:rtype: Gtk.ResponseType
"""
return handle_gtk_dialog(parent, Gtk.MessageType.QUESTION, message, "Question")
def handle_gtk_dialog(parent, msgtype, message, title):
"""
Instantiate and present a dialog to the user.
:arg parent: The Gtk parent window/dialog.
:arg Gtk.MessageType msgtype: The type of message to present to the user (e.g. a question, or error message).
:arg str message: The message to display in the dialog.
:arg str title: The title to display at the top of the dialog.
:returns: The response from the user, based on which button they pushed.
:rtype: Gtk.ResponseType
"""
bt = Gtk.ButtonsType
buttons = bt.YES_NO if msgtype == Gtk.MessageType.QUESTION else bt.OK
dialog = Gtk.MessageDialog(parent, Gtk.DialogFlags.DESTROY_WITH_PARENT,
msgtype, buttons, message, title=title)
response = dialog.run()
dialog.destroy()
return response

Wyświetl plik

@ -1,7 +1,6 @@
#!/usr/bin/env python
# File: awards.py
#!/usr/bin/env python3
# Copyright (C) 2013 Christian Jacobs.
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
@ -18,88 +17,101 @@
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk, GObject
from gi.repository import Gtk
import logging
import sqlite3 as sqlite
class Awards(Gtk.VBox):
""" A tool for tracking progress towards an award. Currently this only supports the DXCC award. For more information visit http://www.arrl.org/dxcc """
def __init__(self, parent):
""" Set up a table for progress tracking purposes. """
#TODO: This only considers the DXCC award for now.
logging.debug("New Awards instance created!")
Gtk.VBox.__init__(self, spacing=2)
self.parent = parent
class Awards:
self.bands = ["70cm", "2m", "6m", "10m", "12m", "15m", "17m", "20m", "30m", "40m", "80m", "160m"]
self.modes = ["Phone", "CW", "Digital", "Mixed"]
data_types = [str] + [int]*len(self.bands)
self.awards = Gtk.ListStore(*data_types)
""" A tool for tracking progress towards an award. Currently this only supports the DXCC award.
For more information visit http://www.arrl.org/dxcc """
# The main table for the awards
self.treeview = Gtk.TreeView(self.awards)
# A separate, empty column just for the mode names
renderer = Gtk.CellRendererText()
column = Gtk.TreeViewColumn("Modes", renderer, text=0)
column.set_clickable(False)
self.treeview.append_column(column)
# Now for all the bands...
logging.debug("Initialising the columns in the awards table.")
for i in range(0, len(self.bands)):
renderer = Gtk.CellRendererText()
column = Gtk.TreeViewColumn(self.bands[i], renderer, text=i+1)
column.set_min_width(40)
column.set_clickable(False)
self.treeview.append_column(column)
def __init__(self, application):
""" Set up a table for progress tracking purposes.
# Add a label to inform the user that this only considers the DXCC award for now.
label = Gtk.Label(halign=Gtk.Align.START)
label.set_markup("<span size=\"x-large\">%s</span>" % "DXCC Award")
self.pack_start(label, False, False, 4)
# Show the table in the Awards tab
self.add(self.treeview)
self.show_all()
:arg application: The PyQSO application containing the main Gtk window, etc.
"""
# TODO: Add more awards. This only considers the DXCC award for now.
logging.debug("Setting up awards table...")
logging.debug("Awards table set up successfully.")
self.application = application
self.builder = self.application.builder
self.count()
self.bands = ["70cm", "2m", "6m", "10m", "12m", "15m", "17m", "20m", "30m", "40m", "80m", "160m"]
self.modes = ["Phone", "CW", "Digital", "Mixed"]
return
data_types = [str] + [int]*len(self.bands)
self.awards = Gtk.ListStore(*data_types)
def count(self):
""" Update the table for progress tracking. """
logging.debug("Counting the band/mode combinations for the awards table...")
# Wipe everything and start again
self.awards.clear()
# For each mode, add a new list for holding the totals, and initialise the values to zero.
count = []
for i in range(0, len(self.bands)):
count.append([0]*len(self.bands))
# The main table for the awards.
self.treeview = Gtk.TreeView(model=self.awards)
# A separate, empty column just for the mode names.
renderer = Gtk.CellRendererText()
column = Gtk.TreeViewColumn("Modes", renderer, text=0)
column.set_clickable(False)
self.treeview.append_column(column)
# Now for all the bands...
logging.debug("Initialising the columns in the awards table.")
for i in range(0, len(self.bands)):
renderer = Gtk.CellRendererText()
column = Gtk.TreeViewColumn(self.bands[i], renderer, text=i+1)
column.set_min_width(40)
column.set_clickable(False)
self.treeview.append_column(column)
for log in self.parent.logbook.logs:
records = log.get_all_records()
if(records is not None):
for r in records:
if(r["BAND"] is not None and r["MODE"] is not None):
if(r["BAND"].lower() in self.bands and r["MODE"] != ""):
band = self.bands.index(r["BAND"].lower())
# Phone modes
if(r["MODE"].upper() in ["FM", "AM", "SSB", "SSTV"]):
count[0][band] += 1
elif(r["MODE"].upper() == "CW"):
count[1][band] += 1
else:
#FIXME: This assumes that all the other modes in the ADIF list are digital modes. Is this the case?
count[2][band] += 1
count[3][band] += 1 # Keep the total of each column in the "Mixed" mode
else:
logging.error("Could not update the awards table for '%s' because of a database error." % log.name)
# Insert the rows containing the totals
for i in range(0, len(self.modes)):
self.awards.append([self.modes[i]] + count[i])
logging.debug("Awards table updated.")
return
# Show the table in the Awards tab.
self.builder.get_object("awards").add(self.treeview)
self.builder.get_object("awards").show_all()
logging.debug("Awards table set up successfully.")
self.count(self.application.logbook)
return
def count(self, logbook):
""" Update the table for progress tracking.
:arg logbook: The logbook containing logs which in turn contain QSOs.
:returns: A list of lists containing the QSO counts for different modes and bands.
:rtype: list
"""
logging.debug("Counting the band/mode combinations for the awards table...")
# Wipe everything and start again.
self.awards.clear()
# For each mode, add a new list for holding the totals, and initialise the values to zero.
count = []
for i in range(0, len(self.bands)):
count.append([0]*len(self.bands))
for log in logbook.logs:
try:
records = log.records
for r in records:
if(r["BAND"] is not None and r["MODE"] is not None):
if(r["BAND"].lower() in self.bands and r["MODE"] != ""):
band = self.bands.index(r["BAND"].lower())
# Phone modes
if(r["MODE"].upper() in ["FM", "AM", "SSB", "SSTV"]):
count[0][band] += 1
elif(r["MODE"].upper() == "CW"):
count[1][band] += 1
else:
# FIXME: This assumes that all the other modes in the ADIF list are digital modes. Is this the case?
count[2][band] += 1
count[3][band] += 1 # Keep the total of each column in the "Mixed" mode.
except sqlite.Error as e:
logging.error("Could not update the awards table for '%s' because of a database error." % log.name)
logging.exception(e)
# Insert the rows containing the totals.
for i in range(0, len(self.modes)):
self.awards.append([self.modes[i]] + count[i])
logging.debug("Awards table updated.")
return count

62
pyqso/blank.py 100644
Wyświetl plik

@ -0,0 +1,62 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk
class Blank(object):
""" A blank page in the logbook for the "+" (New Log) tab. """
def __init__(self, application):
""" Create the blank page.
:arg application: The PyQSO application containing the main Gtk window, etc.
"""
self.application = application
blank_treeview = Gtk.TreeView()
# Allow the (blank) page to be scrolled up/down
sw = Gtk.ScrolledWindow()
sw.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
sw.add(blank_treeview)
page = Gtk.VBox()
page.pack_start(sw, True, True, 0)
# Add a "+" button to the tab
tab = Gtk.HBox(homogeneous=False, spacing=0)
icon = Gtk.Image.new_from_icon_name(Gtk.STOCK_ADD, Gtk.IconSize.MENU)
button = Gtk.Button()
button.set_relief(Gtk.ReliefStyle.NONE)
button.set_focus_on_click(False)
button.connect("clicked", self.application.logbook.new_log)
button.add(icon)
button.set_tooltip_text('New Log')
tab.pack_start(button, False, False, 0)
tab.show_all()
page.show_all()
self.application.logbook.notebook.insert_page(page, tab, 1)
self.application.logbook.notebook.set_current_page(0)
return

105
pyqso/cabrillo.py 100644
Wyświetl plik

@ -0,0 +1,105 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
import logging
CABRILLO_VERSION = "3.0"
CONTESTS = ["", "AP-SPRINT", "ARRL-10", "ARRL-160", "ARRL-222", "ARRL-DX-CW", "ARRL-DX-SSB", "ARRL-RR-PH", "ARRL-RR-DIG", "ARRL-RR-CW", "ARRL-SCR", "ARRL-SS-CW", "ARRL-SS-SSB", "ARRL-UHF-AUG", "ARRL-VHF-JAN", "ARRL-VHF-JUN", "ARRL-VHF-SEP", "ARRL-RTTY", "BARTG-RTTY", "CQ-160-CW", "CQ-160-SSB", "CQ-WPX-CW", "CQ-WPX-RTTY", "CQ-WPX-SSB", "CQ-VHF", "CQ-WW-CW", "CQ-WW-RTTY", "CQ-WW-SSB", "DARC-WAEDC-CW", "DARC-WAEDC-RTTY", "DARC-WAEDC-SSB", "DL-DX-RTTY", "DRCG-WW-RTTY", "FCG-FQP", "IARU-HF", "JIDX-CW", "JIDX-SSB", "NAQP-CW", "NAQP-SSB", "NA-SPRINT-CW", "NA-SPRINT-SSB", "NCCC-CQP", "NEQP", "OCEANIA-DX-CW", "OCEANIA-DX-SSB", "RDXC", "RSGB-IOTA", "SAC-CW", "SAC-SSB", "STEW-PERRY", "TARA-RTTY"]
class Cabrillo:
""" The Cabrillo class supplies methods for writing log files in the Cabrillo format (v3.0).
For more information, visit http://wwrof.org/cabrillo/ """
def __init__(self):
""" Initialise class for I/O of files using the Cabrillo format. """
return
def write(self, records, path, contest="", mycall=""):
""" Write a list of QSO records to a file in the Cabrillo format.
:arg list records: The list of QSO records to write.
:arg str path: The desired path of the Cabrillo file to write to.
:arg str contest: The name of the contest.
:arg str mycall: The callsign used during the contest.
:returns: None
:raises IOError: If the Cabrillo file cannot be written (e.g. due to lack of write permissions)."""
logging.debug("Writing records to a Cabrillo file...")
with open(path, mode='w', errors="replace") as f: # Open file for writing
# Header
f.write("""START-OF-LOG: %s\n""" % (CABRILLO_VERSION))
f.write("""CREATED-BY: PyQSO v1.1.0\n""")
f.write("""CALLSIGN: %s\n""" % (mycall))
f.write("""CONTEST: %s\n""" % (contest))
# Write each record to the file.
for r in records:
# Frequency. Note that this must be in kHz. The frequency is stored in MHz in the database, so it's converted to kHz here.
try:
freq = str(float(r["FREQ"])*1e3)
except ValueError:
freq = ""
# Mode
if(r["MODE"] == "SSB"):
mo = "PH"
elif(r["MODE"] == "CW"):
mo = "CW"
elif(r["MODE"] == "FM"):
mo = "FM"
else:
# FIXME: This assumes that the mode is any other non-CW digital mode, which isn't always going to be the case (e.g. for AM).
mo = "RY"
# Date in yyyy-mm-dd format.
date = r["QSO_DATE"][0:4] + "-" + r["QSO_DATE"][4:6] + "-" + r["QSO_DATE"][6:8]
# Time
time = r["TIME_ON"]
# The callsign that was used when operating the contest station.
call_sent = mycall
# Exchange (the part sent to the distant station)
exch_sent = r["RST_SENT"]
# Callsign
call_rcvd = r["CALL"]
# Exchange (the part received from the distant station)
exch_rcvd = r["RST_RCVD"]
# Transmitter ID (must be 0 or 1, if applicable).
# FIXME: For now this has been hard-coded to 0.
t = "0"
f.write("""QSO: %s %s %s %s %s %s %s %s %s\n""" % (freq, mo, date, time, call_sent, exch_sent, call_rcvd, exch_rcvd, t))
# Footer
f.write("END-OF-LOG:")
logging.info("Wrote %d QSOs to %s in Cabrillo format." % (len(records), path))
return

Wyświetl plik

@ -0,0 +1,70 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
import os
import logging
from pyqso.cabrillo import CONTESTS
class CabrilloExportDialog:
""" A handler for the Gtk.Dialog through which a user can specify Cabrillo log details. """
def __init__(self, application):
""" Create and show the Cabrillo export dialog to the user.
:arg application: The PyQSO application containing the main Gtk window, etc.
"""
logging.debug("Building new Cabrillo export dialog...")
self.builder = application.builder
glade_file_path = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "pyqso.glade")
self.builder.add_objects_from_file(glade_file_path, ("cabrillo_export_dialog",))
self.dialog = self.builder.get_object("cabrillo_export_dialog")
self.contest_combo = self.builder.get_object("cabrillo_export_contest_combo")
self.mycall_entry = self.builder.get_object("cabrillo_export_mycall_entry")
for contest in CONTESTS:
self.contest_combo.append_text(contest)
self.dialog.show_all()
logging.debug("Cabrillo export dialog built.")
return
@property
def contest(self):
""" Return the name of the contest.
:returns: The name of the contest.
:rtype: str
"""
return self.contest_combo.get_active_text()
@property
def mycall(self):
""" Return the callsign used during the contest.
:returns: The callsign used during the contest.
:rtype: str
"""
# Always show the callsigns in upper case.
return self.mycall_entry.get_text().upper()

Wyświetl plik

@ -0,0 +1,60 @@
#!/usr/bin/env python3
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
import logging
import os.path
class CalendarDialog:
""" Handler for a simple dialog containing a Gtk.Calendar widget. Using this ensures the date is in the correct YYYYMMDD format required by ADIF. """
def __init__(self, application):
""" Set up the calendar widget and show it to the user.
:arg application: The PyQSO application containing the main Gtk window, etc.
"""
self.builder = application.builder
glade_file_path = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "pyqso.glade")
self.builder.add_objects_from_file(glade_file_path, ("calendar_dialog",))
self.dialog = self.builder.get_object("calendar_dialog")
self.calendar = self.builder.get_object("calendar")
self.dialog.show_all()
return
@property
def date(self):
""" Return the date from the Gtk.Calendar widget in YYYYMMDD format.
:returns: The date from the calendar in YYYYMMDD format.
:rtype: str
"""
logging.debug("Retrieving the date from the calendar...")
(year, month, day) = self.calendar.get_date()
# If necessary, add on leading zeros so the YYYYMMDD format is followed.
if(month + 1 < 10):
month = "0" + str(month + 1) # Note: the months start from an index of 0 when retrieved from the calendar widget.
else:
month += 1
if(day < 10):
day = "0" + str(day)
date = str(year) + str(month) + str(day)
return date

Wyświetl plik

@ -1,7 +1,6 @@
#!/usr/bin/env python
# File: callsign_lookup.py
#!/usr/bin/env python3
# Copyright (C) 2013 Christian Jacobs.
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
@ -18,111 +17,309 @@
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk, GObject
import logging
import httplib
try:
import http.client as http_client
except ImportError:
import httplib as http_client
from xml.dom import minidom
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
from auxiliary_dialogs import *
from pyqso.auxiliary_dialogs import error
class CallsignLookup():
""" Uses qrz.com to lookup details about a particular callsign. """
def __init__(self, parent):
self.parent = parent
self.connection = None
self.session_key = None
logging.debug("New CallsignLookup instance created!")
return
class CallsignLookupQRZ:
def connect(self, username, password):
""" Initiate a session with the qrz.com server. Hopefully this will return a session key. """
logging.debug("Connecting to the qrz.com server...")
self.connection = httplib.HTTPConnection('xmldata.qrz.com')
request = '/xml/current/?username=%s;password=%s;agent=pyqso' % (username, password)
self.connection.request('GET', request)
response = self.connection.getresponse()
""" Use qrz.com to lookup details about a particular callsign. """
xml_data = minidom.parseString(response.read())
session_node = xml_data.getElementsByTagName('Session')[0] # There should only be one Session element
session_key_node = session_node.getElementsByTagName('Key')
if(len(session_key_node) > 0):
self.session_key = session_key_node[0].firstChild.nodeValue
logging.debug("Successfully connected to the qrz.com server...")
connected = True
else:
connected = False
def __init__(self, parent):
""" Initialise a new callsign lookup handler.
# If there are any errors or warnings, print them out
session_error_node = session_node.getElementsByTagName('Error')
if(len(session_error_node) > 0):
session_error = session_error_node[0].firstChild.nodeValue
error(parent=self.parent, message=session_error)
logging.error(session_error)
:arg parent: The parent Gtk dialog.
"""
self.parent = parent
self.connection = None
self.session_key = None
return
return connected
def connect(self, username, password):
""" Initiate a session with the qrz.com server. Hopefully this will provide a session key.
def lookup(self, callsign):
""" Parse the XML tree that is returned from the qrz.com XML server to obtain the NAME, ADDRESS, STATE, COUNTRY, DXCC, CQZ, ITUZ, and IOTA field data (if present),
and return the data in the dictionary called fields_and_data. """
logging.debug("Performing a callsign lookup...")
fields_and_data = {"NAME":"", "ADDRESS":"", "STATE":"", "COUNTRY":"", "DXCC":"", "CQZ":"", "ITUZ":"", "IOTA":""}
if(self.session_key):
request = '/xml/current/?s=%s;callsign=%s' % (self.session_key, callsign)
self.connection.request('GET', request)
response = self.connection.getresponse()
:arg str username: The username of the qrz.com user account.
:arg str password: The password of the qrz.com user account.
:returns: True if a successful connection was made to the server, and False otherwise.
:rtype: bool
"""
logging.debug("Connecting to the qrz.com server...")
xml_data = minidom.parseString(response.read())
callsign_node = xml_data.getElementsByTagName('Callsign')
if(len(callsign_node) > 0):
callsign_node = callsign_node[0] # There should only be a maximum of one Callsign element
# Connect to the server.
try:
self.connection = http_client.HTTPConnection("xmldata.qrz.com")
request = "/xml/current/?username=%s;password=%s;agent=pyqso" % (username, quote(password)) # Percent-escape the password in case there are reserved characters present.
self.connection.request("GET", request)
response = self.connection.getresponse()
except Exception as e:
logging.exception(e)
error(parent=self.parent, message="Could not connect to the qrz.com server. Check connection to the internets?")
return False
callsign_fname_node = callsign_node.getElementsByTagName('fname')
callsign_name_node = callsign_node.getElementsByTagName('name')
if(len(callsign_fname_node) > 0):
fields_and_data["NAME"] = callsign_fname_node[0].firstChild.nodeValue
if(len(callsign_name_node) > 0): # Add the surname, if present
fields_and_data["NAME"] = fields_and_data["NAME"] + " " + callsign_name_node[0].firstChild.nodeValue
# Get the session key.
xml_data = minidom.parseString(response.read())
session_node = xml_data.getElementsByTagName("Session")[0] # There should only be one Session element.
session_key_node = session_node.getElementsByTagName("Key")
if(session_key_node):
self.session_key = session_key_node[0].firstChild.nodeValue
logging.debug("Successfully connected to the qrz.com server. Session key is: %s." % self.session_key)
connected = True
else:
connected = False
callsign_addr1_node = callsign_node.getElementsByTagName('addr1')
callsign_addr2_node = callsign_node.getElementsByTagName('addr2')
if(len(callsign_addr1_node) > 0):
fields_and_data["ADDRESS"] = callsign_addr1_node[0].firstChild.nodeValue
if(len(callsign_addr2_node) > 0): # Add the second line of the address, if present
fields_and_data["ADDRESS"] = fields_and_data["ADDRESS"] + ", " + callsign_addr2_node[0].firstChild.nodeValue
# If there are any errors or warnings, print them out.
session_error_node = session_node.getElementsByTagName("Error")
if(session_error_node):
session_error = session_error_node[0].firstChild.nodeValue
error(parent=self.parent, message="qrz.com session error: %s" % session_error)
callsign_state_node = callsign_node.getElementsByTagName('state')
if(len(callsign_state_node) > 0):
fields_and_data["STATE"] = callsign_state_node[0].firstChild.nodeValue
return connected
callsign_country_node = callsign_node.getElementsByTagName('country')
if(len(callsign_country_node) > 0):
fields_and_data["COUNTRY"] = callsign_country_node[0].firstChild.nodeValue
def lookup(self, full_callsign, ignore_prefix_suffix=True):
""" Parse the XML tree that is returned from the qrz.com XML server to obtain the NAME, ADDRESS, STATE, COUNTRY, DXCC, CQZ, ITUZ, and IOTA field data (if present).
callsign_ccode_node = callsign_node.getElementsByTagName('ccode')
if(len(callsign_ccode_node) > 0):
fields_and_data["DXCC"] = callsign_ccode_node[0].firstChild.nodeValue
:arg str full_callsign: The callsign to look up (without any prefix/suffix stripping).
:arg bool ignore_prefix_suffix: True if callsign prefixes/suffixes should be removed prior to querying the server, False otherwise.
:returns: The data in a dictionary called fields_and_data.
:rtype: dict
"""
callsign_cqzone_node = callsign_node.getElementsByTagName('cqzone')
if(len(callsign_cqzone_node) > 0):
fields_and_data["CQZ"] = callsign_cqzone_node[0].firstChild.nodeValue
logging.debug("Looking up callsign. The full callsign (with a prefix and/or suffix) is %s." % full_callsign)
callsign_ituzone_node = callsign_node.getElementsByTagName('ituzone')
if(len(callsign_ituzone_node) > 0):
fields_and_data["ITUZ"] = callsign_ituzone_node[0].firstChild.nodeValue
# Remove any prefix or suffix from the callsign before performing the lookup.
if(ignore_prefix_suffix):
callsign = strip(full_callsign)
else:
callsign = full_callsign
callsign_iota_node = callsign_node.getElementsByTagName('iota')
if(len(callsign_iota_node) > 0):
fields_and_data["IOTA"] = callsign_iota_node[0].firstChild.nodeValue
else:
# If there is no Callsign element, then print out the error message in the Session element
session_node = xml_data.getElementsByTagName('Session')
if(len(session_node) > 0):
session_error_node = session_node.getElementsByTagName('Error')
if(len(session_error_node) > 0):
session_error = session_error_node[0].firstChild.nodeValue
error(parent=self.parent, message=session_error)
# Return empty strings for the field data
logging.debug("Callsign lookup complete. Returning data...")
return fields_and_data
# Commence lookup.
fields_and_data = {"NAME": "", "ADDRESS": "", "STATE": "", "COUNTRY": "", "DXCC": "", "CQZ": "", "ITUZ": "", "IOTA": ""}
if(self.session_key):
request = "/xml/current/?s=%s;callsign=%s" % (self.session_key, callsign)
self.connection.request("GET", request)
response = self.connection.getresponse()
xml_data = minidom.parseString(response.read())
callsign_node = xml_data.getElementsByTagName("Callsign")
if(callsign_node):
callsign_node = callsign_node[0] # There should only be a maximum of one Callsign element.
callsign_fname_node = callsign_node.getElementsByTagName("fname")
callsign_name_node = callsign_node.getElementsByTagName("name")
if(callsign_fname_node):
fields_and_data["NAME"] = callsign_fname_node[0].firstChild.nodeValue
if(callsign_name_node): # Add the surname, if present.
fields_and_data["NAME"] = fields_and_data["NAME"] + " " + callsign_name_node[0].firstChild.nodeValue
callsign_addr1_node = callsign_node.getElementsByTagName("addr1")
callsign_addr2_node = callsign_node.getElementsByTagName("addr2")
if(callsign_addr1_node):
fields_and_data["ADDRESS"] = callsign_addr1_node[0].firstChild.nodeValue
if(callsign_addr2_node): # Add the second line of the address, if present.
fields_and_data["ADDRESS"] = (fields_and_data["ADDRESS"] + ", " if callsign_addr1_node else "") + callsign_addr2_node[0].firstChild.nodeValue
callsign_state_node = callsign_node.getElementsByTagName("state")
if(callsign_state_node):
fields_and_data["STATE"] = callsign_state_node[0].firstChild.nodeValue
callsign_country_node = callsign_node.getElementsByTagName("country")
if(callsign_country_node):
fields_and_data["COUNTRY"] = callsign_country_node[0].firstChild.nodeValue
callsign_ccode_node = callsign_node.getElementsByTagName("ccode")
if(callsign_ccode_node):
fields_and_data["DXCC"] = callsign_ccode_node[0].firstChild.nodeValue
callsign_cqzone_node = callsign_node.getElementsByTagName("cqzone")
if(callsign_cqzone_node):
fields_and_data["CQZ"] = callsign_cqzone_node[0].firstChild.nodeValue
callsign_ituzone_node = callsign_node.getElementsByTagName("ituzone")
if(callsign_ituzone_node):
fields_and_data["ITUZ"] = callsign_ituzone_node[0].firstChild.nodeValue
callsign_iota_node = callsign_node.getElementsByTagName("iota")
if(callsign_iota_node):
fields_and_data["IOTA"] = callsign_iota_node[0].firstChild.nodeValue
else:
# If there is no Callsign element, then print out the error message in the Session element.
session_node = xml_data.getElementsByTagName("Session")
if(session_node):
session_error_node = session_node[0].getElementsByTagName("Error")
if(session_error_node):
session_error = session_error_node[0].firstChild.nodeValue
error(parent=self.parent, message=session_error)
# Return empty strings for the field data.
logging.debug("Callsign lookup complete. Returning data...")
return fields_and_data
class CallsignLookupHamQTH:
""" Use hamqth.com to lookup details about a particular callsign. """
def __init__(self, parent):
self.parent = parent
self.connection = None
self.session_id = None
return
def connect(self, username, password):
""" Initiate a session with the hamqth.com server. Hopefully this will provide a session key.
:arg str username: The username of the hamqth.com user account.
:arg str password: The password of the hamqth.com user account.
:returns: True if a successful connection was made to the server, and False otherwise.
:rtype: bool
"""
logging.debug("Connecting to the hamqth.com server...")
# Connect to the server.
try:
self.connection = http_client.HTTPSConnection("www.hamqth.com")
request = "/xml.php?u=%s&p=%s" % (username, quote(password)) # Percent-escape the password in case there are reserved characters present.
self.connection.request("GET", request)
response = self.connection.getresponse()
except Exception as e:
logging.exception(e)
error(parent=self.parent, message="Could not connect to the hamqth.com server. Check connection to the internets?")
return False
# Get the session ID.
xml_data = minidom.parseString(response.read())
session_node = xml_data.getElementsByTagName("session")[0] # There should only be one Session element.
session_id_node = session_node.getElementsByTagName("session_id")
if(session_id_node):
self.session_id = session_id_node[0].firstChild.nodeValue
logging.debug("Successfully connected to the hamqth.com server. Session ID is: %s." % self.session_id)
connected = True
else:
connected = False
# If there are any errors or warnings, print them out.
session_error_node = session_node.getElementsByTagName("error")
if(session_error_node):
session_error = session_error_node[0].firstChild.nodeValue
error(parent=self.parent, message="hamqth.com session error: %s" % session_error)
return connected
def lookup(self, full_callsign, ignore_prefix_suffix=True):
""" Parse the XML tree that is returned from the hamqth.com XML server to obtain the NAME, ADDRESS, STATE, COUNTRY, DXCC, CQZ, ITUZ, and IOTA field data (if present),
:arg str full_callsign: The callsign to look up (without any prefix/suffix stripping).
:arg bool ignore_prefix_suffix: True if callsign prefixes/suffixes should be removed prior to querying the server, False otherwise.
:returns: The data in a dictionary called fields_and_data.
:rtype: dict
"""
logging.debug("Looking up callsign. The full callsign (with a prefix and/or suffix) is %s." % full_callsign)
# Remove any prefix or suffix from the callsign before performing the lookup.
if(ignore_prefix_suffix):
callsign = strip(full_callsign)
else:
callsign = full_callsign
# Commence lookup.
fields_and_data = {"NAME": "", "ADDRESS": "", "STATE": "", "COUNTRY": "", "DXCC": "", "CQZ": "", "ITUZ": "", "IOTA": ""}
if(self.session_id):
request = "/xml.php?id=%s&callsign=%s&prg=pyqso" % (self.session_id, callsign)
self.connection.request("GET", request)
response = self.connection.getresponse()
xml_data = minidom.parseString(response.read())
search_node = xml_data.getElementsByTagName("search")
if(search_node):
search_node = search_node[0] # There should only be a maximum of one Callsign element.
search_name_node = search_node.getElementsByTagName("nick")
if(search_name_node):
fields_and_data["NAME"] = search_name_node[0].firstChild.nodeValue
search_addr1_node = search_node.getElementsByTagName("adr_street1")
search_addr2_node = search_node.getElementsByTagName("adr_street2")
if(search_addr1_node):
fields_and_data["ADDRESS"] = search_addr1_node[0].firstChild.nodeValue
if(search_addr2_node): # Add the second line of the address, if present.
fields_and_data["ADDRESS"] = (fields_and_data["ADDRESS"] + ", " if search_addr1_node else "") + search_addr2_node[0].firstChild.nodeValue
search_state_node = search_node.getElementsByTagName("us_state")
if(search_state_node):
fields_and_data["STATE"] = search_state_node[0].firstChild.nodeValue
search_country_node = search_node.getElementsByTagName("country")
if(search_country_node):
fields_and_data["COUNTRY"] = search_country_node[0].firstChild.nodeValue
search_cqzone_node = search_node.getElementsByTagName("cq")
if(search_cqzone_node):
fields_and_data["CQZ"] = search_cqzone_node[0].firstChild.nodeValue
search_ituzone_node = search_node.getElementsByTagName("itu")
if(search_ituzone_node):
fields_and_data["ITUZ"] = search_ituzone_node[0].firstChild.nodeValue
search_iota_node = search_node.getElementsByTagName("iota")
if(search_iota_node):
fields_and_data["IOTA"] = search_iota_node[0].firstChild.nodeValue
else:
# If there is no Callsign element, then print out the error message in the Session element.
session_node = xml_data.getElementsByTagName("session")
if(session_node):
session_error_node = session_node[0].getElementsByTagName("error")
if(session_error_node):
session_error = session_error_node[0].firstChild.nodeValue
error(parent=self.parent, message=session_error)
# Return empty strings for the field data.
logging.debug("Callsign lookup complete. Returning data...")
return fields_and_data
def strip(full_callsign):
""" Remove any prefixes or suffixes from a callsign.
:arg str full_callsign: The callsign to be considered for prefix/suffix removal.
:returns: The callsign with prefixes/suffixes removed.
:rtype: str
"""
components = full_callsign.split("/") # We assume that prefixes or suffixes come before/after a forward slash character "/".
suffixes = ["P", "M", "A", "PM", "MM", "AM", "QRP"]
try:
if(len(components) == 3):
# We have both a prefix and a suffix.
callsign = components[1]
elif(len(components) == 2):
if(components[1].upper() in suffixes or components[1].lower() in suffixes):
# If the last part of the full_callsign is a valid suffix, then use the part before that.
callsign = components[0]
logging.debug("Suffix %s found. Callsign to lookup is %s." % (components[1], callsign))
else:
# We have a prefix, so take the part after the first "/".
callsign = components[1]
logging.debug("Prefix %s found. Callsign to lookup is %s." % (components[0], callsign))
elif(len(components) == 1):
# We have neither a prefix nor a suffix, so use the full_callsign.
callsign = full_callsign
logging.debug("No prefix or suffix found. Callsign to lookup is %s." % callsign)
else:
raise ValueError
except ValueError:
callsign = full_callsign
return callsign

73
pyqso/compare.py 100644
Wyświetl plik

@ -0,0 +1,73 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
def compare_date_and_time(model, row1, row2, user_data):
""" Compare two rows (let's call them A and B) in a Gtk.ListStore, and sort by both date and time.
:arg Gtk.TreeModel model: The model used to sort the log data.
:arg Gtk.TreeIter row1: The pointer to row A.
:arg Gtk.TreeIter row2: The pointer to row B.
:arg user_data: The specific column from which to retrieve data for rows A and B.
:returns: -1 if Row B's date/time is more recent than Row A's; 0 if both dates and times are the same; 1 if Row A's date/time is more recent than Row B's.
:rtype: int
"""
date1 = model.get_value(row1, user_data[0])
date2 = model.get_value(row2, user_data[0])
time1 = model.get_value(row1, user_data[1])
time2 = model.get_value(row2, user_data[1])
if(date1 < date2):
return -1
elif(date1 == date2):
# If the dates are the same, then let's also sort by time.
if(time1 > time2):
return 1
elif(time1 == time2):
return 0
else:
return -1
else:
return 1
def compare_default(model, row1, row2, user_data):
""" The default sorting function for all Gtk.ListStore objects.
:arg Gtk.TreeModel model: The model used to sort the log data.
:arg Gtk.TreeIter row1: The pointer to row A.
:arg Gtk.TreeIter row2: The pointer to row B.
:arg user_data: The specific column from which to retrieve data for rows A and B.
:returns: -1 if the value of Row A's column value is less than Row B's column value; 0 if both values are the same; 1 if Row A's column value is greater than Row B's column value.
:rtype: int
"""
# Let's try to deal with numerical values, if possible.
try:
value1 = float(model.get_value(row1, user_data))
value2 = float(model.get_value(row2, user_data))
except ValueError:
value1 = model.get_value(row1, user_data)
value2 = model.get_value(row2, user_data)
if(value1 < value2):
return -1
elif(value1 == value2):
return 0
else:
return 1

Wyświetl plik

@ -1,7 +1,6 @@
#!/usr/bin/env python
# File: dx_cluster.py
#!/usr/bin/env python3
# Copyright (C) 2013 Christian Jacobs.
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
@ -18,163 +17,302 @@
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk, GObject
from gi.repository import Gtk, GObject, Gdk
import logging
import os
import os.path
import sys
import telnetlib
try:
import configparser
except ImportError:
import ConfigParser as configparser
import os.path
from pyqso.telnet_connection_dialog import *
from pyqso.telnet_connection_dialog import TelnetConnectionDialog
from pyqso.auxiliary_dialogs import error
class DXCluster(Gtk.VBox):
""" A tool for connecting to a DX cluster (specifically Telnet-based DX clusters). """
def __init__(self, parent):
""" Set up the DX cluster's Gtk.VBox, and set up a timer so that PyQSO can retrieve new data from the Telnet server every few seconds. """
logging.debug("Setting up the DX cluster...")
Gtk.VBox.__init__(self, spacing=2)
BOOKMARKS_FILE = os.path.expanduser('~/.config/pyqso/bookmarks.ini')
self.connection = None
self.parent = parent
# Set up the toolbar
self.toolbar = Gtk.HBox(spacing=2)
self.buttons = {}
# Connect
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_CONNECT, Gtk.IconSize.BUTTON)
button = Gtk.Button()
button.add(icon)
button.set_tooltip_text('Connect to Telnet Server')
button.connect("clicked", self.telnet_connect)
self.toolbar.pack_start(button, False, False, 0)
self.buttons["CONNECT"] = button
class DXCluster:
# Disconnect
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_DISCONNECT, Gtk.IconSize.BUTTON)
button = Gtk.Button()
button.add(icon)
button.set_tooltip_text('Disconnect from Telnet Server')
button.connect("clicked", self.telnet_disconnect)
self.toolbar.pack_start(button, False, False, 0)
self.buttons["DISCONNECT"] = button
""" A tool for connecting to a DX cluster (specifically Telnet-based DX clusters). """
self.toolbar.pack_start(Gtk.SeparatorToolItem(), False, False, 0)
def __init__(self, application):
""" Set up the DX cluster, and set up a timer so that PyQSO can retrieve new data from the Telnet server every few seconds.
self.command = Gtk.Entry()
self.toolbar.pack_start(self.command, False, False, 0)
self.send = Gtk.Button("Send Command")
self.send.connect("clicked", self.telnet_send_command)
self.toolbar.pack_start(self.send, False, False, 0)
:arg application: The PyQSO application containing the main Gtk window, etc.
"""
self.pack_start(self.toolbar, False, False, 0)
logging.debug("Setting up the DX cluster...")
# A TextView object to display the output from the Telnet server.
self.renderer = Gtk.TextView()
self.renderer.set_editable(False)
self.renderer.set_cursor_visible(False)
sw = Gtk.ScrolledWindow()
sw.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
sw.add(self.renderer)
self.buffer = self.renderer.get_buffer()
self.pack_start(sw, True, True, 0)
self.application = application
self.builder = self.application.builder
self.connection = None
self.set_connect_button_sensitive(True)
# Connect signals.
self.builder.get_object("mitem_new").connect("activate", self.new_server)
self.builder.get_object("mitem_disconnect").connect("activate", self.telnet_disconnect)
self.builder.get_object("send").connect("clicked", self.telnet_send_command)
self.builder.get_object("command").connect("key-press-event", self.on_command_key_press)
self.show_all()
# Get the text renderer and its buffer.
self.renderer = self.builder.get_object("renderer")
self.buffer = self.renderer.get_buffer()
logging.debug("DX cluster ready!")
# Items whose sensitivity may change.
self.items = {}
self.items["CONNECT"] = self.builder.get_object("mitem_connect")
self.items["DISCONNECT"] = self.builder.get_object("mitem_disconnect")
self.items["SEND"] = self.builder.get_object("send")
self.set_items_sensitive(True)
return
self.populate_bookmarks()
def telnet_connect(self, widget=None):
""" Connect to a user-specified Telnet server, with the host and login details specified in the Gtk.Entry boxes in the TelnetConnectionDialog. """
dialog = TelnetConnectionDialog(self.parent)
response = dialog.run()
if(response == Gtk.ResponseType.OK):
connection_info = dialog.get_connection_info()
host = connection_info["HOST"].get_text()
port = connection_info["PORT"].get_text()
username = connection_info["USERNAME"].get_text()
password = connection_info["PASSWORD"].get_text()
dialog.destroy()
else:
dialog.destroy()
return
logging.debug("DX cluster ready!")
if(host == ""):
logging.error("No Telnet server specified.")
return
if(port == ""):
port = 23 # The default Telnet port
else:
port = int(port)
return
try:
self.connection = telnetlib.Telnet(host, port)
def on_command_key_press(self, widget, event, data=None):
""" If the Return key is pressed when the focus is on the command box, then send whatever command the user has entered. """
if(event.keyval == Gdk.KEY_Return):
self.telnet_send_command()
return
if(username):
self.connection.read_until("login: ")
self.connection.write(username + "\n")
if(password):
self.connection.read_until("password: ")
self.connection.write(password + "\n")
except:
logging.exception("Could not create a connection to the Telnet server")
self.connection = None
return
def new_server(self, widget=None):
""" Get Telnet server host and login details specified in the Gtk.Entry boxes in the Telnet connection dialog and attempt a connection. """
self.set_connect_button_sensitive(False)
# Get connection details.
tcd = TelnetConnectionDialog(self.application)
response = tcd.dialog.run()
if(response == Gtk.ResponseType.OK):
host = tcd.host
port = tcd.port
username = tcd.username
password = tcd.password
bookmark = tcd.bookmark
tcd.dialog.destroy()
self.check_io_event = GObject.timeout_add(1000, self._on_telnet_io)
# Handle empty hostname.
if(not host):
logging.error("No hostname specified.")
return
return
# Handle empty port number.
if(not port):
logging.warning("No port specified. Assuming default port 23...")
port = 23
else:
try:
# Cast port into an int.
port = int(port)
except ValueError as e:
logging.error("Could not cast the DX cluster's port information to an integer.")
logging.exception(e)
return
def telnet_disconnect(self, widget=None):
""" Disconnect from a Telnet server and remove the I/O timer. """
if(self.connection):
self.connection.close()
self.buffer.set_text("")
self.connection = None
self.set_connect_button_sensitive(True)
GObject.source_remove(self.check_io_event)
return
# Save the server details in a new bookmark, if desired.
if(bookmark):
try:
config = configparser.ConfigParser()
config.read(BOOKMARKS_FILE)
def telnet_send_command(self, widget=None):
""" Send the user-specified command in the Gtk.Entry box to the Telnet server (if PyQSO is connected to one). """
if(self.connection):
self.connection.write(self.command.get_text() + "\n")
self.command.set_text("")
return
# Use the host name as the bookmark's identifier.
if(username):
bookmark_identifier = "%s@%s:%d" % (username, host, port)
else:
bookmark_identifier = "%s:%d" % (host, port)
logging.debug("Using %s as the bookmark identifier." % bookmark_identifier)
def _on_telnet_io(self):
""" Retrieve any new data from the Telnet server and print it out in the Gtk.TextView widget. Always returns True to satisfy the GObject timer. """
if(self.connection):
text = self.connection.read_very_eager()
text = text.replace(u"\u0007", "") # Remove the BEL Unicode character from the end of the line
# Add bookmark.
try:
config.add_section(bookmark_identifier)
except configparser.DuplicateSectionError:
# If the hostname already exists, assume the user wants to update the port number, username and/or password.
logging.warning("Bookmark '%s' already exists. Over-writing existing details..." % (bookmark_identifier))
config.set(bookmark_identifier, "host", host)
config.set(bookmark_identifier, "port", str(port))
config.set(bookmark_identifier, "username", username)
config.set(bookmark_identifier, "password", password)
# Allow auto-scrolling to the new text entry if the focus is already at
# the very end of the Gtk.TextView. Otherwise, don't auto-scroll
# in case the user is reading something further up.
# Note: This is based on the code from http://forums.gentoo.org/viewtopic-t-445598-view-next.html
end_iter = self.buffer.get_end_iter()
end_mark = self.buffer.create_mark(None, end_iter)
self.renderer.move_mark_onscreen(end_mark)
at_end = self.buffer.get_iter_at_mark(end_mark).equal(end_iter)
self.buffer.insert(end_iter, text)
if(at_end):
# Write the bookmarks to file.
if not os.path.exists(os.path.expanduser('~/.config/pyqso')):
os.makedirs(os.path.expanduser('~/.config/pyqso'))
with open(BOOKMARKS_FILE, 'w') as f:
config.write(f)
self.populate_bookmarks()
except IOError:
# Maybe the bookmarks file could not be written to?
logging.error("Bookmark could not be saved. Check bookmarks file permissions? Going ahead with the server connection anyway...")
# Attempt a connection with the server.
self.telnet_connect(host, port, username, password)
else:
tcd.dialog.destroy()
return
def populate_bookmarks(self):
""" Populate the list of bookmarked Telnet servers in the menu. """
# Get the bookmarks submenu.
subm_bookmarks = self.builder.get_object("subm_bookmarks")
config = configparser.ConfigParser()
have_config = (config.read(BOOKMARKS_FILE) != [])
if(have_config):
try:
# Clear the menu of all current bookmarks.
for i in subm_bookmarks.get_children():
subm_bookmarks.remove(i)
# Add all bookmarks in the config file.
for bookmark in config.sections():
mitem = Gtk.MenuItem(label=bookmark)
mitem.connect("activate", self.bookmarked_server, bookmark)
subm_bookmarks.append(mitem)
except Exception as e:
logging.error("An error occurred whilst populating the DX cluster bookmarks menu.")
logging.exception(e)
self.builder.get_object("dx_cluster").show_all() # Need to do this to update the bookmarks list in the menu.
return
def bookmarked_server(self, widget, name):
""" Get Telnet server host and login details from an existing bookmark and attempt a connection.
:arg str name: The name of the bookmark. This is the same as the server's hostname.
"""
config = configparser.ConfigParser()
have_config = (config.read(BOOKMARKS_FILE) != [])
try:
if(not have_config):
raise IOError("The bookmark's details could not be loaded.")
host = config.get(name, "host")
port = int(config.get(name, "port"))
username = config.get(name, "username")
password = config.get(name, "password")
self.telnet_connect(host, port, username, password)
except ValueError as e:
# This exception may occur when casting the port (which is a str) to an int.
logging.exception(e)
except IOError as e:
logging.exception(e)
except Exception as e:
logging.error("Could not connect to Telnet server '%s'." % name)
logging.exception(e)
return
def telnet_connect(self, host, port=23, username=None, password=None):
""" Connect to a user-specified Telnet server.
:arg str host: The Telnet server's hostname.
:arg int port: The Telnet server's port number. If no port is specified, the default Telnet server port of 23 will be used.
:arg str username: The user's username. This is an optional argument.
:arg str password: The user's password. This is an optional argument.
"""
# Handle empty host/port string (or the case where host/port are None).
if(not host):
error(parent=self.application.window, message="Unable to connect to a DX cluster because no hostname was specified.")
return
if(not port):
logging.warning("No port specified. Assuming default port 23...")
port = 23 # Use the default Telnet port.
try:
logging.debug("Attempting connection to Telnet server %s:%d..." % (host, port))
self.connection = telnetlib.Telnet(host, port)
assert(self.connection)
if(username):
self.connection.read_until("login: ".encode())
self.connection.write((username + "\n").encode())
if(password):
self.connection.read_until("password: ".encode())
self.connection.write((password + "\n").encode())
except Exception as e:
message = "Could not create a connection to the Telnet server %s:%d. Check connection to the internets? Check connection details?" % (host, port)
error(parent=self.application.window, message=message)
logging.exception(e)
self.connection = None
return
logging.debug("Connection to %s:%d established." % (host, port))
self.set_items_sensitive(False)
self.check_io_event = GObject.timeout_add(1000, self.on_telnet_io)
return
def telnet_disconnect(self, widget=None):
""" Disconnect from a Telnet server and remove the I/O timer. """
if(self.connection):
self.connection.close()
self.buffer.set_text("")
self.connection = None
self.set_items_sensitive(True)
# Stop checking for server output once disconnected.
try:
GObject.source_remove(self.check_io_event)
except AttributeError:
# This may happen if a connection hasn't yet been established.
pass
return
def telnet_send_command(self, widget=None):
""" Send the user-specified command in the Gtk.Entry box to the Telnet server (if PyQSO is connected to one). """
if(self.connection):
command = self.builder.get_object("command")
self.connection.write((command.get_text() + "\n").encode())
command.set_text("")
return
def on_telnet_io(self):
""" Retrieve any new data from the Telnet server and print it out in the Gtk.TextView widget.
:returns: Always returns True to satisfy the GObject timer.
:rtype: bool
"""
if(self.connection):
text = self.connection.read_very_eager()
text = text.decode("ascii", "replace") # Replace any characters that cannot be decoded with a replacement marker.
try:
text = text.replace("\u0007", "") # Remove the BEL Unicode character from the end of the line
except UnicodeDecodeError:
pass
# Allow auto-scrolling to the new text entry if the focus is already at
# the very end of the Gtk.TextView. Otherwise, don't auto-scroll
# in case the user is reading something further up.
# Note: This is based on the code from http://forums.gentoo.org/viewtopic-t-445598-view-next.html
end_iter = self.buffer.get_end_iter()
end_mark = self.buffer.create_mark(None, end_iter)
self.renderer.scroll_mark_onscreen(end_mark)
self.renderer.move_mark_onscreen(end_mark)
at_end = self.buffer.get_iter_at_mark(end_mark).equal(end_iter)
self.buffer.insert(end_iter, text)
if(at_end):
end_mark = self.buffer.create_mark(None, end_iter)
self.renderer.scroll_mark_onscreen(end_mark)
return True
return True
def set_connect_button_sensitive(self, sensitive):
""" Enable/disable the relevant buttons for connecting/disconnecting from a DX cluster, so that users cannot click the connect button if PyQSO is already connected. """
self.buttons["CONNECT"].set_sensitive(sensitive)
self.buttons["DISCONNECT"].set_sensitive(not sensitive)
self.send.set_sensitive(not sensitive)
return
def set_items_sensitive(self, sensitive):
""" Enable/disable the relevant buttons for connecting/disconnecting from a DX cluster, so that users cannot click the connect button if PyQSO is already connected.
:arg bool sensitive: If True, enable the Connect button and disable the Disconnect button. If False, vice versa.
"""
self.items["CONNECT"].set_sensitive(sensitive)
self.items["DISCONNECT"].set_sensitive(not sensitive)
self.items["SEND"].set_sensitive(not sensitive)
return

Wyświetl plik

@ -1,83 +0,0 @@
#!/usr/bin/env python
# File: grey_line.py
# Copyright (C) 2013 Christian Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk, GObject
import logging
from datetime import datetime
try:
import numpy
import matplotlib
matplotlib.rcParams['font.size'] = 10.0
from mpl_toolkits.basemap import Basemap
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
have_necessary_modules = True
except ImportError:
logging.error("Could not import a non-standard Python module needed by the GreyLine class. Check that all the PyQSO dependencies are satisfied.")
have_necessary_modules = False
class GreyLine(Gtk.VBox):
""" A tool for visualising the grey line. """
def __init__(self, parent):
""" Set up the drawing canvas and the timer which will re-plot the grey line every 30 minutes. """
logging.debug("Setting up the grey line...")
Gtk.VBox.__init__(self, spacing=2)
self.parent = parent
if(have_necessary_modules):
self.fig = matplotlib.figure.Figure()
self.canvas = FigureCanvas(self.fig) # For embedding in the Gtk application
self.pack_start(self.canvas, True, True, 0)
self.refresh_event = GObject.timeout_add(1800000, self.draw) # Re-draw the grey line automatically after 30 minutes (if the grey line tool is visible).
self.show_all()
logging.debug("Grey line ready!")
return
def draw(self):
""" Draw the world map and the grey line on top of it. This method always returns True to satisfy the GObject timer. """
if(have_necessary_modules):
if(self.parent.toolbox.tools.get_current_page() != 1 or not self.parent.toolbox.get_visible()):
# Don't re-draw if the grey line is not visible.
return True # We need to return True in case this is method was called by a timer event.
else:
logging.debug("Drawing the grey line...")
# Re-draw the grey line
self.fig.clf()
sub = self.fig.add_subplot(111)
# Draw the map of the world. This is based on the example from:
# http://matplotlib.org/basemap/users/examples.html
m = Basemap(projection='mill', lon_0=0, ax=sub, resolution='c', fix_aspect=False)
m.drawcountries(linewidth=0.5)
m.drawcoastlines(linewidth=0.5)
m.drawparallels(numpy.arange(-90, 90, 30), labels=[1, 0, 0, 0])
m.drawmeridians(numpy.arange(m.lonmin, m.lonmax+30, 60), labels=[0, 0, 0, 1])
m.drawmapboundary(fill_color='lightblue')
m.fillcontinents(color='darkgreen', lake_color='lightblue')
m.nightshade(datetime.utcnow()) # Add in the grey line using UTC time. Note that this requires NetCDF.
logging.debug("Grey line drawn.")
return True
else:
return False # Don't try to re-draw the canvas if the necessary modules to do so could not be imported.

Wyświetl plik

@ -1,7 +1,6 @@
#!/usr/bin/env python
# File: log.py
#!/usr/bin/env python3
# Copyright (C) 2013 Christian Jacobs.
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
@ -18,360 +17,318 @@
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk, GObject
from os.path import basename
from gi.repository import Gtk
import logging
import sqlite3 as sqlite
import unittest
from adif import AVAILABLE_FIELD_NAMES_TYPES, AVAILABLE_FIELD_NAMES_ORDERED
from record_dialog import *
from pyqso.adif import AVAILABLE_FIELD_NAMES_ORDERED
class Log(Gtk.ListStore):
""" A Log object can store multiple Record objects. """
def __init__(self, connection, name):
# The ListStore constructor needs to know the data types of the columns.
# The index is always an integer. We will assume the fields are strings.
data_types = [int] + [str]*len(AVAILABLE_FIELD_NAMES_ORDERED)
# Call the constructor of the super class (Gtk.ListStore)
Gtk.ListStore.__init__(self, *data_types)
""" A single log inside of the whole logbook. A Log object can store multiple records. This is """
self.connection = connection
self.name = name
logging.debug("New Log instance created!")
return
def __init__(self, connection, name):
""" Set up a new Log object.
def populate(self):
""" Remove everything in the Gtk.ListStore that is rendered already (via the TreeView), and start afresh. """
:arg connection: An sqlite database connection.
:arg str name: The name of the log (i.e. the database table name).
"""
logging.debug("Populating '%s'..." % self.name)
self.add_missing_db_columns()
self.clear()
records = self.get_all_records()
if(records is not None):
for r in records:
liststore_entry = [r["id"]]
for field_name in AVAILABLE_FIELD_NAMES_ORDERED:
# Note: r may contain column names that are not in AVAILABLE_FIELD_NAMES_ORDERED,
# so we need to loop over and only select those that are, since the ListStore will
# expect a specific number of columns.
liststore_entry.append(r[field_name])
self.append(liststore_entry)
logging.debug("Finished populating '%s'." % self.name)
else:
logging.error("Could not populate '%s' because of a database error." % self.name)
return
# The ListStore constructor needs to know the data types of the columns.
# The index is always an integer. We will assume the fields are strings.
data_types = [int] + [str]*len(AVAILABLE_FIELD_NAMES_ORDERED)
# Call the constructor of the super class (Gtk.ListStore).
Gtk.ListStore.__init__(self, *data_types)
def add_missing_db_columns(self):
""" Check whether each field name in AVAILABLE_FIELD_NAMES_ORDERED is in the database table. If not, add it
(with all entries being set to an empty string initially). """
logging.debug("Adding any missing database columns...")
self.connection = connection
self.name = name
# Get all the column names in the current database table.
column_names = []
try:
with self.connection:
return
def populate(self):
""" Remove everything in the Gtk.ListStore that is rendered already (via the TreeView), and start afresh. """
logging.debug("Populating '%s'..." % self.name)
self.add_missing_db_columns()
self.clear()
try:
records = self.records
for r in records:
liststore_entry = [r["id"]]
for field_name in AVAILABLE_FIELD_NAMES_ORDERED:
# Note: r may contain column names that are not in AVAILABLE_FIELD_NAMES_ORDERED,
# so we need to loop over and only select those that are, since the ListStore will
# expect a specific number of columns.
liststore_entry.append(r[field_name])
self.append(liststore_entry)
logging.debug("Finished populating '%s'." % self.name)
except sqlite.Error as e:
logging.error("Could not populate '%s' because of a database error." % self.name)
logging.exception(e)
return
def add_missing_db_columns(self):
""" Check whether each field name in AVAILABLE_FIELD_NAMES_ORDERED is in the database table. If not, add it
(with all entries being set to an empty string initially).
:raises sqlite.Error, IndexError: If the existing database column names could not be obtained, or missing column names could not be added.
"""
logging.debug("Adding any missing database columns...")
# Get all the column names in the current database table.
column_names = []
try:
with self.connection:
c = self.connection.cursor()
c.execute("PRAGMA table_info(%s)" % self.name)
result = c.fetchall()
for t in result:
column_names.append(t[1].upper())
except (sqlite.Error, IndexError) as e:
logging.exception(e)
logging.error("Could not obtain the database column names.")
return
for field_name in AVAILABLE_FIELD_NAMES_ORDERED:
if(not(field_name in column_names)):
try:
with self.connection:
c.execute("ALTER TABLE %s ADD COLUMN %s TEXT DEFAULT \"\"" % (self.name, field_name.lower()))
except sqlite.Error as e:
logging.exception(e)
logging.error("Could not add the missing database column '%s'." % field_name)
pass
logging.debug("Finished adding any missing database columns.")
return
def add_record(self, fields_and_data):
""" Add a record (or multiple records) to the log.
:arg fields_and_data: A list of dictionaries (or possibly just a single dictionary), with each dictionary representing a single QSO, to be added to the log.
"""
logging.debug("Adding record(s) to log...")
# If a dictionary is given, assume that we only have one record to add.
if isinstance(fields_and_data, dict):
fields_and_data = [fields_and_data]
with self.connection:
c = self.connection.cursor()
c.execute("PRAGMA table_info(%s)" % self.name)
result = c.fetchall()
for t in result:
column_names.append(t[1].upper())
except (sqlite.Error, IndexError) as e:
logging.exception(e)
logging.error("Could not obtain the database column names.")
return
for field_name in AVAILABLE_FIELD_NAMES_ORDERED:
if(not(field_name in column_names)):
try:
with self.connection:
c.execute("ALTER TABLE %s ADD COLUMN %s TEXT DEFAULT \"\"" % (self.name, field_name.lower()))
except sqlite.Error as e:
logging.exception(e)
logging.error("Could not add the missing database column '%s'." % field_name)
pass
logging.debug("Finished adding any missing database columns.")
return
# Get all the column names in the current database table.
c.execute("PRAGMA table_info(%s)" % self.name)
column_names = c.fetchall()
def add_record(self, fields_and_data):
""" Add a record comprising data given in the 'fields_and_data' argument to the log. """
logging.debug("Adding record to log...")
liststore_entry = []
field_names = AVAILABLE_FIELD_NAMES_ORDERED
for i in range(0, len(field_names)):
if(field_names[i] in fields_and_data.keys()):
liststore_entry.append(fields_and_data[field_names[i]])
else:
liststore_entry.append("")
# Get the index/rowid of the last inserted record in the database.
c.execute("SELECT max(id) FROM %s" % self.name)
last_index = c.fetchone()[0]
if last_index is None:
# Assume no records are currently present.
last_index = 0
try:
with self.connection:
c = self.connection.cursor()
# A list of all the database entries, to be inserted in one go into the database.
database_entries = []
# Construct the SQL query.
query = "INSERT INTO %s VALUES (NULL" % self.name
for i in range(len(column_names)-1): # -1 here because we don't want to count the database's 'id' column, since this is autoincremented.
query = query + ",?"
query = query + ")"
# Gather all the records (making sure that the entries of each record are in the correct order).
for r in range(len(fields_and_data)):
# What if the database columns are not necessarily in the same order as (or even exist in) AVAILABLE_FIELD_NAMES_ORDERED?
# PyQSO handles this here, but needs a separate list (called database_entry) to successfully perform the SQL query.
database_entry = []
c.execute("PRAGMA table_info(%s)" % self.name) # Get all the column names in the current database table.
column_names = c.fetchall()
query = "INSERT INTO %s VALUES (NULL" % self.name
for t in column_names:
# 't' here is a tuple
column_name = str(t[1])
if( (column_name.upper() in AVAILABLE_FIELD_NAMES_ORDERED) and (column_name.upper() in fields_and_data.keys()) ):
database_entry.append(fields_and_data[column_name.upper()])
query = query + ",?"
else:
if(column_name != "id"): # Ignore the row index field. This is a special case since it's not in AVAILABLE_FIELD_NAMES_ORDERED.
query = query + ",\"\""
query = query + ")"
c.execute(query, database_entry)
index = c.lastrowid
column_name = str(t[1]) # 't' here is a tuple
if((column_name.upper() in AVAILABLE_FIELD_NAMES_ORDERED) and (column_name.upper() in list(fields_and_data[r].keys()))):
database_entry.append(fields_and_data[r][column_name.upper()])
else:
if(column_name != "id"): # Ignore the index/rowid field. This is a special case since it's not in AVAILABLE_FIELD_NAMES_ORDERED.
database_entry.append("")
database_entries.append(database_entry)
liststore_entry.insert(0, index) # Add the record's index.
self.append(liststore_entry)
logging.debug("Successfully added the record to the log.")
except (sqlite.Error, IndexError) as e:
logging.exception(e)
logging.error("Could not add the record to the log.")
return
# Insert records in the database.
with self.connection:
c = self.connection.cursor()
c.executemany(query, database_entries)
def delete_record(self, index, iter=None):
""" Delete a record with a specific index in the SQL database. The corresponding record is also deleted from the Gtk.ListStore data structure. Note that iter should always be given. It is given a default value of None for unit testing purposes only. """
logging.debug("Deleting record from log...")
# Get the selected row in the logbook
try:
with self.connection:
# Get the indices/rowids of the newly-inserted records.
query = "SELECT id FROM %s WHERE id > %s ORDER BY id ASC" % (self.name, last_index)
c.execute(query)
inserted = c.fetchall()
# Check that the number of records we wanted to insert is the same as the number of records successfully inserted.
assert(len(inserted) == len(database_entries))
# Add the records to the ListStore as well.
for r in range(len(fields_and_data)):
liststore_entry = [inserted[r]["id"]] # Add the record's index.
field_names = AVAILABLE_FIELD_NAMES_ORDERED
for i in range(0, len(field_names)):
if(field_names[i] in list(fields_and_data[r].keys())):
liststore_entry.append(fields_and_data[r][field_names[i]])
else:
liststore_entry.append("")
self.append(liststore_entry)
logging.debug("Successfully added the record(s) to the log.")
return
def delete_record(self, index, iter=None):
""" Delete a specified record from the log. The corresponding record is also deleted from the Gtk.ListStore data structure.
:arg int index: The index of the record in the SQL database.
:arg iter: The iterator pointing to the record to be deleted in the Gtk.ListStore. If the default value of None is used, only the database entry is deleted and the corresponding Gtk.ListStore is left alone.
:raises sqlite.Error, IndexError: If the record could not be deleted.
"""
logging.debug("Deleting record from log...")
# Delete the selected row in database.
with self.connection:
c = self.connection.cursor()
query = "DELETE FROM %s" % self.name
c.execute(query+" WHERE id=?", [index])
if(iter is not None):
self.remove(iter)
logging.debug("Successfully deleted the record from the log.")
except (sqlite.Error, IndexError) as e:
logging.exception(e)
logging.error("Could not delete the record from the log.")
return
def edit_record(self, index, field_name, data, iter=None, column_index=None):
""" Edit a specified record by replacing the data in the field 'field_name' with the data given in the argument called 'data'. Note that both iter and column_index should always be given. These are given default values of None for unit testing purposes only. """
logging.debug("Editing field '%s' in record %d..." % (field_name, index))
try:
with self.connection:
# Delete the selected row in the Gtk.ListStore.
if(iter is not None):
self.remove(iter)
logging.debug("Successfully deleted the record from the log.")
return
def edit_record(self, index, field_name, data, iter=None, column_index=None):
""" Edit a specified record by replacing the current data in a specified field with the data provided.
:arg int index: The index of the record in the SQL database.
:arg str field_name: The name of the field whose data should be modified.
:arg str data: The data that should replace the current data in the field.
:arg iter: The iterator pointing to the record to be edited in the Gtk.ListStore. If the default value of None is used, only the database entry is edited and the corresponding Gtk.ListStore is left alone.
:arg column_index: The index of the column in the Gtk.ListStore to be edited. If the default value of None is used, only the database entry is edited and the corresponding Gtk.ListStore is left alone.
:raises sqlite.Error, IndexError: If the record could not be edited.
"""
logging.debug("Editing field '%s' in record %d..." % (field_name, index))
with self.connection:
c = self.connection.cursor()
query = "UPDATE %s SET %s" % (self.name, field_name)
query = query + "=? WHERE id=?"
c.execute(query, [data, index]) # First update the SQL database...
if(iter is not None and column_index is not None):
self.set(iter, column_index, data) # ...and then the ListStore.
logging.debug("Successfully edited field '%s' in record %d in the log." % (field_name, index))
except (sqlite.Error, IndexError) as e:
logging.exception(e)
logging.error("Could not edit field %s in record %d in the log." % (field_name, index))
return
c.execute(query, [data, index]) # First update the SQL database...
if(iter is not None and column_index is not None):
self.set(iter, column_index, data) # ...and then the ListStore.
logging.debug("Successfully edited field '%s' in record %d in the log." % (field_name, index))
return
def remove_duplicates(self):
""" Find the duplicates in the log, based on the CALL, QSO_DATE, TIME_ON, FREQ and MODE fields. Return a tuple containing the number of duplicates in the log, and the number of duplicates successfully removed. Hopefully these will be the same. """
duplicates = []
try:
with self.connection:
c = self.connection.cursor()
c.execute(
"""SELECT rowid FROM %s WHERE rowid NOT IN
def remove_duplicates(self):
""" Remove any duplicate records from the log.
:returns: The total number of duplicates, and the number of duplicates that were successfully removed. Hopefully these will be the same.
:rtype: tuple
"""
duplicates = self.get_duplicates()
if(len(duplicates) == 0):
return (0, 0) # Nothing to do here.
removed = 0 # Count the number of records that are removed. Hopefully this will be the same as len(duplicates).
iter = self.get_iter_first() # Start with the first row in the log.
prev = iter # Keep track of the previous iter (initially this will be the same as the first row in the log).
while iter is not None:
row_index = self.get_value(iter, 0) # Get the index.
if(row_index in duplicates): # Is this a duplicate row? If so, delete it.
self.delete_record(row_index, iter)
removed += 1
iter = prev # Go back to the iter before the record that was just removed and continue from there.
continue
prev = iter
iter = self.iter_next(iter) # Move on to the next row, until iter_next returns None.
return (len(duplicates), removed)
def rename(self, new_name):
""" Rename the log.
:arg str new_name: The new name for the log.
:returns: True if the renaming process is successful. Otherwise returns False.
:rtype: bool
"""
try:
with self.connection:
# First try to alter the table name in the database.
c = self.connection.cursor()
query = "ALTER TABLE %s RENAME TO %s" % (self.name, new_name)
c.execute(query)
# If the table name change was successful, then change the name attribute of the Log object too.
self.name = new_name
success = True
except sqlite.Error as e:
logging.exception(e)
success = False
return success
def get_duplicates(self):
""" Find the duplicates in the log, based on the CALL, QSO_DATE, and TIME_ON fields.
:returns: A list of indices/ids corresponding to the duplicate records.
:rtype: list
"""
duplicates = []
try:
with self.connection:
c = self.connection.cursor()
c.execute(
"""SELECT id FROM %s WHERE id NOT IN
(
SELECT MIN(rowid) FROM %s GROUP BY call, qso_date, time_on, freq, mode
SELECT MIN(id) FROM %s GROUP BY call, qso_date, time_on
)""" % (self.name, self.name))
result = c.fetchall()
for rowid in result:
duplicates.append(rowid[0]) # Get the integer from inside the tuple.
if(len(duplicates) == 0):
return (0, 0) # Nothing to do here.
except (sqlite.Error, IndexError) as e:
logging.exception(e)
return (0, 0)
result = c.fetchall()
for index in result:
duplicates.append(index[0]) # Get the integer from inside the tuple.
duplicates.sort() # These indices should monotonically increasing, but let's sort the list just in case.
except (sqlite.Error, IndexError) as e:
logging.exception(e)
return duplicates
removed = 0 # Count the number of records that are removed. Hopefully this will be the same as len(duplicates).
path = Gtk.TreePath(0) # Start with the first row in the log.
iter = self.get_iter(path)
while iter is not None:
row_index = self.get_value(iter, 0) # Get the index.
if(row_index in duplicates): # Is this a duplicate row? If so, delete it.
self.delete_record(row_index, iter)
removed += 1
iter = self.iter_next(iter) # Move on to the next row, until iter_next returns None.
def get_record_by_index(self, index):
""" Return a record with a given index in the log.
assert(len(duplicates) == removed)
return (len(duplicates), removed)
def get_record_by_index(self, index):
""" Return a record with a given index in the log. The record is represented by a dictionary of field-value pairs. """
try:
with self.connection:
:arg int index: The index of the record in the SQL database.
:returns: The desired record, represented by a dictionary of field-value pairs.
:rtype: dict
:raises sqlite.Error: If the record could not be retrieved from the database.
"""
with self.connection:
c = self.connection.cursor()
query = "SELECT * FROM %s WHERE id=?" % self.name
c.execute(query, [index])
return c.fetchone()
except sqlite.Error as e:
logging.exception(e)
return None
def get_all_records(self):
""" Return a list of all the records in the log. Each record is represented by a dictionary. """
try:
with self.connection:
@property
def records(self):
""" Return a list of all the records in the log.
:returns: A list of all the records in the log. Each record is represented by a dictionary.
:rtype: dict
:raises sqlite.Error: If the records could not be retrieved from the database.
"""
with self.connection:
c = self.connection.cursor()
c.execute("SELECT * FROM %s" % self.name)
return c.fetchall()
except sqlite.Error as e:
logging.exception(e)
return None
def get_number_of_records(self):
""" Return the total number of records in the log. """
try:
with self.connection:
@property
def record_count(self):
""" Return the total number of records in the log.
:returns: The total number of records in the log.
:rtype: int
:raises sqlite.Error: If the record count could not be determined due to a database error.
"""
with self.connection:
c = self.connection.cursor()
c.execute("SELECT Count(*) FROM %s" % self.name)
return c.fetchone()[0]
except (sqlite.Error, IndexError) as e:
logging.exception(e)
return None
class TestLog(unittest.TestCase):
def setUp(self):
self.connection = sqlite.connect(":memory:")
self.connection.row_factory = sqlite.Row
self.field_names = ["CALL", "QSO_DATE", "TIME_ON", "FREQ", "BAND", "MODE", "RST_SENT", "RST_RCVD"]
self.fields_and_data = {"CALL":"TEST123", "QSO_DATE":"20130312", "TIME_ON":"1234", "FREQ":"145.500", "BAND":"2m", "MODE":"FM", "RST_SENT":"59", "RST_RCVD":"59"}
c = self.connection.cursor()
query = "CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT"
for field_name in self.field_names:
s = ", %s TEXT" % field_name.lower()
query = query + s
query = query + ")"
c.execute(query)
self.log = Log(self.connection, "test")
def tearDown(self):
self.connection.close()
def test_log_add_missing_db_columns(self):
column_names_before = []
column_names_after = []
c = self.connection.cursor()
c.execute("PRAGMA table_info(test)")
result = c.fetchall()
for t in result:
column_names_before.append(t[1].upper())
self.log.add_missing_db_columns()
c.execute("PRAGMA table_info(test)")
result = c.fetchall()
for t in result:
column_names_after.append(t[1].upper())
print "Column names before: ", column_names_before
print "Column names after: ", column_names_after
assert(len(column_names_before) == len(self.field_names) + 1) # Added 1 here because of the "ID" column in all database tables.
assert(len(column_names_after) == len(AVAILABLE_FIELD_NAMES_ORDERED) + 1)
for field_name in AVAILABLE_FIELD_NAMES_ORDERED:
assert(field_name in column_names_after)
def test_log_add_record(self):
self.log.add_record(self.fields_and_data)
c = self.connection.cursor()
c.execute("SELECT * FROM test")
records = c.fetchall()
assert len(records) == 1
for field_name in self.field_names:
print self.fields_and_data[field_name], records[0][field_name]
assert self.fields_and_data[field_name] == records[0][field_name]
def test_log_delete_record(self):
query = "INSERT INTO test VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)"
c = self.connection.cursor()
c.execute(query, (self.fields_and_data["CALL"], self.fields_and_data["QSO_DATE"], self.fields_and_data["TIME_ON"], self.fields_and_data["FREQ"], self.fields_and_data["BAND"], self.fields_and_data["MODE"], self.fields_and_data["RST_SENT"], self.fields_and_data["RST_RCVD"]))
c.execute("SELECT * FROM test")
records_before = c.fetchall()
self.log.delete_record(1)
c.execute("SELECT * FROM test")
records_after = c.fetchall()
assert(len(records_before) == 1)
assert(len(records_after) == 0)
def test_log_edit_record(self):
query = "INSERT INTO test VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)"
c = self.connection.cursor()
c.execute(query, (self.fields_and_data["CALL"], self.fields_and_data["QSO_DATE"], self.fields_and_data["TIME_ON"], self.fields_and_data["FREQ"], self.fields_and_data["BAND"], self.fields_and_data["MODE"], self.fields_and_data["RST_SENT"], self.fields_and_data["RST_RCVD"]))
c.execute("SELECT * FROM test")
record_before = c.fetchall()[0]
self.log.edit_record(1, "CALL", "TEST456")
self.log.edit_record(1, "FREQ", "145.450")
c.execute("SELECT * FROM test")
record_after = c.fetchall()[0]
assert(record_before["CALL"] == "TEST123")
assert(record_after["CALL"] == "TEST456")
assert(record_before["FREQ"] == "145.500")
assert(record_after["FREQ"] == "145.450")
def test_log_get_record_by_index(self):
query = "INSERT INTO test VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)"
c = self.connection.cursor()
c.execute(query, (self.fields_and_data["CALL"], self.fields_and_data["QSO_DATE"], self.fields_and_data["TIME_ON"], self.fields_and_data["FREQ"], self.fields_and_data["BAND"], self.fields_and_data["MODE"], self.fields_and_data["RST_SENT"], self.fields_and_data["RST_RCVD"]))
record = self.log.get_record_by_index(1)
print "Contents of retrieved record: ", record
for field_name in record.keys():
if(field_name.upper() == "ID"):
continue
else:
assert(record[field_name.upper()] == self.fields_and_data[field_name.upper()])
assert(len(record) == len(self.fields_and_data) + 1)
def test_log_get_all_records(self):
query = "INSERT INTO test VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)"
c = self.connection.cursor()
# Add the same record twice
c.execute(query, (self.fields_and_data["CALL"], self.fields_and_data["QSO_DATE"], self.fields_and_data["TIME_ON"], self.fields_and_data["FREQ"], self.fields_and_data["BAND"], self.fields_and_data["MODE"], self.fields_and_data["RST_SENT"], self.fields_and_data["RST_RCVD"]))
c.execute(query, (self.fields_and_data["CALL"], self.fields_and_data["QSO_DATE"], self.fields_and_data["TIME_ON"], self.fields_and_data["FREQ"], self.fields_and_data["BAND"], self.fields_and_data["MODE"], self.fields_and_data["RST_SENT"], self.fields_and_data["RST_RCVD"]))
records = self.log.get_all_records()
print "Contents of all retrieved records: ", records
assert(len(records) == 2) # There should be 2 records
for field_name in self.field_names:
assert(records[0][field_name] == self.fields_and_data[field_name])
assert(records[1][field_name] == self.fields_and_data[field_name])
def test_log_get_number_of_records(self):
query = "INSERT INTO test VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)"
c = self.connection.cursor()
# Add the same record twice
c.execute(query, (self.fields_and_data["CALL"], self.fields_and_data["QSO_DATE"], self.fields_and_data["TIME_ON"], self.fields_and_data["FREQ"], self.fields_and_data["BAND"], self.fields_and_data["MODE"], self.fields_and_data["RST_SENT"], self.fields_and_data["RST_RCVD"]))
c.execute(query, (self.fields_and_data["CALL"], self.fields_and_data["QSO_DATE"], self.fields_and_data["TIME_ON"], self.fields_and_data["FREQ"], self.fields_and_data["BAND"], self.fields_and_data["MODE"], self.fields_and_data["RST_SENT"], self.fields_and_data["RST_RCVD"]))
number_of_records = self.log.get_number_of_records()
print "Number of records in the log: ", number_of_records
assert(number_of_records == 2) # There should be 2 records
if(__name__ == '__main__'):
unittest.main()

Wyświetl plik

@ -1,7 +1,6 @@
#!/usr/bin/env python
# File: new_log_dialog.py
#!/usr/bin/env python3
# Copyright (C) 2013 Christian Jacobs.
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
@ -18,39 +17,49 @@
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk, GObject
import logging
import re
import calendar
class LogNameDialog(Gtk.Dialog):
def __init__(self, parent, title=None, name=None):
if(title is None):
title = "New Log"
else:
title = title
Gtk.Dialog.__init__(self, title=title, parent=parent, flags=Gtk.DialogFlags.DESTROY_WITH_PARENT, buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK))
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label("Log Name:")
label.set_alignment(0, 0.5)
hbox_temp.pack_start(label, False, False, 6)
self.entry = Gtk.Entry()
if(name is not None):
self.entry.set_text(name)
hbox_temp.pack_start(self.entry, False, False, 6)
self.vbox.pack_start(hbox_temp, False, False, 6)
self.show_all()
logging.debug("New LogNameDialog instance created!")
return
def get_log_name(self):
logging.debug("Retrieving the log name from the LogNameDialog...")
return self.entry.get_text()
import os.path
class LogNameDialog:
""" A handler for the Gtk.Dialog through which a user can specify the name of a Log object. """
def __init__(self, application, title=None, name=None):
""" Create and show the log name dialog to the user.
:arg application: The PyQSO application containing the main Gtk window, etc.
:arg title: The title of the dialog. If this is None, it is assumed that a new log is going to be created.
:arg name: The existing name of the Log object. Defaults to None if not specified (because the Log does not yet exist).
"""
logging.debug("Building new log name dialog...")
self.builder = application.builder
glade_file_path = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "pyqso.glade")
self.builder.add_objects_from_file(glade_file_path, ("log_name_dialog",))
self.dialog = self.builder.get_object("log_name_dialog")
if(title is None):
self.dialog.set_title("New Log")
else:
self.dialog.set_title(title)
self.entry = self.builder.get_object("log_name_entry")
if(name is not None):
self.entry.set_text(name)
self.dialog.show_all()
logging.debug("Log name dialog built.")
return
@property
def name(self):
""" Return the log name specified in the Gtk.Entry box by the user.
:returns: The log's name.
:rtype: str
"""
return self.entry.get_text()

Plik diff jest za duży Load Diff

Wyświetl plik

@ -1,9 +1,8 @@
#!/usr/bin/env python
# logbook: menu.py
#!/usr/bin/env python3
# Copyright (C) 2012 Christian Jacobs.
# Copyright (C) 2012-2017 Christian Thomas Jacobs.
# This logbook is part of PyQSO.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@ -18,242 +17,146 @@
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk, GObject
import logging
import ConfigParser
from gi.repository import Gtk
try:
import configparser
except ImportError:
import ConfigParser as configparser
import os.path
class Menu(Gtk.MenuBar):
def __init__(self, parent):
logging.debug("New Menu instance created!")
# First let's call the constructor of the super class (Gtk.MenuBar)
Gtk.MenuBar.__init__(self)
logging.debug("Setting up the menu bar...")
agrp = Gtk.AccelGroup()
parent.add_accel_group(agrp)
class Menu:
self.items = {}
###### LOGBOOK ######
mitem_logbook = Gtk.MenuItem("Logbook")
self.append(mitem_logbook)
subm_logbook = Gtk.Menu()
mitem_logbook.set_submenu(subm_logbook)
# Create/open logbook
mitem_connect = Gtk.ImageMenuItem("Open New or Existing Logbook...")
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_OPEN, Gtk.IconSize.MENU)
mitem_connect.set_image(icon)
mitem_connect.connect("activate", parent.logbook.open)
key, mod = Gtk.accelerator_parse("<Control>O")
mitem_connect.add_accelerator("activate", agrp, key, mod, Gtk.AccelFlags.VISIBLE)
subm_logbook.append(mitem_connect)
self.items["OPEN_LOGBOOK"] = mitem_connect
""" The menu bar along the top of the main window. """
# Close logbook
mitem_disconnect = Gtk.ImageMenuItem("Close Logbook")
mitem_disconnect.connect("activate", parent.logbook.close)
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_CLOSE, Gtk.IconSize.MENU)
mitem_disconnect.set_image(icon)
key, mod = Gtk.accelerator_parse("<Control>W")
mitem_disconnect.add_accelerator("activate", agrp, key, mod, Gtk.AccelFlags.VISIBLE)
subm_logbook.append(mitem_disconnect)
self.items["CLOSE_LOGBOOK"] = mitem_disconnect
def __init__(self, application):
""" Set up all menu items and connect to the various functions.
subm_logbook.append(Gtk.SeparatorMenuItem())
:arg application: The PyQSO application containing the main Gtk window, etc.
"""
# New log
mitem_new = Gtk.ImageMenuItem("New Log")
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_ADD, Gtk.IconSize.MENU)
mitem_new.set_image(icon)
mitem_new.connect("activate", parent.logbook.new_log)
key, mod = Gtk.accelerator_parse("<Control>N")
mitem_new.add_accelerator("activate", agrp, key, mod, Gtk.AccelFlags.VISIBLE)
subm_logbook.append(mitem_new)
self.items["NEW_LOG"] = mitem_new
self.application = application
self.builder = self.application.builder
# Delete the current log
mitem_delete = Gtk.ImageMenuItem("Delete Selected Log")
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_DELETE, Gtk.IconSize.MENU)
mitem_delete.set_image(icon)
mitem_delete.connect("activate", parent.logbook.delete_log)
subm_logbook.append(mitem_delete)
self.items["DELETE_LOG"] = mitem_delete
# Rename the current log
mitem_rename = Gtk.ImageMenuItem("Rename Selected Log")
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_EDIT, Gtk.IconSize.MENU)
mitem_rename.set_image(icon)
mitem_rename.connect("activate", parent.logbook.rename_log)
subm_logbook.append(mitem_rename)
self.items["RENAME_LOG"] = mitem_rename
# Collect Gtk menu items and connect signals.
self.items = {}
subm_logbook.append(Gtk.SeparatorMenuItem())
# New logbook
self.items["NEW_LOGBOOK"] = self.builder.get_object("mitem_new_logbook")
self.items["NEW_LOGBOOK"].connect("activate", self.application.logbook.new)
# Import log
mitem_import = Gtk.ImageMenuItem("Import Log")
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_GO_FORWARD, Gtk.IconSize.MENU)
mitem_import.set_image(icon)
mitem_import.connect("activate", parent.logbook.import_log)
subm_logbook.append(mitem_import)
self.items["IMPORT_LOG"] = mitem_import
# Open logbook
self.items["OPEN_LOGBOOK"] = self.builder.get_object("mitem_open_logbook")
self.items["OPEN_LOGBOOK"].connect("activate", self.application.logbook.open)
# Export the current log
mitem_export = Gtk.ImageMenuItem("Export Log")
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_GO_BACK, Gtk.IconSize.MENU)
mitem_export.set_image(icon)
mitem_export.connect("activate", parent.logbook.export_log)
subm_logbook.append(mitem_export)
self.items["EXPORT_LOG"] = mitem_export
subm_logbook.append(Gtk.SeparatorMenuItem())
# Close logbook
self.items["CLOSE_LOGBOOK"] = self.builder.get_object("mitem_close_logbook")
self.items["CLOSE_LOGBOOK"].connect("activate", self.application.logbook.close)
# Print log
mitem_print = Gtk.ImageMenuItem("Print Log")
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_PRINT, Gtk.IconSize.MENU)
mitem_print.set_image(icon)
mitem_print.connect("activate", parent.logbook.print_log)
key, mod = Gtk.accelerator_parse("<Control>P")
mitem_print.add_accelerator("activate", agrp, key, mod, Gtk.AccelFlags.VISIBLE)
subm_logbook.append(mitem_print)
self.items["PRINT_LOG"] = mitem_print
# New log
self.items["NEW_LOG"] = self.builder.get_object("mitem_new_log")
self.items["NEW_LOG"].connect("activate", self.application.logbook.new_log)
subm_logbook.append(Gtk.SeparatorMenuItem())
# Delete the current log
self.items["DELETE_LOG"] = self.builder.get_object("mitem_delete_log")
self.items["DELETE_LOG"].connect("activate", self.application.logbook.delete_log)
# Quit
mitem_quit = Gtk.ImageMenuItem("Quit")
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_QUIT, Gtk.IconSize.MENU)
mitem_quit.set_image(icon)
mitem_quit.connect("activate", Gtk.main_quit)
key, mod = Gtk.accelerator_parse("<Control>Q")
mitem_quit.add_accelerator("activate", agrp, key, mod, Gtk.AccelFlags.VISIBLE)
subm_logbook.append(mitem_quit)
self.items["QUIT"] = mitem_quit
###### RECORDS ######
mitem_records = Gtk.MenuItem("Records")
self.append(mitem_records)
subm_records = Gtk.Menu()
mitem_records.set_submenu(subm_records)
mitem_addrecord = Gtk.ImageMenuItem("Add Record...")
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_ADD, Gtk.IconSize.MENU)
mitem_addrecord.set_image(icon)
mitem_addrecord.connect("activate", parent.logbook.add_record_callback)
key, mod = Gtk.accelerator_parse("<Control>R")
mitem_addrecord.add_accelerator("activate", agrp, key, mod, Gtk.AccelFlags.VISIBLE)
subm_records.append(mitem_addrecord)
self.items["ADD_RECORD"] = mitem_addrecord
mitem_editrecord = Gtk.ImageMenuItem("Edit Selected Record...")
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_EDIT, Gtk.IconSize.MENU)
mitem_editrecord.set_image(icon)
mitem_editrecord.connect("activate", parent.logbook.edit_record_callback, None, None)
key, mod = Gtk.accelerator_parse("<Control>E")
mitem_editrecord.add_accelerator("activate", agrp, key, mod, Gtk.AccelFlags.VISIBLE)
subm_records.append(mitem_editrecord)
self.items["EDIT_RECORD"] = mitem_editrecord
# Rename the current log
self.items["RENAME_LOG"] = self.builder.get_object("mitem_rename_log")
self.items["RENAME_LOG"].connect("activate", self.application.logbook.rename_log)
mitem_deleterecord = Gtk.ImageMenuItem("Delete Selected Record...")
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_DELETE, Gtk.IconSize.MENU)
mitem_deleterecord.set_image(icon)
mitem_deleterecord.connect("activate", parent.logbook.delete_record_callback)
key, mod = Gtk.accelerator_parse("Delete")
mitem_deleterecord.add_accelerator("activate", agrp, key, mod, Gtk.AccelFlags.VISIBLE)
subm_records.append(mitem_deleterecord)
self.items["DELETE_RECORD"] = mitem_deleterecord
# Import log
self.items["IMPORT_LOG"] = self.builder.get_object("mitem_import_log")
self.items["IMPORT_LOG"].connect("activate", self.application.logbook.import_log)
mitem_removeduplicates = Gtk.ImageMenuItem("Remove Duplicate Records")
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_FIND_AND_REPLACE, Gtk.IconSize.MENU)
mitem_removeduplicates.set_image(icon)
mitem_removeduplicates.connect("activate", parent.logbook.remove_duplicates_callback)
subm_records.append(mitem_removeduplicates)
self.items["REMOVE_DUPLICATES"] = mitem_removeduplicates
###### VIEW ######
mitem_view = Gtk.MenuItem("View")
self.append(mitem_view)
subm_view = Gtk.Menu()
mitem_view.set_submenu(subm_view)
# Export the current log as ADIF
self.items["EXPORT_LOG_ADIF"] = self.builder.get_object("mitem_export_log_adif")
self.items["EXPORT_LOG_ADIF"].connect("activate", self.application.logbook.export_log_adif)
mitem_toolbox = Gtk.CheckMenuItem("Toolbox")
config = ConfigParser.ConfigParser()
have_config = (config.read(os.path.expanduser('~/.pyqso.ini')) != [])
if(have_config):
mitem_toolbox.set_active(config.get("general", "show_toolbox") == "True")
else:
mitem_toolbox.set_active(False) # Don't show the toolbox by default
mitem_toolbox.connect("activate", parent.toolbox.toggle_visible_callback)
subm_view.append(mitem_toolbox)
self.items["TOOLBOX"] = mitem_toolbox
# Export the current log as Cabrillo
self.items["EXPORT_LOG_CABRILLO"] = self.builder.get_object("mitem_export_log_cabrillo")
self.items["EXPORT_LOG_CABRILLO"].connect("activate", self.application.logbook.export_log_cabrillo)
mitem_preferences = Gtk.ImageMenuItem("Preferences...")
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_PREFERENCES, Gtk.IconSize.MENU)
mitem_preferences.set_image(icon)
mitem_preferences.connect("activate", parent.show_preferences)
subm_view.append(mitem_preferences)
self.items["PREFERENCES"] = mitem_preferences
# Print log
self.items["PRINT_LOG"] = self.builder.get_object("mitem_print_log")
self.items["PRINT_LOG"].connect("activate", self.application.logbook.print_log)
###### HELP ######
mitem_help = Gtk.MenuItem("Help")
self.append(mitem_help)
subm_help = Gtk.Menu()
mitem_help.set_submenu(subm_help)
# About
mitem_about = Gtk.ImageMenuItem("About PyQSO")
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_ABOUT, Gtk.IconSize.MENU)
mitem_about.set_image(icon)
mitem_about.connect("activate", parent.show_about)
subm_help.append(mitem_about)
# Preferences
self.items["PREFERENCES"] = self.builder.get_object("mitem_preferences")
self.items["PREFERENCES"].connect("activate", self.application.show_preferences)
self.set_logbook_item_sensitive(True)
self.set_log_items_sensitive(False)
self.set_record_items_sensitive(False)
logging.debug("Menu bar ready!")
# Quit
self.items["QUIT"] = self.builder.get_object("mitem_quit")
self.items["QUIT"].connect("activate", Gtk.main_quit)
return
def set_logbook_item_sensitive(self, sensitive):
logging.debug("Setting the 'Create/Open Logbook' menu item's sensitivity to: %s..." % sensitive)
self.items["OPEN_LOGBOOK"].set_sensitive(sensitive)
self.items["CLOSE_LOGBOOK"].set_sensitive(not sensitive)
logging.debug("Set the 'Create/Open Logbook' menu item's sensitivity to: %s." % sensitive)
return
# Add record
self.items["ADD_RECORD"] = self.builder.get_object("mitem_add_record")
self.items["ADD_RECORD"].connect("activate", self.application.logbook.add_record_callback)
def set_log_items_sensitive(self, sensitive):
logging.debug("Setting log-related menu item sensitivity to: %s..." % sensitive)
for item_name in ["NEW_LOG", "DELETE_LOG", "RENAME_LOG", "IMPORT_LOG", "EXPORT_LOG", "PRINT_LOG"]:
self.items[item_name].set_sensitive(sensitive)
logging.debug("Set log-related menu item sensitivity to: %s." % sensitive)
return
# Edit selected record
self.items["EDIT_RECORD"] = self.builder.get_object("mitem_edit_record")
self.items["EDIT_RECORD"].connect("activate", self.application.logbook.edit_record_callback)
def set_record_items_sensitive(self, sensitive):
logging.debug("Setting record-related menu item sensitivity to: %s..." % sensitive)
for item_name in ["ADD_RECORD", "EDIT_RECORD", "DELETE_RECORD", "REMOVE_DUPLICATES"]:
self.items[item_name].set_sensitive(sensitive)
logging.debug("Set record-related menu item sensitivity to: %s." % sensitive)
return
# Delete selected record
self.items["DELETE_RECORD"] = self.builder.get_object("mitem_delete_record")
self.items["DELETE_RECORD"].connect("activate", self.application.logbook.delete_record_callback)
# Remove duplicates
self.items["REMOVE_DUPLICATES"] = self.builder.get_object("mitem_remove_duplicates")
self.items["REMOVE_DUPLICATES"].connect("activate", self.application.logbook.remove_duplicates_callback)
# Record count
self.items["RECORD_COUNT"] = self.builder.get_object("mitem_record_count")
self.items["RECORD_COUNT"].connect("activate", self.application.logbook.record_count_callback)
# View toolbox
self.items["TOOLBOX"] = self.builder.get_object("mitem_toolbox")
config = configparser.ConfigParser()
have_config = (config.read(os.path.expanduser('~/.config/pyqso/preferences.ini')) != [])
(section, option) = ("general", "show_toolbox")
if(have_config and config.has_option(section, option)):
self.items["TOOLBOX"].set_active(config.getboolean(section, option))
else:
self.items["TOOLBOX"].set_active(False) # Don't show the toolbox by default
self.items["TOOLBOX"].connect("activate", self.application.toolbox.toggle_visible_callback)
# About
self.items["ABOUT"] = self.builder.get_object("mitem_about")
self.items["ABOUT"].connect("activate", self.application.show_about)
self.set_logbook_item_sensitive(True)
self.set_log_items_sensitive(False)
self.set_record_items_sensitive(False)
return
def set_logbook_item_sensitive(self, sensitive):
""" Enable/disable logbook-related menu items.
:arg bool sensitive: If True, enable the 'new logbook' and 'open logbook' menu items. If False, disable them.
"""
self.items["NEW_LOGBOOK"].set_sensitive(sensitive)
self.items["OPEN_LOGBOOK"].set_sensitive(sensitive)
self.items["CLOSE_LOGBOOK"].set_sensitive(not sensitive)
return
def set_log_items_sensitive(self, sensitive):
""" Enable/disable log-related menu items.
:arg bool sensitive: If True, enable all the log-related menu items. If False, disable them all.
"""
for item_name in ["NEW_LOG", "DELETE_LOG", "RENAME_LOG", "IMPORT_LOG", "EXPORT_LOG_ADIF", "EXPORT_LOG_CABRILLO", "PRINT_LOG"]:
self.items[item_name].set_sensitive(sensitive)
return
def set_record_items_sensitive(self, sensitive):
""" Enable/disable record-related menu items.
:arg bool sensitive: If True, enable all the record-related menu items. If False, disable them all.
"""
for item_name in ["ADD_RECORD", "EDIT_RECORD", "DELETE_RECORD", "REMOVE_DUPLICATES", "RECORD_COUNT"]:
self.items[item_name].set_sensitive(sensitive)
return

46
pyqso/popup.py 100644
Wyświetl plik

@ -0,0 +1,46 @@
#!/usr/bin/env python3
# Copyright (C) 2018 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
class Popup:
""" The popup menu that appears when a QSO record is right-clicked. """
def __init__(self, application):
""" Set up popup menu items. """
self.application = application
self.builder = self.application.builder
self.menu = self.builder.get_object("popup")
# Collect Gtk menu items and connect signals.
self.items = {}
# Plot selected QSO on the world map.
self.items["PINPOINT"] = self.builder.get_object("mitem_pinpoint")
self.items["PINPOINT"].connect("activate", self.application.logbook.pinpoint_callback)
self.items["COPY"] = self.builder.get_object("mitem_copy")
self.items["COPY"].connect("activate", self.application.logbook.copy_callback)
self.items["PASTE"] = self.builder.get_object("mitem_paste")
self.items["PASTE"].connect("activate", self.application.logbook.paste_callback)
return

Wyświetl plik

@ -1,7 +1,6 @@
#!/usr/bin/env python
# File: preferences_dialog.py
#!/usr/bin/env python3
# Copyright (C) 2013 Christian Jacobs.
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
@ -18,266 +17,587 @@
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk, GObject
from gi.repository import Gtk
import logging
import ConfigParser
try:
import configparser
except ImportError:
import ConfigParser as configparser
import os.path
import base64
from math import ceil
try:
import Hamlib
have_hamlib = True
import Hamlib
have_hamlib = True
except ImportError:
logging.error("Could not import the Hamlib module!")
have_hamlib = False
logging.warning("Could not import the Hamlib module!")
have_hamlib = False
try:
import geocoder
have_geocoder = True
except ImportError:
logging.warning("Could not import the geocoder module!")
have_geocoder = False
from pyqso.adif import AVAILABLE_FIELD_NAMES_FRIENDLY, AVAILABLE_FIELD_NAMES_ORDERED
from pyqso.adif import AVAILABLE_FIELD_NAMES_ORDERED, MODES
from pyqso.auxiliary_dialogs import error
class PreferencesDialog(Gtk.Dialog):
def __init__(self, parent):
logging.debug("Setting up the preferences dialog...")
PREFERENCES_FILE = os.path.expanduser("~/.config/pyqso/preferences.ini")
Gtk.Dialog.__init__(self, title="Preferences", parent=parent, flags=Gtk.DialogFlags.DESTROY_WITH_PARENT, buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK))
self.preferences = Gtk.Notebook()
class PreferencesDialog:
self.general = GeneralPage()
self.preferences.insert_page(self.general, Gtk.Label("General"), 0)
""" A dialog to specify the PyQSO preferences. """
self.view = ViewPage()
self.preferences.insert_page(self.view, Gtk.Label("View"), 1)
def __init__(self, application):
""" Set up the various pages of the preferences dialog.
self.hamlib = HamlibPage()
self.preferences.insert_page(self.hamlib, Gtk.Label("Hamlib"), 2)
:arg application: The PyQSO application containing the main Gtk window, etc.
"""
self.vbox.pack_start(self.preferences, True, True, 2)
self.show_all()
logging.debug("Setting up the preferences dialog...")
logging.debug("Preferences dialog ready!")
self.application = application
self.builder = self.application.builder
glade_file_path = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "pyqso.glade")
self.builder.add_objects_from_file(glade_file_path, ("preferences_dialog",))
self.dialog = self.builder.get_object("preferences_dialog")
return
self.general = GeneralPage(self.dialog, self.builder)
self.view = ViewPage(self.dialog, self.builder)
self.records = RecordsPage(self.dialog, self.builder)
self.import_export = ImportExportPage(self.dialog, self.builder)
self.hamlib = HamlibPage(self.dialog, self.builder)
self.world_map = WorldMapPage(self.dialog, self.builder)
def commit(self):
""" Commit the user preferences to the configuration file. """
logging.debug("Committing the user preferences to the configuration file...")
general_data = self.general.get_data()
view_data = self.view.get_data()
hamlib_data = self.hamlib.get_data()
self.dialog.show_all()
config = ConfigParser.ConfigParser()
logging.debug("Preferences dialog ready!")
# General
config.add_section("general")
for key in general_data.keys():
config.set("general", key.lower(), general_data[key])
return
# View
config.add_section("view")
for key in view_data.keys():
config.set("view", key.lower(), view_data[key])
def commit(self):
""" Commit the user preferences to the configuration file. """
# Hamlib
config.add_section("hamlib")
for key in hamlib_data.keys():
config.set("hamlib", key.lower(), hamlib_data[key])
with open(os.path.expanduser('~/.pyqso.ini'), 'w') as f:
config.write(f)
logging.debug("Committing the user preferences to the configuration file...")
return
config = configparser.ConfigParser()
class GeneralPage(Gtk.VBox):
def __init__(self):
logging.debug("Setting up the General page of the preferences dialog...")
# General
config.add_section("general")
for key in list(self.general.data.keys()):
config.set("general", key.lower(), str(self.general.data[key]))
Gtk.VBox.__init__(self, spacing=2)
# View
config.add_section("view")
for key in list(self.view.data.keys()):
config.set("view", key.lower(), str(self.view.data[key]))
# Remember that the have_config conditional in the PyQSO class may be out-of-date the next time the user opens up the preferences dialog
# because a configuration file may have been created after launching the application. Let's check to see if one exists again...
config = ConfigParser.ConfigParser()
have_config = (config.read(os.path.expanduser('~/.pyqso.ini')) != [])
# Records
config.add_section("records")
for key in list(self.records.data.keys()):
config.set("records", key.lower(), str(self.records.data[key]))
self.sources = {}
# Import/Export
config.add_section("import_export")
for key in list(self.import_export.data.keys()):
config.set("import_export", key.lower(), str(self.import_export.data[key]))
frame = Gtk.Frame()
frame.set_label("Startup")
hbox = Gtk.HBox()
self.sources["SHOW_TOOLBOX"] = Gtk.CheckButton("Show toolbox by default")
if(have_config):
self.sources["SHOW_TOOLBOX"].set_active(config.get("general", "show_toolbox") == "True")
else:
self.sources["SHOW_TOOLBOX"].set_active(False)
hbox.pack_start(self.sources["SHOW_TOOLBOX"], False, False, 2)
frame.add(hbox)
self.pack_start(frame, False, False, 2)
# Hamlib
config.add_section("hamlib")
for key in list(self.hamlib.data.keys()):
config.set("hamlib", key.lower(), str(self.hamlib.data[key]))
frame = Gtk.Frame()
frame.set_label("Login details (qrz.com)")
inner_vbox = Gtk.VBox()
# World Map
config.add_section("world_map")
for key in list(self.world_map.data.keys()):
config.set("world_map", key.lower(), str(self.world_map.data[key]))
hbox = Gtk.HBox()
label = Gtk.Label("Username: ")
label.set_width_chars(9)
label.set_alignment(0, 0.5)
hbox.pack_start(label, False, False, 2)
self.sources["QRZ_USERNAME"] = Gtk.Entry()
if(have_config):
self.sources["QRZ_USERNAME"].set_text(config.get("general", "qrz_username"))
hbox.pack_start(self.sources["QRZ_USERNAME"], False, False, 2)
inner_vbox.pack_start(hbox, False, False, 2)
# Write the preferences to file.
with open(os.path.expanduser(PREFERENCES_FILE), 'w') as f:
config.write(f)
hbox = Gtk.HBox()
label = Gtk.Label("Password: ")
label.set_width_chars(9)
label.set_alignment(0, 0.5)
hbox.pack_start(label, False, False, 2)
self.sources["QRZ_PASSWORD"] = Gtk.Entry()
self.sources["QRZ_PASSWORD"].set_visibility(False) # Mask the password with the "*" character.
if(have_config):
self.sources["QRZ_PASSWORD"].set_text(base64.b64decode(config.get("general", "qrz_password")))
hbox.pack_start(self.sources["QRZ_PASSWORD"], False, False, 2)
inner_vbox.pack_start(hbox, False, False, 2)
return
label = Gtk.Label("Warning: Login details are currently stored as\nBase64-encoded plain text in the configuration file.")
inner_vbox.pack_start(label, False, False, 2)
frame.add(inner_vbox)
self.pack_start(frame, False, False, 2)
class GeneralPage:
logging.debug("General page of the preferences dialog ready!")
return
""" The section of the preferences dialog containing general preferences. """
def get_data(self):
logging.debug("Retrieving data from the General page of the preferences dialog...")
data = {}
data["SHOW_TOOLBOX"] = self.sources["SHOW_TOOLBOX"].get_active()
data["QRZ_USERNAME"] = self.sources["QRZ_USERNAME"].get_text()
data["QRZ_PASSWORD"] = base64.b64encode(self.sources["QRZ_PASSWORD"].get_text())
return data
def __init__(self, parent, builder):
""" Set up the General page of the Preferences dialog. """
class ViewPage(Gtk.VBox):
def __init__(self):
logging.debug("Setting up the View page of the preferences dialog...")
self.parent = parent
self.builder = builder
self.sources = {}
Gtk.VBox.__init__(self, spacing=2)
# Remember that the have_config conditional in the PyQSO class may be out-of-date the next time the user opens up the preferences dialog
# because a configuration file may have been created after launching the application. Let's check to see if one exists again...
config = configparser.ConfigParser()
have_config = (config.read(PREFERENCES_FILE) != [])
config = ConfigParser.ConfigParser()
have_config = (config.read(os.path.expanduser('~/.pyqso.ini')) != [])
# Show toolbox.
self.sources["SHOW_TOOLBOX"] = self.builder.get_object("general_show_toolbox_checkbutton")
(section, option) = ("general", "show_toolbox")
if(have_config and config.has_option(section, option)):
self.sources["SHOW_TOOLBOX"].set_active(config.getboolean(section, option))
else:
self.sources["SHOW_TOOLBOX"].set_active(False)
self.sources = {}
# Show statistics.
self.sources["SHOW_YEARLY_STATISTICS"] = self.builder.get_object("general_show_yearly_statistics_checkbutton")
(section, option) = ("general", "show_yearly_statistics")
if(have_config and config.has_option(section, option)):
self.sources["SHOW_YEARLY_STATISTICS"].set_active(config.getboolean(section, option))
else:
self.sources["SHOW_YEARLY_STATISTICS"].set_active(False)
# Divide the list of available field names up into multiple columns (of maximum length 'max_buttons_per_column')
# so we don't make the Preferences dialog too long.
hbox = Gtk.HBox(spacing=2)
max_buttons_per_column = 6
number_of_columns = int( len(AVAILABLE_FIELD_NAMES_ORDERED)/max_buttons_per_column ) + 1 # Number of check buttons per column
for i in range(0, number_of_columns):
vbox = Gtk.VBox(spacing=2)
for j in range(0, max_buttons_per_column):
if(i*max_buttons_per_column + j >= len(AVAILABLE_FIELD_NAMES_ORDERED)):
break
field_name = AVAILABLE_FIELD_NAMES_ORDERED[i*max_buttons_per_column + j]
button = Gtk.CheckButton(AVAILABLE_FIELD_NAMES_FRIENDLY[field_name ])
if(have_config):
button.set_active(config.get("view", field_name.lower()) == "True")
# Default logbook.
self.sources["DEFAULT_LOGBOOK"] = self.builder.get_object("general_default_logbook_checkbutton")
(section, option) = ("general", "default_logbook")
if(have_config and config.has_option(section, option)):
self.sources["DEFAULT_LOGBOOK"].set_active(config.getboolean(section, option))
else:
self.sources["DEFAULT_LOGBOOK"].set_active(False)
self.sources["DEFAULT_LOGBOOK"].connect("toggled", self.on_default_logbook_toggled)
self.sources["DEFAULT_LOGBOOK_PATH"] = self.builder.get_object("general_default_logbook_entry")
(section, option) = ("general", "default_logbook")
# Disable the text entry box if the default logbook checkbox is not checked.
if(have_config and config.has_option(section, option)):
self.sources["DEFAULT_LOGBOOK_PATH"].set_sensitive(self.sources["DEFAULT_LOGBOOK"].get_active())
self.builder.get_object("general_default_logbook_button").set_sensitive(self.sources["DEFAULT_LOGBOOK"].get_active())
else:
self.sources["DEFAULT_LOGBOOK_PATH"].set_sensitive(False)
self.builder.get_object("general_default_logbook_button").set_sensitive(False)
(section, option) = ("general", "default_logbook_path")
if(have_config and config.has_option(section, option)):
self.sources["DEFAULT_LOGBOOK_PATH"].set_text(config.get(section, option))
self.builder.get_object("general_default_logbook_button").connect("clicked", self.on_default_logbook_clicked)
# Keep 'Add Record' dialog open.
self.sources["KEEP_OPEN"] = self.builder.get_object("general_keep_open_checkbutton")
(section, option) = ("general", "keep_open")
if(have_config and config.has_option(section, option)):
self.sources["KEEP_OPEN"].set_active(config.getboolean(section, option))
else:
self.sources["KEEP_OPEN"].set_active(False)
return
@property
def data(self):
""" User preferences regarding General settings. """
data = {}
data["SHOW_TOOLBOX"] = self.sources["SHOW_TOOLBOX"].get_active()
data["SHOW_YEARLY_STATISTICS"] = self.sources["SHOW_YEARLY_STATISTICS"].get_active()
data["DEFAULT_LOGBOOK"] = self.sources["DEFAULT_LOGBOOK"].get_active()
data["DEFAULT_LOGBOOK_PATH"] = os.path.expanduser(self.sources["DEFAULT_LOGBOOK_PATH"].get_text())
data["KEEP_OPEN"] = self.sources["KEEP_OPEN"].get_active()
return data
def on_default_logbook_toggled(self, widget, data=None):
if(widget.get_active()):
self.sources["DEFAULT_LOGBOOK_PATH"].set_sensitive(True)
self.builder.get_object("general_default_logbook_button").set_sensitive(True)
else:
self.sources["DEFAULT_LOGBOOK_PATH"].set_sensitive(False)
self.builder.get_object("general_default_logbook_button").set_sensitive(False)
return
def on_default_logbook_clicked(self, widget):
""" Let the user select the default logbook file via a file chooser dialog,
and set the path in the adjacent entry box. """
dialog = Gtk.FileChooserDialog("Select SQLite Database File",
self.parent,
Gtk.FileChooserAction.OPEN,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
response = dialog.run()
if(response == Gtk.ResponseType.OK):
path = dialog.get_filename()
self.sources["DEFAULT_LOGBOOK_PATH"].set_text(path)
dialog.destroy()
return
class ViewPage:
""" The section of the preferences dialog containing view-related preferences. """
def __init__(self, parent, builder):
""" Set up the View page of the Preferences dialog. """
self.parent = parent
self.builder = builder
self.sources = {}
config = configparser.ConfigParser()
have_config = (config.read(PREFERENCES_FILE) != [])
# Visible fields
for field_name in AVAILABLE_FIELD_NAMES_ORDERED:
self.sources[field_name] = self.builder.get_object("visible_fields_%s" % (field_name.lower()))
if(have_config and config.has_option("view", field_name.lower())):
self.sources[field_name].set_active(config.getboolean("view", field_name.lower()))
else:
button.set_active(True)
self.sources[field_name] = button
vbox.pack_start(button, False, False, 2)
hbox.pack_start(vbox, False, False, 2)
self.pack_start(hbox, False, False, 2)
self.sources[field_name].set_active(True)
self.label = Gtk.Label("Note: View-related changes will not take effect\nuntil PyQSO is restarted.")
self.pack_start(self.label, False, False, 2)
return
logging.debug("View page of the preferences dialog ready!")
return
@property
def data(self):
""" User preferences regarding View settings. """
data = {}
for field_name in AVAILABLE_FIELD_NAMES_ORDERED:
data[field_name] = self.sources[field_name].get_active()
return data
def get_data(self):
logging.debug("Retrieving data from the View page of the preferences dialog...")
data = {}
for field_name in AVAILABLE_FIELD_NAMES_ORDERED:
data[field_name] = self.sources[field_name].get_active()
return data
class HamlibPage(Gtk.VBox):
def __init__(self):
logging.debug("Setting up the Hamlib page of the preferences dialog...")
class RecordsPage:
Gtk.VBox.__init__(self, spacing=2)
""" The section of the preferences dialog containing record-related preferences. """
config = ConfigParser.ConfigParser()
have_config = (config.read(os.path.expanduser('~/.pyqso.ini')) != [])
def __init__(self, parent, builder):
""" Set up the Record page of the Preferences dialog. """
self.sources = {}
self.parent = parent
self.builder = builder
self.sources = {}
frame = Gtk.Frame()
frame.set_label("Hamlib support")
# Remember that the have_config conditional in the PyQSO class may be out-of-date the next time the user opens up the preferences dialog
# because a configuration file may have been created after launching the application. Let's check to see if one exists again...
config = configparser.ConfigParser()
have_config = (config.read(PREFERENCES_FILE) != [])
vbox_inner = Gtk.VBox(spacing=2)
# Autocomplete
self.sources["AUTOCOMPLETE_BAND"] = self.builder.get_object("records_autocomplete_band_checkbutton")
(section, option) = ("records", "autocomplete_band")
if(have_config and config.has_option(section, option)):
self.sources["AUTOCOMPLETE_BAND"].set_active(config.getboolean(section, option))
else:
self.sources["AUTOCOMPLETE_BAND"].set_active(True)
self.sources["AUTOFILL"] = Gtk.CheckButton("Auto-fill Frequency field")
if(have_config):
self.sources["AUTOFILL"].set_active(config.get("hamlib", "autofill") == "True")
else:
self.sources["AUTOFILL"].set_active(False)
vbox_inner.pack_start(self.sources["AUTOFILL"], False, False, 2)
self.sources["USE_UTC"] = self.builder.get_object("records_autocomplete_utc_checkbutton")
(section, option) = ("records", "use_utc")
if(have_config and config.has_option(section, option)):
self.sources["USE_UTC"].set_active(config.getboolean(section, option))
else:
self.sources["USE_UTC"].set_active(True)
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label("Model: ")
label.set_alignment(0, 0.5)
label.set_width_chars(17)
hbox_temp.pack_start(label, False, False, 2)
# Default values
# Get the list of rig models
models = ["RIG_MODEL_NONE"]
if(have_hamlib):
try:
for item in dir(Hamlib):
if(item.startswith("RIG_MODEL_")):
models.append(item)
except:
logging.error("Could not obtain rig models list via Hamlib!")
else:
logging.debug("Hamlib module not present. Could not obtain a list of rig models.")
# Mode
self.sources["DEFAULT_MODE"] = self.builder.get_object("default_values_mode_combo")
for mode in sorted(MODES.keys()):
self.sources["DEFAULT_MODE"].append_text(mode)
(section, option) = ("records", "default_mode")
if(have_config and config.has_option(section, option)):
mode = config.get(section, option)
else:
mode = ""
self.sources["DEFAULT_MODE"].set_active(sorted(MODES.keys()).index(mode))
self.sources["DEFAULT_MODE"].connect("changed", self.on_mode_changed)
self.sources["RIG_MODEL"] = Gtk.ComboBoxText()
for model in models:
self.sources["RIG_MODEL"].append_text(model)
if(have_config):
self.sources["RIG_MODEL"].set_active(models.index(config.get("hamlib", "rig_model")))
else:
self.sources["RIG_MODEL"].set_active(models.index("RIG_MODEL_NONE")) # Set to RIG_MODEL_NONE as the default option.
hbox_temp.pack_start(self.sources["RIG_MODEL"], True, True, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# Submode
self.sources["DEFAULT_SUBMODE"] = self.builder.get_object("default_values_submode_combo")
for submode in MODES[mode]:
self.sources["DEFAULT_SUBMODE"].append_text(submode)
(section, option) = ("records", "default_submode")
if(have_config and config.has_option(section, option)):
submode = config.get(section, option)
else:
submode = ""
self.sources["DEFAULT_SUBMODE"].set_active(MODES[mode].index(submode))
# Path to rig
hbox_temp = Gtk.HBox()
label = Gtk.Label("Path to radio device: ")
label.set_width_chars(17)
label.set_alignment(0, 0.5)
hbox_temp.pack_start(label, False, False, 2)
self.sources["RIG_PATHNAME"] = Gtk.Entry()
if(have_config):
self.sources["RIG_PATHNAME"].set_text(config.get("hamlib", "rig_pathname"))
hbox_temp.pack_start(self.sources["RIG_PATHNAME"], True, True, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# Power
self.sources["DEFAULT_POWER"] = self.builder.get_object("default_values_tx_power_entry")
(section, option) = ("records", "default_power")
if(have_config and config.has_option(section, option)):
self.sources["DEFAULT_POWER"].set_text(config.get(section, option))
else:
self.sources["DEFAULT_POWER"].set_text("")
frame.add(vbox_inner)
self.pack_start(frame, True, True, 2)
# Frequency unit
self.sources["DEFAULT_FREQUENCY_UNIT"] = self.builder.get_object("default_values_frequency_unit_combo")
units = ["Hz", "kHz", "MHz", "GHz"]
for unit in units:
self.sources["DEFAULT_FREQUENCY_UNIT"].append_text(unit)
(section, option) = ("records", "default_frequency_unit")
if(have_config and config.has_option(section, option)):
self.sources["DEFAULT_FREQUENCY_UNIT"].set_active(units.index(config.get(section, option)))
else:
self.sources["DEFAULT_FREQUENCY_UNIT"].set_active(units.index("MHz"))
logging.debug("Hamlib page of the preferences dialog ready!")
return
# Callsign lookup
self.sources["CALLSIGN_DATABASE"] = self.builder.get_object("callsign_lookup_database_combo")
callsign_database = ["", "qrz.com", "hamqth.com"]
for database in callsign_database:
self.sources["CALLSIGN_DATABASE"].append_text(database)
(section, option) = ("records", "callsign_database")
if(have_config and config.has_option(section, option)):
self.sources["CALLSIGN_DATABASE"].set_active(callsign_database.index(config.get(section, option)))
else:
self.sources["CALLSIGN_DATABASE"].set_active(callsign_database.index(""))
def get_data(self):
logging.debug("Retrieving data from the Hamlib page of the preferences dialog...")
data = {}
data["AUTOFILL"] = self.sources["AUTOFILL"].get_active()
data["RIG_PATHNAME"] = self.sources["RIG_PATHNAME"].get_text()
data["RIG_MODEL"] = self.sources["RIG_MODEL"].get_active_text()
return data
# Login details
self.sources["CALLSIGN_DATABASE_USERNAME"] = self.builder.get_object("callsign_lookup_login_details_username_entry")
(section, option) = ("records", "callsign_database_username")
if(have_config and config.has_option(section, option)):
self.sources["CALLSIGN_DATABASE_USERNAME"].set_text(config.get(section, option))
self.sources["CALLSIGN_DATABASE_PASSWORD"] = self.builder.get_object("callsign_lookup_login_details_password_entry")
(section, option) = ("records", "callsign_database_password")
if(have_config and config.has_option(section, option)):
password = base64.b64decode(config.get(section, option)).decode("utf-8")
self.sources["CALLSIGN_DATABASE_PASSWORD"].set_text(password)
self.sources["IGNORE_PREFIX_SUFFIX"] = self.builder.get_object("callsign_lookup_ignore_prefix_suffix_checkbutton")
(section, option) = ("records", "ignore_prefix_suffix")
if(have_config and config.has_option(section, option)):
self.sources["IGNORE_PREFIX_SUFFIX"].set_active(config.getboolean(section, option))
else:
self.sources["IGNORE_PREFIX_SUFFIX"].set_active(True)
return
@property
def data(self):
""" User preferences regarding Records settings. """
data = {}
data["AUTOCOMPLETE_BAND"] = self.sources["AUTOCOMPLETE_BAND"].get_active()
data["USE_UTC"] = self.sources["USE_UTC"].get_active()
data["DEFAULT_MODE"] = self.sources["DEFAULT_MODE"].get_active_text()
data["DEFAULT_SUBMODE"] = self.sources["DEFAULT_SUBMODE"].get_active_text()
data["DEFAULT_POWER"] = self.sources["DEFAULT_POWER"].get_text()
data["DEFAULT_FREQUENCY_UNIT"] = self.sources["DEFAULT_FREQUENCY_UNIT"].get_active_text()
data["CALLSIGN_DATABASE"] = self.sources["CALLSIGN_DATABASE"].get_active_text()
data["CALLSIGN_DATABASE_USERNAME"] = self.sources["CALLSIGN_DATABASE_USERNAME"].get_text()
data["CALLSIGN_DATABASE_PASSWORD"] = base64.b64encode(self.sources["CALLSIGN_DATABASE_PASSWORD"].get_text().encode("utf-8")).decode("utf-8") # Need to convert from bytes to str here.
data["IGNORE_PREFIX_SUFFIX"] = self.sources["IGNORE_PREFIX_SUFFIX"].get_active()
return data
def on_mode_changed(self, combo):
""" If the MODE field has changed its value, then fill the SUBMODE field with all the available SUBMODE options for that new MODE. """
self.sources["DEFAULT_SUBMODE"].get_model().clear()
mode = combo.get_active_text()
for submode in MODES[mode]:
self.sources["DEFAULT_SUBMODE"].append_text(submode)
self.sources["DEFAULT_SUBMODE"].set_active(MODES[mode].index(""))
return
class ImportExportPage:
""" The section of the preferences dialog containing import/export-related preferences. """
def __init__(self, parent, builder):
""" Set up the Import/Export page of the Preferences dialog. """
self.parent = parent
self.builder = builder
self.sources = {}
# Remember that the have_config conditional in the PyQSO class may be out-of-date the next time the user opens up the preferences dialog
# because a configuration file may have been created after launching the application. Let's check to see if one exists again...
config = configparser.ConfigParser()
have_config = (config.read(PREFERENCES_FILE) != [])
# Import
self.sources["MERGE_COMMENT"] = self.builder.get_object("adif_import_merge_comment_checkbutton")
(section, option) = ("import_export", "merge_comment")
if(have_config and config.has_option(section, option)):
self.sources["MERGE_COMMENT"].set_active(config.getboolean(section, option))
else:
self.sources["MERGE_COMMENT"].set_active(False)
return
@property
def data(self):
""" User preferences regarding Import/Export settings. """
data = {}
data["MERGE_COMMENT"] = self.sources["MERGE_COMMENT"].get_active()
return data
class HamlibPage:
""" The section of the preferences dialog containing Hamlib-related preferences. """
def __init__(self, parent, builder):
""" Set up the Hamlib page of the Preferences dialog. """
self.parent = parent
self.builder = builder
self.sources = {}
config = configparser.ConfigParser()
have_config = (config.read(PREFERENCES_FILE) != [])
self.sources["AUTOFILL"] = self.builder.get_object("hamlib_support_checkbutton")
(section, option) = ("hamlib", "autofill")
if(have_config and config.has_option(section, option)):
self.sources["AUTOFILL"].set_active(config.getboolean(section, option))
else:
self.sources["AUTOFILL"].set_active(False)
# Get the list of rig models
models = ["RIG_MODEL_NONE"]
if(have_hamlib):
try:
for item in dir(Hamlib):
if(item.startswith("RIG_MODEL_")):
models.append(item)
except:
logging.error("Could not obtain rig models list via Hamlib!")
else:
logging.debug("Hamlib module not present. Could not obtain a list of rig models.")
self.sources["RIG_MODEL"] = self.builder.get_object("hamlib_support_model_combo")
for model in models:
self.sources["RIG_MODEL"].append_text(model)
(section, option) = ("hamlib", "rig_model")
if(have_config and config.has_option("hamlib", "rig_model")):
self.sources["RIG_MODEL"].set_active(models.index(config.get("hamlib", "rig_model")))
else:
self.sources["RIG_MODEL"].set_active(models.index("RIG_MODEL_NONE")) # Set to RIG_MODEL_NONE as the default option.
# Path to rig
self.sources["RIG_PATHNAME"] = self.builder.get_object("hamlib_support_path_entry")
(section, option) = ("hamlib", "rig_pathname")
if(have_config and config.has_option(section, option)):
self.sources["RIG_PATHNAME"].set_text(config.get(section, option))
return
@property
def data(self):
""" User preferences regarding Hamlib settings. """
data = {}
data["AUTOFILL"] = self.sources["AUTOFILL"].get_active()
data["RIG_PATHNAME"] = self.sources["RIG_PATHNAME"].get_text()
data["RIG_MODEL"] = self.sources["RIG_MODEL"].get_active_text()
return data
class WorldMapPage:
""" The section of the preferences dialog containing World Map preferences. """
def __init__(self, parent, builder):
""" Set up the World Map page of the Preferences dialog. """
self.parent = parent
self.builder = builder
self.sources = {}
# Remember that the have_config conditional in the PyQSO class may be out-of-date the next time the user opens up the preferences dialog
# because a configuration file may have been created after launching the application. Let's check to see if one exists again...
config = configparser.ConfigParser()
have_config = (config.read(PREFERENCES_FILE) != [])
# Option to pinpoint QTH on grey line map.
self.sources["SHOW_QTH"] = self.builder.get_object("world_map_show_qth_checkbutton")
(section, option) = ("world_map", "show_qth")
if(have_config and config.has_option(section, option)):
self.sources["SHOW_QTH"].set_active(config.getboolean(section, option))
else:
self.sources["SHOW_QTH"].set_active(False)
self.sources["QTH_NAME"] = self.builder.get_object("world_map_qth_name_entry")
button = self.builder.get_object("world_map_qth_lookup")
button.connect("clicked", self.lookup_callback) # Uses geocoding to find the latitude-longitude coordinates.
self.sources["QTH_LATITUDE"] = self.builder.get_object("world_map_qth_coordinates_latitude_entry")
self.sources["QTH_LONGITUDE"] = self.builder.get_object("world_map_qth_coordinates_longitude_entry")
(section, option) = ("world_map", "show_qth")
# Disable the text entry boxes if the SHOW_QTH checkbox is not checked.
if(have_config and config.has_option(section, option)):
self.sources["QTH_NAME"].set_sensitive(self.sources["SHOW_QTH"].get_active())
self.sources["QTH_LATITUDE"].set_sensitive(self.sources["SHOW_QTH"].get_active())
self.sources["QTH_LONGITUDE"].set_sensitive(self.sources["SHOW_QTH"].get_active())
button.set_sensitive(self.sources["SHOW_QTH"].get_active())
else:
self.sources["QTH_NAME"].set_sensitive(False)
self.sources["QTH_LATITUDE"].set_sensitive(False)
self.sources["QTH_LONGITUDE"].set_sensitive(False)
button.set_sensitive(False)
(section, option) = ("world_map", "qth_name")
if(have_config and config.has_option(section, option)):
self.sources["QTH_NAME"].set_text(config.get(section, option))
(section, option) = ("world_map", "qth_latitude")
if(have_config and config.has_option(section, option)):
self.sources["QTH_LATITUDE"].set_text(config.get(section, option))
(section, option) = ("world_map", "qth_longitude")
if(have_config and config.has_option(section, option)):
self.sources["QTH_LONGITUDE"].set_text(config.get(section, option))
self.sources["SHOW_QTH"].connect("toggled", self.on_show_qth_toggled)
# Option to show Maidenhead grid squares.
self.sources["SHOW_GRID_SQUARES"] = self.builder.get_object("world_map_show_grid_squares_checkbutton")
(section, option) = ("world_map", "show_grid_squares")
if(have_config and config.has_option(section, option)):
self.sources["SHOW_GRID_SQUARES"].set_active(config.getboolean(section, option))
else:
self.sources["SHOW_GRID_SQUARES"].set_active(False)
# Option to shade in worked Maidenhead grid squares.
self.sources["SHADE_WORKED_GRID_SQUARES"] = self.builder.get_object("world_map_shade_worked_grid_squares_checkbutton")
(section, option) = ("world_map", "shade_worked_grid_squares")
if(have_config and config.has_option(section, option)):
self.sources["SHADE_WORKED_GRID_SQUARES"].set_active(config.getboolean(section, option))
else:
self.sources["SHADE_WORKED_GRID_SQUARES"].set_active(False)
return
@property
def data(self):
""" User preferences regarding World Map settings. """
data = {}
data["SHOW_QTH"] = self.sources["SHOW_QTH"].get_active()
data["QTH_NAME"] = self.sources["QTH_NAME"].get_text()
data["QTH_LATITUDE"] = self.sources["QTH_LATITUDE"].get_text()
data["QTH_LONGITUDE"] = self.sources["QTH_LONGITUDE"].get_text()
data["SHOW_GRID_SQUARES"] = self.sources["SHOW_GRID_SQUARES"].get_active()
data["SHADE_WORKED_GRID_SQUARES"] = self.sources["SHADE_WORKED_GRID_SQUARES"].get_active()
return data
def on_show_qth_toggled(self, widget, data=None):
if(widget.get_active()):
self.sources["QTH_NAME"].set_sensitive(True)
self.sources["QTH_LATITUDE"].set_sensitive(True)
self.sources["QTH_LONGITUDE"].set_sensitive(True)
self.builder.get_object("world_map_qth_lookup").set_sensitive(True)
else:
self.sources["QTH_NAME"].set_sensitive(False)
self.sources["QTH_LATITUDE"].set_sensitive(False)
self.sources["QTH_LONGITUDE"].set_sensitive(False)
self.builder.get_object("world_map_qth_lookup").set_sensitive(False)
return
def lookup_callback(self, widget=None):
""" Perform geocoding of the QTH location to obtain latitude-longitude coordinates. """
if(not have_geocoder):
error(parent=self.parent, message="Geocoder module could not be imported. Geocoding aborted.")
return
logging.debug("Geocoding QTH location...")
name = self.sources["QTH_NAME"].get_text()
try:
g = geocoder.google(name)
latitude, longitude = g.latlng
self.sources["QTH_LATITUDE"].set_text(str(latitude))
self.sources["QTH_LONGITUDE"].set_text(str(longitude))
logging.debug("QTH coordinates found: (%s, %s)", str(latitude), str(longitude))
except ValueError as e:
error(parent=self.parent, message="Unable to lookup QTH coordinates. Is the QTH name correct?")
logging.exception(e)
except Exception as e:
error(parent=self.parent, message="Unable to lookup QTH coordinates. Check connection to the internets? Lookup limit reached?")
logging.exception(e)
return

132
pyqso/printer.py 100644
Wyświetl plik

@ -0,0 +1,132 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk, Pango, PangoCairo
import logging
from pyqso.auxiliary_dialogs import error
class Printer(object):
""" Handles the printing of one or more records to file or paper. """
def __init__(self, application):
""" Initialise the record printer.
:arg application: The PyQSO application containing the main Gtk window, etc.
"""
self.application = application
self.action = Gtk.PrintOperationAction.PRINT_DIALOG
self.operation = Gtk.PrintOperation()
ps = Gtk.PageSetup()
ps.set_orientation(Gtk.PageOrientation.LANDSCAPE)
self.operation.set_default_page_setup(ps)
self.operation.set_unit(Gtk.Unit.MM)
self.operation.connect("begin_print", self.begin_print)
self.operation.connect("draw_page", self.draw_page)
return
def print_records(self, records, title=None):
""" Perform the print operation.
:arg dict records: The records to be printed.
:arg str title: Optional title for the document. Default is None.
:returns: The result of the print operation.
:rtype: Gtk.PrintOperationResult
"""
# Add the title, if given.
if(title):
self.text_to_print = title + "\n\n"
else:
self.text_to_print = ""
# Assemble the header and records into one string.
line_format = "%-5s\t%-15s\t%-8s\t%-6s\t%-15s\t%-12s\t%-8s\t%-8s\n"
self.text_to_print += line_format % ("Index", "Callsign", "Date", "Time", "Frequency", "Mode", "RST Sent", "RST Rcvd")
self.text_to_print += line_format % ("-----", "--------", "----", "----", "---------", "----", "--------", "--------")
for r in records:
self.text_to_print += line_format % (str(r["id"]), str(r["CALL"]), str(r["QSO_DATE"]), str(r["TIME_ON"]), str(r["FREQ"]), str(r["MODE"]), str(r["RST_SENT"]), str(r["RST_RCVD"]))
result = self.operation.run(self.action, parent=self.application.window)
if(result == Gtk.PrintOperationResult.ERROR):
error(parent=self.application.window, message="Unable to print the log.")
return result
def begin_print(self, operation, context):
""" Specify the layout/position/font of the text on the pages to be printed.
:arg Gtk.PrintOperation operation: The printing API.
:arg Gtk.PrintContext context: Used to draw/render the pages to print.
"""
width = context.get_width() # Measured in pixels.
height = context.get_height() # Measured in pixels.
layout = context.create_pango_layout()
layout.set_font_description(Pango.FontDescription("monospace expanded 10"))
layout.set_width(int(width*Pango.SCALE))
layout.set_text(self.text_to_print, -1)
number_of_pages = 1
page_height = 0
for line in range(0, layout.get_line_count()):
layout_line = layout.get_line(line)
ink_rectangle, logical_rectangle = layout_line.get_pixel_extents()
self.line_height = logical_rectangle.height + 3.0
page_height += self.line_height
if((page_height + 2*self.line_height) >= height):
# Go on to the next page.
number_of_pages += 1
page_height = 0.0
operation.set_n_pages(number_of_pages)
logging.debug("Printing %d pages..." % number_of_pages)
self.text_to_print = self.text_to_print.split("\n")
return
def draw_page(self, operation, context, page_number):
""" Render the QSO details on the page.
:arg Gtk.PrintOperation operation: The printing API.
:arg Gtk.PrintContext context: Used to draw/render the pages to print.
:arg int page_number: The current page number.
"""
cr = context.get_cairo_context()
cr.set_source_rgb(0, 0, 0)
layout = context.create_pango_layout()
layout.set_font_description(Pango.FontDescription("monospace expanded 10"))
layout.set_width(int(context.get_width()*Pango.SCALE))
current_line_number = 1
for line in self.text_to_print:
layout.set_text(line, -1)
cr.move_to(5, current_line_number*self.line_height)
PangoCairo.update_layout(cr, layout)
PangoCairo.show_layout(cr, layout)
current_line_number += 1
if((current_line_number+1)*self.line_height >= context.get_height()):
for j in range(0, current_line_number-1):
self.text_to_print.pop(0) # Remove what has been printed already before draw_page is called again.
break
return

Wyświetl plik

@ -1,7 +1,6 @@
#!/usr/bin/env python
# File: record_dialog.py
#!/usr/bin/env python3
# Copyright (C) 2013 Christian Jacobs.
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
@ -18,465 +17,511 @@
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk, GObject
from gi.repository import Gtk, Gdk
import logging
import ConfigParser
import os
try:
import configparser
except ImportError:
import ConfigParser as configparser
from datetime import datetime
from os.path import expanduser
import base64
try:
import Hamlib
have_hamlib = True
import Hamlib
have_hamlib = True
except ImportError:
logging.error("Could not import the Hamlib module!")
have_hamlib = False
logging.warning("Could not import the Hamlib module!")
have_hamlib = False
from adif import AVAILABLE_FIELD_NAMES_FRIENDLY, AVAILABLE_FIELD_NAMES_ORDERED
from callsign_lookup import *
from auxiliary_dialogs import *
class RecordDialog(Gtk.Dialog):
""" A dialog through which users can enter information about a QSO/record. """
def __init__(self, parent, log, index=None):
""" Set up the layout of the record dialog.
If a record index is specified in the 'index' argument, then the dialog turns into 'edit record mode' and fills the data sources with the existing data in the log.
If the 'index' argument is None, then the dialog starts off with nothing in the data sources (e.g. the Gtk.Entry boxes). """
logging.debug("Setting up the record dialog...")
if(index is not None):
title = "Edit Record %d" % index
else:
title = "Add Record"
Gtk.Dialog.__init__(self, title=title, parent=parent, flags=Gtk.DialogFlags.DESTROY_WITH_PARENT, buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK))
## QSO DATA FRAME
qso_frame = Gtk.Frame()
qso_frame.set_label("QSO Information")
self.vbox.add(qso_frame)
hbox_inner = Gtk.HBox(spacing=2)
vbox_inner = Gtk.VBox(spacing=2)
hbox_inner.pack_start(vbox_inner, True, True, 2)
# Create label:entry pairs and store them in a dictionary
self.sources = {}
# CALL
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["CALL"], halign=Gtk.Align.START)
label.set_width_chars(15)
label.set_alignment(0, 0.5)
hbox_temp.pack_start(label, False, False, 2)
self.sources["CALL"] = Gtk.Entry()
self.sources["CALL"].set_width_chars(15)
hbox_temp.pack_start(self.sources["CALL"], False, False, 2)
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_INFO, Gtk.IconSize.MENU)
button = Gtk.Button()
button.add(icon)
button.connect("clicked", self.lookup_callback) # Looks up the callsign on qrz.com for callsign and station information.
button.set_tooltip_text("Lookup on qrz.com")
hbox_temp.pack_start(button, True, True, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# DATE
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["QSO_DATE"], halign=Gtk.Align.START)
label.set_width_chars(15)
label.set_alignment(0, 0.5)
hbox_temp.pack_start(label, False, False, 2)
self.sources["QSO_DATE"] = Gtk.Entry()
self.sources["QSO_DATE"].set_width_chars(15)
hbox_temp.pack_start(self.sources["QSO_DATE"], False, False, 2)
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_GO_BACK, Gtk.IconSize.MENU)
button = Gtk.Button()
button.add(icon)
button.connect("clicked", self.calendar_callback)
button.set_tooltip_text("Select date from calendar")
hbox_temp.pack_start(button, True, True, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# TIME
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["TIME_ON"], halign=Gtk.Align.START)
label.set_alignment(0, 0.5)
label.set_width_chars(15)
hbox_temp.pack_start(label, False, False, 2)
self.sources["TIME_ON"] = Gtk.Entry()
self.sources["TIME_ON"].set_width_chars(15)
hbox_temp.pack_start(self.sources["TIME_ON"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# FREQ
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["FREQ"], halign=Gtk.Align.START)
label.set_alignment(0, 0.5)
label.set_width_chars(15)
hbox_temp.pack_start(label, False, False, 2)
self.sources["FREQ"] = Gtk.Entry()
self.sources["FREQ"].set_width_chars(15)
hbox_temp.pack_start(self.sources["FREQ"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# BAND
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["BAND"], halign=Gtk.Align.START)
label.set_alignment(0, 0.5)
label.set_width_chars(15)
hbox_temp.pack_start(label, False, False, 2)
bands = ["", "2190m", "560m", "160m", "80m", "60m", "40m", "30m", "20m", "17m", "15m", "12m", "10m", "6m", "4m", "2m", "1.25m", "70cm", "33cm", "23cm", "13cm", "9cm", "6cm", "3cm", "1.25cm", "6mm", "4mm", "2.5mm", "2mm", "1mm"]
self.sources["BAND"] = Gtk.ComboBoxText()
for band in bands:
self.sources["BAND"].append_text(band)
self.sources["BAND"].set_active(0) # Set an empty string as the default option.
hbox_temp.pack_start(self.sources["BAND"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# MODE
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["MODE"])
label.set_alignment(0, 0.5)
label.set_width_chars(15)
hbox_temp.pack_start(label, False, False, 2)
modes = ["", "AM", "AMTORFEC", "ASCI", "ATV", "CHIP64", "CHIP128", "CLO", "CONTESTI", "CW", "DSTAR", "DOMINO", "DOMINOF", "FAX", "FM", "FMHELL", "FSK31", "FSK441", "GTOR", "HELL", "HELL80", "HFSK", "ISCAT", "JT44", "JT4A", "JT4B", "JT4C", "JT4D", "JT4E", "JT4F", "JT4G", "JT65", "JT65A", "JT65B", "JT65C", "JT6M", "MFSK8", "MFSK16", "MT63", "OLIVIA", "PAC", "PAC2", "PAC3", "PAX", "PAX2", "PCW", "PKT", "PSK10", "PSK31", "PSK63", "PSK63F", "PSK125", "PSKAM10", "PSKAM31", "PSKAM50", "PSKFEC31", "PSKHELL", "Q15", "QPSK31", "QPSK63", "QPSK125", "ROS", "RTTY", "RTTYM", "SSB", "SSTV", "THRB", "THOR", "THRBX", "TOR", "V4", "VOI", "WINMOR", "WSPR"]
self.sources["MODE"] = Gtk.ComboBoxText()
for mode in modes:
self.sources["MODE"].append_text(mode)
self.sources["MODE"].set_active(0) # Set an empty string as the default option.
hbox_temp.pack_start(self.sources["MODE"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# POWER
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["TX_PWR"], halign=Gtk.Align.START)
label.set_alignment(0, 0.5)
label.set_width_chars(15)
hbox_temp.pack_start(label, False, False, 2)
self.sources["TX_PWR"] = Gtk.Entry()
self.sources["TX_PWR"].set_width_chars(15)
hbox_temp.pack_start(self.sources["TX_PWR"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
vbox_inner = Gtk.VBox(spacing=2)
hbox_inner.pack_start(Gtk.SeparatorToolItem(), False, False, 0)
hbox_inner.pack_start(vbox_inner, True, True, 2)
# RST_SENT
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["RST_SENT"])
label.set_alignment(0, 0.5)
label.set_width_chars(15)
hbox_temp.pack_start(label, False, False, 2)
self.sources["RST_SENT"] = Gtk.Entry()
self.sources["RST_SENT"].set_width_chars(15)
hbox_temp.pack_start(self.sources["RST_SENT"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# RST_RCVD
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["RST_RCVD"])
label.set_alignment(0, 0.5)
label.set_width_chars(15)
hbox_temp.pack_start(label, False, False, 2)
self.sources["RST_RCVD"] = Gtk.Entry()
self.sources["RST_RCVD"].set_width_chars(15)
hbox_temp.pack_start(self.sources["RST_RCVD"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# QSL_SENT
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["QSL_SENT"])
label.set_alignment(0, 0.5)
label.set_width_chars(15)
hbox_temp.pack_start(label, False, False, 2)
qsl_options = ["", "Y", "N", "R", "I"]
self.sources["QSL_SENT"] = Gtk.ComboBoxText()
for option in qsl_options:
self.sources["QSL_SENT"].append_text(option)
self.sources["QSL_SENT"].set_active(0) # Set an empty string as the default option.
hbox_temp.pack_start(self.sources["QSL_SENT"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# QSL_RCVD
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["QSL_RCVD"])
label.set_alignment(0, 0.5)
label.set_width_chars(15)
hbox_temp.pack_start(label, False, False, 2)
qsl_options = ["", "Y", "N", "R", "I"]
self.sources["QSL_RCVD"] = Gtk.ComboBoxText()
for option in qsl_options:
self.sources["QSL_RCVD"].append_text(option)
self.sources["QSL_RCVD"].set_active(0) # Set an empty string as the default option.
hbox_temp.pack_start(self.sources["QSL_RCVD"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# NOTES
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["NOTES"])
label.set_alignment(0, 0.5)
label.set_width_chars(15)
hbox_temp.pack_start(label, False, False, 2)
self.textview = Gtk.TextView()
sw = Gtk.ScrolledWindow()
sw.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
sw.add(self.textview)
self.sources["NOTES"] = self.textview.get_buffer()
hbox_temp.pack_start(sw, True, True, 2)
vbox_inner.pack_start(hbox_temp, True, True, 2)
qso_frame.add(hbox_inner)
from pyqso.adif import *
from pyqso.callsign_lookup import *
from pyqso.auxiliary_dialogs import *
from pyqso.calendar_dialog import CalendarDialog
## STATION INFORMATION FRAME
station_frame = Gtk.Frame()
station_frame.set_label("Station Information")
self.vbox.add(station_frame)
class RecordDialog:
hbox_inner = Gtk.HBox(spacing=2)
""" A dialog through which users can enter information about a QSO/record. """
vbox_inner = Gtk.VBox(spacing=2)
hbox_inner.pack_start(vbox_inner, True, True, 2)
def __init__(self, application, log, index=None):
""" Set up the layout of the record dialog, populate the various fields with the QSO details (if the record already exists), and show the dialog to the user.
# NAME
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["NAME"], halign=Gtk.Align.START)
label.set_width_chars(15)
label.set_alignment(0, 0.5)
hbox_temp.pack_start(label, False, False, 2)
self.sources["NAME"] = Gtk.Entry()
self.sources["NAME"].set_width_chars(15)
hbox_temp.pack_start(self.sources["NAME"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
:arg application: The PyQSO application containing the main Gtk window, etc.
:arg log: The log to which the record belongs (or will belong).
:arg int index: If specified, then the dialog turns into 'edit record mode' and fills the data sources (e.g. the Gtk.Entry boxes) with the existing data in the log. If not specified (i.e. index is None), then the dialog starts off with nothing in the data sources.
"""
# ADDRESS
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["ADDRESS"], halign=Gtk.Align.START)
label.set_width_chars(15)
label.set_alignment(0, 0.5)
hbox_temp.pack_start(label, False, False, 2)
self.sources["ADDRESS"] = Gtk.Entry()
self.sources["ADDRESS"].set_width_chars(15)
hbox_temp.pack_start(self.sources["ADDRESS"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
logging.debug("Setting up the record dialog...")
# STATE
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["STATE"], halign=Gtk.Align.START)
label.set_width_chars(15)
label.set_alignment(0, 0.5)
hbox_temp.pack_start(label, False, False, 2)
self.sources["STATE"] = Gtk.Entry()
self.sources["STATE"].set_width_chars(15)
hbox_temp.pack_start(self.sources["STATE"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
self.application = application
self.builder = self.application.builder
glade_file_path = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "pyqso.glade")
self.builder.add_objects_from_file(glade_file_path, ("record_dialog",))
self.dialog = self.builder.get_object("record_dialog")
self.builder.get_object("record_dialog").connect("key-press-event", self.on_key_press)
# COUNTRY
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["COUNTRY"], halign=Gtk.Align.START)
label.set_width_chars(15)
label.set_alignment(0, 0.5)
hbox_temp.pack_start(label, False, False, 2)
self.sources["COUNTRY"] = Gtk.Entry()
self.sources["COUNTRY"].set_width_chars(15)
hbox_temp.pack_start(self.sources["COUNTRY"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# Set dialog title
if(index is not None):
self.dialog.set_title("Edit Record %d" % index)
else:
self.dialog.set_title("Add Record")
vbox_inner = Gtk.VBox(spacing=2)
hbox_inner.pack_start(Gtk.SeparatorToolItem(), False, False, 0)
hbox_inner.pack_start(vbox_inner, True, True, 2)
# Check if a configuration file is present, since we might need it to set up the rest of the dialog.
config = configparser.ConfigParser()
have_config = (config.read(expanduser('~/.config/pyqso/preferences.ini')) != [])
# DXCC
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["DXCC"], halign=Gtk.Align.START)
label.set_width_chars(15)
label.set_alignment(0, 0.5)
hbox_temp.pack_start(label, False, False, 2)
self.sources["DXCC"] = Gtk.Entry()
self.sources["DXCC"].set_width_chars(15)
hbox_temp.pack_start(self.sources["DXCC"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# Create label:entry pairs and store them in a dictionary
self.sources = {}
# CQZ
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["CQZ"], halign=Gtk.Align.START)
label.set_width_chars(15)
label.set_alignment(0, 0.5)
hbox_temp.pack_start(label, False, False, 2)
self.sources["CQZ"] = Gtk.Entry()
self.sources["CQZ"].set_width_chars(15)
hbox_temp.pack_start(self.sources["CQZ"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# QSO INFORMATION
# ITUZ
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["ITUZ"], halign=Gtk.Align.START)
label.set_width_chars(15)
label.set_alignment(0, 0.5)
hbox_temp.pack_start(label, False, False, 2)
self.sources["ITUZ"] = Gtk.Entry()
self.sources["ITUZ"].set_width_chars(15)
hbox_temp.pack_start(self.sources["ITUZ"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# CALL
self.sources["CALL"] = self.builder.get_object("qso_call_entry")
self.builder.get_object("callsign_lookup").connect("clicked", self.callsign_lookup_callback)
# IOTA
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label(AVAILABLE_FIELD_NAMES_FRIENDLY["IOTA"], halign=Gtk.Align.START)
label.set_width_chars(15)
label.set_alignment(0, 0.5)
hbox_temp.pack_start(label, False, False, 2)
self.sources["IOTA"] = Gtk.Entry()
self.sources["IOTA"].set_width_chars(15)
hbox_temp.pack_start(self.sources["IOTA"], False, False, 2)
vbox_inner.pack_start(hbox_temp, False, False, 2)
# DATE
self.sources["QSO_DATE"] = self.builder.get_object("qso_date_entry")
self.builder.get_object("select_date").connect("clicked", self.calendar_callback)
station_frame.add(hbox_inner)
# TIME
self.sources["TIME_ON"] = self.builder.get_object("qso_time_entry")
self.builder.get_object("current_datetime").connect("clicked", self.set_current_datetime_callback)
if(index is not None):
# The record already exists, so display its current data in the input boxes.
record = log.get_record_by_index(index)
field_names = AVAILABLE_FIELD_NAMES_ORDERED
for i in range(0, len(field_names)):
data = record[field_names[i].lower()]
if(data is None):
data = ""
if(field_names[i] == "BAND"):
self.sources[field_names[i]].set_active(bands.index(data))
elif(field_names[i] == "MODE"):
self.sources[field_names[i]].set_active(modes.index(data))
elif(field_names[i] == "QSL_SENT" or field_names[i] == "QSL_RCVD"):
self.sources[field_names[i]].set_active(qsl_options.index(data))
elif(field_names[i] == "NOTES"):
# Remember to put the new line escape characters back in when displaying the data in a Gtk.TextView
text = data.replace("\\n", "\n")
self.sources[field_names[i]].set_text(text)
# FREQ
self.sources["FREQ"] = self.builder.get_object("qso_frequency_entry")
(section, option) = ("records", "default_frequency_unit")
if(have_config and config.has_option(section, option)):
self.frequency_unit = config.get(section, option)
self.builder.get_object("qso_frequency_label").set_label("Frequency (%s)" % self.frequency_unit)
else:
self.frequency_unit = "MHz"
# BAND
self.sources["BAND"] = self.builder.get_object("qso_band_combo")
for band in BANDS:
self.sources["BAND"].append_text(band)
self.sources["BAND"].set_active(0) # Set an empty string as the default option.
# MODE
self.sources["MODE"] = self.builder.get_object("qso_mode_combo")
for mode in sorted(MODES.keys()):
self.sources["MODE"].append_text(mode)
self.sources["MODE"].set_active(0) # Set an empty string as the default option.
self.sources["MODE"].connect("changed", self.on_mode_changed)
# SUBMODE
self.sources["SUBMODE"] = self.builder.get_object("qso_submode_combo")
self.sources["SUBMODE"].append_text("")
self.sources["SUBMODE"].set_active(0) # Set an empty string initially. As soon as the user selects a particular MODE, the available SUBMODES will appear.
# PROP_MODE
self.sources["PROP_MODE"] = self.builder.get_object("qso_propagation_mode_combo")
for propagation_mode in PROPAGATION_MODES:
self.sources["PROP_MODE"].append_text(propagation_mode)
self.sources["PROP_MODE"].set_active(0) # Set an empty string as the default option.
# POWER
self.sources["TX_PWR"] = self.builder.get_object("qso_power_entry")
# RST_SENT
self.sources["RST_SENT"] = self.builder.get_object("qso_rst_sent_entry")
# RST_RCVD
self.sources["RST_RCVD"] = self.builder.get_object("qso_rst_received_entry")
# QSL_SENT
self.sources["QSL_SENT"] = self.builder.get_object("qso_qsl_sent_combo")
qsl_sent_options = ["", "Y", "N", "R", "Q", "I"]
for option in qsl_sent_options:
self.sources["QSL_SENT"].append_text(option)
self.sources["QSL_SENT"].set_active(0) # Set an empty string as the default option.
# QSL_RCVD
self.sources["QSL_RCVD"] = self.builder.get_object("qso_qsl_received_combo")
qsl_rcvd_options = ["", "Y", "N", "R", "I", "V"]
for option in qsl_rcvd_options:
self.sources["QSL_RCVD"].append_text(option)
self.sources["QSL_RCVD"].set_active(0) # Set an empty string as the default option.
# NOTES
self.sources["NOTES"] = self.builder.get_object("qso_notes_textview").get_buffer()
# STATION INFORMATION
# NAME
self.sources["NAME"] = self.builder.get_object("station_name_entry")
# ADDRESS
self.sources["ADDRESS"] = self.builder.get_object("station_address_entry")
# STATE
self.sources["STATE"] = self.builder.get_object("station_state_entry")
# COUNTRY
self.sources["COUNTRY"] = self.builder.get_object("station_country_entry")
# DXCC
self.sources["DXCC"] = self.builder.get_object("station_dxcc_entry")
# CQZ
self.sources["CQZ"] = self.builder.get_object("station_cq_entry")
# ITUZ
self.sources["ITUZ"] = self.builder.get_object("station_itu_entry")
# IOTA
self.sources["IOTA"] = self.builder.get_object("station_iota_entry")
# GRIDSQUARE
self.sources["GRIDSQUARE"] = self.builder.get_object("station_gridsquare_entry")
# SATELLITE INFORMATION
# SAT_NAME
self.sources["SAT_NAME"] = self.builder.get_object("satellite_name_entry")
# SAT_MODE
self.sources["SAT_MODE"] = self.builder.get_object("satellite_mode_entry")
# Populate various fields, if possible.
if(index is not None):
# The record already exists, so display its current data in the input boxes.
record = log.get_record_by_index(index)
field_names = AVAILABLE_FIELD_NAMES_ORDERED
for i in range(0, len(field_names)):
data = record[field_names[i].lower()]
if(data is None):
data = ""
if(field_names[i] == "BAND"):
self.sources[field_names[i]].set_active(BANDS.index(data))
elif(field_names[i] == "FREQ" and self.frequency_unit != "MHz"):
converted = self.convert_frequency(data, from_unit="MHz", to_unit=self.frequency_unit)
self.sources[field_names[i]].set_text(str(converted))
elif(field_names[i] == "MODE"):
self.sources[field_names[i]].set_active(sorted(MODES.keys()).index(data))
# Handle SUBMODE at the same time.
submode_data = record["submode"]
if(submode_data is None):
submode_data = ""
self.sources["SUBMODE"].set_active(MODES[data].index(submode_data))
elif(field_names[i] == "SUBMODE"):
# Skip, because this has been (or will be) handled when populating the MODE field.
continue
elif(field_names[i] == "PROP_MODE"):
self.sources[field_names[i]].set_active(PROPAGATION_MODES.index(data))
elif(field_names[i] == "QSL_SENT"):
self.sources[field_names[i]].set_active(qsl_sent_options.index(data))
elif(field_names[i] == "QSL_RCVD"):
self.sources[field_names[i]].set_active(qsl_rcvd_options.index(data))
else:
self.sources[field_names[i]].set_text(data)
else:
# Automatically fill in the current date and time
self.set_current_datetime_callback()
# Set up default field values
# Mode
(section, option) = ("records", "default_mode")
if(have_config and config.has_option(section, option)):
mode = config.get(section, option)
else:
self.sources[field_names[i]].set_text(data)
else:
# Automatically fill in the current date and time
dt = datetime.now()
(year, month, day) = (dt.year, dt.month, dt.day)
(hour, minute) = (dt.hour, dt.minute)
# If necessary, add on leading zeros so the YYYYMMDD and HHMM format is followed.
if(month < 10):
month = "0" + str(month) # Note: Unlike the calendar widget, the months start from an index of 1 here.
if(day < 10):
day = "0" + str(day)
if(hour < 10):
hour = "0" + str(hour)
if(minute < 10):
minute = "0" + str(minute)
date = str(year) + str(month) + str(day)
time = str(hour) + str(minute)
self.sources["QSO_DATE"].set_text(date)
self.sources["TIME_ON"].set_text(time)
mode = ""
self.sources["MODE"].set_active(sorted(MODES.keys()).index(mode))
if(have_hamlib):
# If the Hamlib module is present, then use it to fill in the Frequency field if desired.
config = ConfigParser.ConfigParser()
have_config = (config.read(expanduser('~/.pyqso.ini')) != [])
if(have_config):
autofill = (config.get("hamlib", "autofill") == "True")
rig_model = config.get("hamlib", "rig_model")
rig_pathname = config.get("hamlib", "rig_pathname")
if(autofill):
# Use Hamlib (if available) to get the frequency
try:
Hamlib.rig_set_debug(Hamlib.RIG_DEBUG_NONE)
rig = Hamlib.Rig(Hamlib.__dict__[rig_model]) # Look up the model's numerical index in Hamlib's symbol dictionary
rig.set_conf("rig_pathname", rig_pathname)
rig.open()
frequency = "%.6f" % (rig.get_freq()/1.0e6) # Converting to MHz here
self.sources["FREQ"].set_text(frequency)
rig.close()
except:
logging.error("Could not obtain Frequency data via Hamlib!")
# Submode
(section, option) = ("records", "default_submode")
if(have_config and config.has_option(section, option)):
submode = config.get(section, option)
else:
submode = ""
self.sources["SUBMODE"].set_active(MODES[mode].index(submode))
self.show_all()
# Power
(section, option) = ("records", "default_power")
if(have_config and config.has_option(section, option)):
power = config.get(section, option)
else:
power = ""
self.sources["TX_PWR"].set_text(power)
logging.debug("Record dialog ready!")
# If the Hamlib module is present, then use it to fill in various fields if desired.
if(have_hamlib):
if(have_config and config.has_option("hamlib", "autofill") and config.has_option("hamlib", "rig_model") and config.has_option("hamlib", "rig_pathname")):
autofill = (config.getboolean("hamlib", "autofill"))
rig_model = config.get("hamlib", "rig_model")
rig_pathname = config.get("hamlib", "rig_pathname")
if(autofill):
self.hamlib_autofill(rig_model, rig_pathname)
return
# Do we want PyQSO to autocomplete the Band field based on the Frequency field?
(section, option) = ("records", "autocomplete_band")
if(have_config and config.has_option(section, option)):
autocomplete_band = (config.getboolean(section, option))
if(autocomplete_band):
self.sources["FREQ"].connect("changed", self.autocomplete_band)
else:
# If no configuration file exists, autocomplete the Band field by default.
self.sources["FREQ"].connect("changed", self.autocomplete_band)
def get_data(self, field_name):
""" Return the data for a specified field (with name 'field_name') from the Gtk.Entry/Gtk.ComboBoxText/etc boxes in the record dialog. """
logging.debug("Retrieving the data in field %s from the record dialog..." % field_name)
if(field_name == "BAND" or field_name == "MODE" or field_name == "QSL_SENT" or field_name == "QSL_RCVD"):
return self.sources[field_name].get_active_text()
elif(field_name == "NOTES"):
(start, end) = self.sources[field_name].get_bounds()
text = self.sources[field_name].get_text(start, end, True)
# Replace the escape characters with a slightly different new line marker.
# If we don't do this, the rows in the Gtk.TreeView expand based on the number of new lines.
text = text.replace("\n", "\\n")
return text
else:
return self.sources[field_name].get_text()
self.dialog.show_all()
def lookup_callback(self, widget=None):
""" Get the callsign-related data from the qrz.com database and store it in the relevant Gtk.Entry boxes, but return None. """
callsign_lookup = CallsignLookup(parent = self)
logging.debug("Record dialog ready!")
config = ConfigParser.ConfigParser()
have_config = (config.read(expanduser('~/.pyqso.ini')) != [])
if(have_config):
username = config.get("general", "qrz_username")
password = base64.b64decode(config.get("general", "qrz_password"))
if(username == "" or password == ""):
return
def get_data(self, field_name):
""" Return the data for a specified field from the Gtk.Entry/Gtk.ComboBoxText/etc boxes in the record dialog.
:arg str field_name: The name of the field containing the desired data.
:returns: The data in the specified field.
:rtype: str
"""
logging.debug("Retrieving the data in field %s from the record dialog..." % field_name)
if(field_name == "CALL"):
# Always show the callsigns in upper case.
return self.sources[field_name].get_text().upper()
elif(field_name == "FREQ" and self.frequency_unit != "MHz"):
converted = self.convert_frequency(self.sources[field_name].get_text(), from_unit=self.frequency_unit, to_unit="MHz")
return str(converted)
elif(field_name == "MODE"):
return self.sources["MODE"].get_active_text()
elif(field_name == "SUBMODE"):
return self.sources["SUBMODE"].get_active_text()
elif(field_name == "PROP_MODE"):
return self.sources["PROP_MODE"].get_active_text()
elif(field_name == "BAND" or field_name == "QSL_SENT" or field_name == "QSL_RCVD"):
return self.sources[field_name].get_active_text()
elif(field_name == "NOTES"):
(start, end) = self.sources[field_name].get_bounds()
text = self.sources[field_name].get_text(start, end, True)
return text
else:
return self.sources[field_name].get_text()
def on_mode_changed(self, combo):
""" If the MODE field has changed its value, then fill the SUBMODE field with all the available SUBMODE options for that new MODE. """
self.sources["SUBMODE"].get_model().clear()
mode = combo.get_active_text()
for submode in MODES[mode]:
self.sources["SUBMODE"].append_text(submode)
self.sources["SUBMODE"].set_active(MODES[mode].index("")) # Set the submode to an empty string.
return
def on_key_press(self, widget, event):
""" If the Return key is pressed, emit the "OK" response to record the QSO. """
child = widget.get_focus()
if(not(isinstance(child, Gtk.ToggleButton) or isinstance(child, Gtk.Button) or isinstance(child, Gtk.TextView)) and event.keyval == Gdk.KEY_Return):
self.dialog.emit('response', Gtk.ResponseType.OK)
return
def autocomplete_band(self, widget=None):
""" If a value for the Frequency is entered, this function autocompletes the Band field. """
frequency = self.sources["FREQ"].get_text()
# Check whether we actually have a (valid) value to use. If not, set the BAND field to an empty string ("").
try:
frequency = float(frequency)
except ValueError:
self.sources["BAND"].set_active(0)
return
# Convert to MHz if necessary.
if(self.frequency_unit != "MHz"):
frequency = self.convert_frequency(frequency, from_unit=self.frequency_unit, to_unit="MHz")
# Find which band the frequency lies in.
for i in range(1, len(BANDS)):
if(frequency >= BANDS_RANGES[i][0] and frequency <= BANDS_RANGES[i][1]):
self.sources["BAND"].set_active(i)
return
self.sources["BAND"].set_active(0) # If we've reached this, then the frequency does not lie in any of the specified bands.
return
def hamlib_autofill(self, rig_model, rig_pathname):
""" Set the various fields using data from the radio via Hamlib.
:arg str rig_model: The model of the radio/rig.
:arg str rig_pathname: The path to the rig (or rig control device).
"""
# Open a communication channel to the radio.
try:
Hamlib.rig_set_debug(Hamlib.RIG_DEBUG_NONE)
rig = Hamlib.Rig(Hamlib.__dict__[rig_model]) # Look up the model's numerical index in Hamlib's symbol dictionary.
rig.set_conf("rig_pathname", rig_pathname)
rig.open()
except:
logging.error("Could not open a communication channel to the rig via Hamlib!")
return
# Frequency
try:
frequency = "%.6f" % (rig.get_freq()/1.0e6) # Converting to MHz here.
# Convert to the desired unit, if necessary.
if(self.frequency_unit != "MHz"):
frequency = str(self.convert_frequency(frequency, from_unit="MHz", to_unit=self.frequency_unit))
self.sources["FREQ"].set_text(frequency)
except:
logging.error("Could not obtain the current frequency via Hamlib!")
# Mode
try:
(mode, width) = rig.get_mode()
mode = Hamlib.rig_strrmode(mode).upper()
# Handle USB and LSB as special cases.
if(mode == "USB" or mode == "LSB"):
submode = mode
mode = "SSB"
self.sources["MODE"].set_active(sorted(MODES.keys()).index(mode))
self.sources["SUBMODE"].set_active(MODES[mode].index(submode))
else:
self.sources["MODE"].set_active(sorted(MODES.keys()).index(mode))
except:
logging.error("Could not obtain the current mode (e.g. FM, AM, CW) via Hamlib!")
# Close communication channel.
try:
rig.close()
except:
logging.error("Could not close the communication channel to the rig via Hamlib!")
return
def callsign_lookup_callback(self, widget=None):
""" Get the callsign-related data from an online database and store it in the relevant Gtk.Entry boxes, but return None. """
# Get the database name.
config = configparser.ConfigParser()
have_config = (config.read(expanduser('~/.config/pyqso/preferences.ini')) != [])
try:
if(have_config and config.has_option("records", "callsign_database")):
database = config.get("records", "callsign_database")
if(database == ""):
raise ValueError
else:
raise ValueError
except ValueError:
error(parent=self.dialog, message="To perform a callsign lookup, please specify the name of the callsign database in the Preferences.")
return
try:
if(database == "qrz.com"):
# QRZ.com
callsign_lookup = CallsignLookupQRZ(parent=self.dialog)
elif(database == "hamqth.com"):
# HamQTH.com
callsign_lookup = CallsignLookupHamQTH(parent=self.dialog)
else:
raise ValueError("Unknown callsign database: %s" % database)
except ValueError as e:
logging.exception(e)
error(parent=self.dialog, message=e)
return
# Get username and password from configuration file.
if(have_config and config.has_option("records", "callsign_database_username") and config.has_option("records", "callsign_database_password")):
username = config.get("records", "callsign_database_username")
password = base64.b64decode(config.get("records", "callsign_database_password")).decode("utf-8")
if(not username or not password):
details_given = False
else:
details_given = True
else:
details_given = False
else:
details_given = True
else:
details_given = False
if(not details_given):
error(parent=self, message="To perform a callsign lookup, please specify your qrz.com username and password in the Preferences.")
return
if(not details_given):
error(parent=self.dialog, message="To perform a callsign lookup, please specify your username and password in the Preferences.")
return
connected = callsign_lookup.connect(username, password)
if(connected):
fields_and_data = callsign_lookup.lookup(self.sources["CALL"].get_text())
for field_name in fields_and_data.keys():
self.sources[field_name].set_text(fields_and_data[field_name])
return
# Get the callsign from the CALL field.
full_callsign = self.sources["CALL"].get_text()
if(not full_callsign):
# Empty callsign field.
error(parent=self.dialog, message="Please enter a callsign to lookup.")
return
def calendar_callback(self, widget):
""" Open up a calendar widget for easy QSO_DATE selection. Return None after the user destroys the dialog. """
calendar = CalendarDialog(parent = self)
response = calendar.run()
if(response == Gtk.ResponseType.OK):
date = calendar.get_date()
self.sources["QSO_DATE"].set_text(date)
calendar.destroy()
return
# Connect to the database.
connected = callsign_lookup.connect(username, password)
if(connected):
# Check whether we want to ignore any prefixes (e.g. "IA/") or suffixes "(e.g. "/M") in the callsign
# before performing the lookup.
if(have_config and config.has_option("records", "ignore_prefix_suffix")):
ignore_prefix_suffix = (config.getboolean("records", "ignore_prefix_suffix"))
else:
ignore_prefix_suffix = True
class CalendarDialog(Gtk.Dialog):
""" A simple dialog containing a Gtk.Calendar widget. Using this ensures the date is in the correct YYYYMMDD format required by ADIF. """
def __init__(self, parent):
logging.debug("Setting up a calendar dialog...")
Gtk.Dialog.__init__(self, title="Select Date", parent=parent, flags=Gtk.DialogFlags.DESTROY_WITH_PARENT, buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK))
self.calendar = Gtk.Calendar()
self.vbox.add(self.calendar)
self.show_all()
logging.debug("Calendar dialog ready!")
return
# Perform the lookup.
fields_and_data = callsign_lookup.lookup(full_callsign, ignore_prefix_suffix=ignore_prefix_suffix)
for field_name in list(fields_and_data.keys()):
self.sources[field_name].set_text(fields_and_data[field_name])
return
def get_date(self):
""" Return the date from the Gtk.Calendar widget in YYYYMMDD format. """
logging.debug("Retrieving the date from the calendar widget...")
(year, month, day) = self.calendar.get_date()
# If necessary, add on leading zeros so the YYYYMMDD format is followed.
if(month + 1 < 10):
month = "0" + str(month + 1) # Note: the months start from an index of 0 when retrieved from the calendar widget.
else:
month = month + 1
if(day < 10):
day = "0" + str(day)
date = str(year) + str(month) + str(day)
return date
def calendar_callback(self, widget):
""" Open up a calendar widget for easy QSO_DATE selection. Return None after the user destroys the dialog. """
c = CalendarDialog(self.application)
response = c.dialog.run()
if(response == Gtk.ResponseType.OK):
self.sources["QSO_DATE"].set_text(c.date)
c.dialog.destroy()
return
def set_current_datetime_callback(self, widget=None):
""" Insert the current date and time. """
# Check if a configuration file is present.
config = configparser.ConfigParser()
have_config = (config.read(expanduser('~/.config/pyqso/preferences.ini')) != [])
# Do we want to use UTC or the computer's local time?
(section, option) = ("records", "use_utc")
if(have_config and config.has_option(section, option)):
use_utc = (config.getboolean(section, option))
if(use_utc):
dt = datetime.utcnow()
else:
dt = datetime.now()
else:
dt = datetime.utcnow() # Use UTC by default, since this is expected by ADIF.
self.sources["QSO_DATE"].set_text(dt.strftime("%Y%m%d"))
self.sources["TIME_ON"].set_text(dt.strftime("%H%M"))
return
def convert_frequency(self, frequency, from_unit, to_unit):
""" Convert a frequency from one unit to another.
:arg float frequency: The frequency to convert.
:arg str from_unit: The current unit of the frequency.
:arg str to_unit: The desired unit of the frequency.
:rtype: float
:returns: The frequency in the to_unit.
"""
scaling = {"Hz": 1, "kHz": 1e3, "MHz": 1e6, "GHz": 1e9}
# Check that the from/to frequency units are valid.
try:
if(from_unit not in scaling.keys()):
raise ValueError("Unknown frequency unit '%s' in from_unit" % from_unit)
if(to_unit not in scaling.keys()):
raise ValueError("Unknown frequency unit '%s' in to_unit" % to_unit)
except ValueError as e:
logging.exception(e)
return frequency
# Cast to float before scaling.
if(not isinstance(frequency, float)):
try:
if(frequency == "" or frequency is None):
return frequency
else:
frequency = float(frequency)
except(ValueError, TypeError):
logging.exception("Could not convert frequency to a floating-point value.")
return frequency
# Do not bother scaling if the units are the same.
if(from_unit == to_unit):
return frequency
coefficient = scaling[from_unit]/scaling[to_unit]
return float("%.6f" % (coefficient*frequency))

Wyświetl plik

Przed

Szerokość:  |  Wysokość:  |  Rozmiar: 667 B

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 667 B

Wyświetl plik

Przed

Szerokość:  |  Wysokość:  |  Rozmiar: 47 KiB

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 47 KiB

Wyświetl plik

Przed

Szerokość:  |  Wysokość:  |  Rozmiar: 6.8 KiB

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 6.8 KiB

4849
pyqso/res/pyqso.glade 100644

Plik diff jest za duży Load Diff

238
pyqso/summary.py 100644
Wyświetl plik

@ -0,0 +1,238 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk
import logging
from os.path import basename, getmtime, expanduser, dirname, join, realpath
from datetime import datetime, date
try:
import configparser
except ImportError:
import ConfigParser as configparser
try:
import matplotlib
matplotlib.use('Agg')
matplotlib.rcParams['font.size'] = 10.0
from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.dates import DateFormatter, MonthLocator
have_matplotlib = True
except ImportError as e:
logging.warning(e)
logging.warning("Could not import matplotlib, so you will not be able to plot annual logbook statistics. Check that all the PyQSO dependencies are satisfied.")
have_matplotlib = False
class Summary(object):
def __init__(self, application):
""" Create a summary page containing various statistics such as the number of logs in the logbook, the logbook's modification date, etc.
:arg application: The PyQSO application containing the main Gtk window, etc.
"""
self.application = application
self.logbook = self.application.logbook
self.builder = self.application.builder
glade_file_path = join(realpath(dirname(__file__)), "res", "pyqso.glade")
self.builder.add_objects_from_file(glade_file_path, ("summary_page",))
self.summary_page = self.builder.get_object("summary_page")
self.items = {}
# Database name in large font at the top of the summary page
self.builder.get_object("database_name").set_markup("<span size=\"x-large\">%s</span>" % basename(self.logbook.path))
self.items["LOG_COUNT"] = self.builder.get_object("log_count")
self.items["QSO_COUNT"] = self.builder.get_object("qso_count")
self.items["DATE_MODIFIED"] = self.builder.get_object("date_modified")
# Yearly statistics
config = configparser.ConfigParser()
have_config = (config.read(expanduser('~/.config/pyqso/preferences.ini')) != [])
(section, option) = ("general", "show_yearly_statistics")
if(have_config and config.has_option(section, option)):
if(config.getboolean("general", "show_yearly_statistics") and have_matplotlib):
hbox = Gtk.HBox()
label = Gtk.Label(label="Display statistics for year: ", halign=Gtk.Align.START)
hbox.pack_start(label, False, False, 6)
year_select = Gtk.ComboBoxText()
min_year, max_year = self.get_year_bounds()
if min_year and max_year:
for year in range(max_year, min_year-1, -1):
year_select.append_text(str(year))
year_select.append_text("")
year_select.connect("changed", self.on_year_changed)
hbox.pack_start(year_select, False, False, 6)
self.summary_page.pack_start(hbox, False, False, 4)
self.items["YEARLY_STATISTICS"] = Figure()
canvas = FigureCanvas(self.items["YEARLY_STATISTICS"])
canvas.set_size_request(800, 175)
canvas.show()
self.summary_page.pack_start(canvas, True, True, 0)
# Summary tab label and icon.
tab = Gtk.HBox(homogeneous=False, spacing=0)
label = Gtk.Label(label="Summary ")
icon = Gtk.Image.new_from_icon_name(Gtk.STOCK_INDEX, Gtk.IconSize.MENU)
tab.pack_start(label, False, False, 0)
tab.pack_start(icon, False, False, 0)
tab.show_all()
self.logbook.notebook.insert_page(self.summary_page, tab, 0) # Append as a new tab
self.logbook.notebook.show_all()
return
def on_year_changed(self, combo):
""" Re-plot the statistics for the year selected by the user. """
# Clear figure
self.items["YEARLY_STATISTICS"].clf()
self.items["YEARLY_STATISTICS"].canvas.draw()
# Get year to show statistics for.
year = combo.get_active_text()
try:
year = int(year)
except ValueError:
# Empty year string.
return
# Number of contacts made each month
contact_count_plot = self.items["YEARLY_STATISTICS"].add_subplot(121)
contact_count = self.get_annual_contact_count(year)
# x-axis formatting based on the date
contact_count_plot.bar(list(contact_count.keys()), list(contact_count.values()), color="k", width=15, align="center")
formatter = DateFormatter("%b")
contact_count_plot.xaxis.set_major_formatter(formatter)
month_locator = MonthLocator()
contact_count_plot.xaxis.set_major_locator(month_locator)
contact_count_plot.set_ylabel("Number of QSOs")
# Set x-axis upper limit based on the current month.
contact_count_plot.xaxis_date()
contact_count_plot.set_xlim([date(year-1, 12, 16), date(year, 12, 15)]) # Make a bit of space either side of January and December of the selected year.
# Pie chart of all the modes used.
mode_count_plot = self.items["YEARLY_STATISTICS"].add_subplot(122)
mode_count = self.get_annual_mode_count(year)
(patches, texts, autotexts) = mode_count_plot.pie(list(mode_count.values()), labels=mode_count.keys(), autopct='%1.1f%%', shadow=False)
for p in patches:
# Make the patches partially transparent.
p.set_alpha(0.75)
mode_count_plot.set_title("Modes used")
self.items["YEARLY_STATISTICS"].canvas.draw()
return
def get_year_bounds(self):
""" Find the years of the oldest and newest QSOs across all logs in the logbook.
:returns: The years of the oldest and newest QSOs. The tuple (None, None) is returned if no QSOs have been made or no QSO dates have been specified.
:rtype: tuple
"""
c = self.logbook.connection.cursor()
max_years = []
min_years = []
for log in self.logbook.logs:
query = "SELECT min(QSO_DATE), max(QSO_DATE) FROM %s" % (log.name)
c.execute(query)
years = c.fetchone()
if years[0] and years[1]:
min_years.append(int(years[0][:4]))
max_years.append(int(years[1][:4]))
if len(min_years) == 0 or len(max_years) == 0:
return None, None
else:
# Return the min and max across all logs.
return min(min_years), max(max_years)
def get_annual_contact_count(self, year):
""" Find the total number of contacts made in each month in the specified year.
:arg int year: The year of interest.
:returns: The total number of contacts made in each month of a given year.
:rtype: dict
"""
contact_count = {}
c = self.logbook.connection.cursor()
for log in self.logbook.logs:
query = "SELECT QSO_DATE, count(QSO_DATE) FROM %s WHERE QSO_DATE >= %d0101 AND QSO_DATE < %d0101 GROUP by QSO_DATE" % (log.name, year, year+1)
c.execute(query)
xy = c.fetchall()
for i in range(len(xy)):
date_str = xy[i][0]
y = int(date_str[0:4])
m = int(date_str[4:6])
date = datetime(y, m, 1) # Collect all contacts together by month.
if date in contact_count.keys():
contact_count[date] += xy[i][1]
else:
contact_count[date] = xy[i][1]
return contact_count
def get_annual_mode_count(self, year):
""" Find the total number of contacts made with each mode in a specified year.
:arg int year: The year of interest.
:returns: The total number of contacts made with each mode in a given year.
:rtype: dict
"""
mode_count = {}
for log in self.logbook.logs:
query = "SELECT MODE, count(MODE) FROM %s WHERE QSO_DATE >= %d0101 AND QSO_DATE < %d0101 GROUP by MODE" % (log.name, year, year+1)
c = self.logbook.connection.cursor()
c.execute(query)
xy = c.fetchall()
for i in range(len(xy)):
mode = xy[i][0]
if mode == "":
mode = "Unspecified"
# Add to running total
if mode in mode_count.keys():
mode_count[mode] += xy[i][1]
else:
mode_count[mode] = xy[i][1]
return mode_count
def update(self):
""" Update the information presented on the summary page. """
self.items["LOG_COUNT"].set_label(str(self.logbook.log_count))
self.items["QSO_COUNT"].set_label(str(self.logbook.record_count))
try:
t = datetime.fromtimestamp(getmtime(self.logbook.path)).strftime("%d %B %Y @ %H:%M")
self.items["DATE_MODIFIED"].set_label(str(t))
except (IOError, OSError) as e:
logging.exception(e)
return

Wyświetl plik

@ -1,7 +1,6 @@
#!/usr/bin/env python
# File: telnet_connection_dialog.py
#!/usr/bin/env python3
# Copyright (C) 2013 Christian Jacobs.
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
@ -18,67 +17,74 @@
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk, GObject
import logging
import re
import calendar
class TelnetConnectionDialog(Gtk.Dialog):
""" A simple dialog through which users can specify host and login information for a Telnet server.
This can be used to connect to DX clusters. """
def __init__(self, parent):
logging.debug("Setting up the Telnet connection dialog...")
Gtk.Dialog.__init__(self, title="New Telnet Connection", parent=parent, flags=Gtk.DialogFlags.DESTROY_WITH_PARENT, buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK))
self.sources = {}
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label("Host: ", halign=Gtk.Align.START)
label.set_width_chars(12)
label.set_alignment(0, 0.5)
hbox_temp.pack_start(label, False, False, 6)
self.sources["HOST"] = Gtk.Entry()
hbox_temp.pack_start(self.sources["HOST"], True, True, 6)
self.vbox.pack_start(hbox_temp, False, False, 6)
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label("Port: ", halign=Gtk.Align.START)
label.set_width_chars(12)
label.set_alignment(0, 0.5)
hbox_temp.pack_start(label, False, False, 6)
self.sources["PORT"] = Gtk.Entry()
hbox_temp.pack_start(self.sources["PORT"], True, True, 6)
self.vbox.pack_start(hbox_temp, False, False, 6)
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label("Username: ", halign=Gtk.Align.START)
label.set_width_chars(12)
label.set_alignment(0, 0.5)
hbox_temp.pack_start(label, False, False, 6)
self.sources["USERNAME"] = Gtk.Entry()
hbox_temp.pack_start(self.sources["USERNAME"], True, True, 6)
self.vbox.pack_start(hbox_temp, False, False, 6)
hbox_temp = Gtk.HBox(spacing=0)
label = Gtk.Label("Password: ", halign=Gtk.Align.START)
label.set_width_chars(12)
label.set_alignment(0, 0.5)
hbox_temp.pack_start(label, False, False, 6)
self.sources["PASSWORD"] = Gtk.Entry()
self.sources["PASSWORD"].set_visibility(False) # Mask the password with the "*" character.
hbox_temp.pack_start(self.sources["PASSWORD"], True, True, 6)
self.vbox.pack_start(hbox_temp, False, False, 6)
logging.debug("Telnet connection dialog ready!")
self.show_all()
return
def get_connection_info(self):
""" Return the host and login information stored in the Gtk.Entry boxes. """
logging.debug("Returning Telnet connection information...")
return self.sources
import os
class TelnetConnectionDialog:
""" A handler for the Gtk.Dialog through which a user can specify Telnet connection details. """
def __init__(self, application):
""" Create and show the Telnet connection dialog to the user.
:arg application: The PyQSO application containing the main Gtk window, etc.
"""
self.builder = application.builder
glade_file_path = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "pyqso.glade")
self.builder.add_objects_from_file(glade_file_path, ("telnet_connection_dialog",))
self.dialog = self.builder.get_object("telnet_connection_dialog")
self.sources = {"HOST": self.builder.get_object("host_entry"),
"PORT": self.builder.get_object("port_entry"),
"USERNAME": self.builder.get_object("username_entry"),
"PASSWORD": self.builder.get_object("password_entry"),
"BOOKMARK": self.builder.get_object("bookmark_checkbox")}
self.dialog.show_all()
return
@property
def host(self):
""" Return the Telnet server's host name.
:returns: The server's host name.
:rtype: str
"""
return self.sources["HOST"].get_text()
@property
def port(self):
""" Return the Telnet server's port number (as a string).
:returns: The server's port number (as a string).
:rtype: str
"""
return self.sources["PORT"].get_text()
@property
def username(self):
""" Return the user's username.
:returns: The user's username.
:rtype: str
"""
return self.sources["USERNAME"].get_text()
@property
def password(self):
""" Return the user's password.
:returns: The user's password.
:rtype: str
"""
return self.sources["PASSWORD"].get_text()
@property
def bookmark(self):
""" Return True if a new bookmark should be created, otherwise return False.
:returns: True if a new bookmark should be created, otherwise False.
:rtype: bool
"""
return self.sources["BOOKMARK"].get_active()

Wyświetl plik

@ -1,7 +1,6 @@
#!/usr/bin/env python
# File: toolbar.py
#!/usr/bin/env python3
# Copyright (C) 2013 Christian Jacobs.
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
@ -18,102 +17,72 @@
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk, GObject
import logging
class Toolbar(Gtk.HBox):
def __init__(self, parent):
logging.debug("Setting up the toolbar...")
Gtk.HBox.__init__(self, spacing=2)
class Toolbar:
self.buttons = {}
""" The toolbar underneath the menu bar. """
# Create/open logbook
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_OPEN, Gtk.IconSize.BUTTON)
button = Gtk.Button()
button.add(icon)
button.set_tooltip_text('Open New or Existing Logbook')
button.connect("clicked", parent.logbook.open)
self.pack_start(button, False, False, 0)
self.buttons["OPEN_LOGBOOK"] = button
def __init__(self, application):
""" Set up the various buttons in the toolbar, and connect to their corresponding functions.
# Close logbook
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_CLOSE, Gtk.IconSize.BUTTON)
button = Gtk.Button()
button.add(icon)
button.set_tooltip_text('Close Logbook')
button.connect("clicked", parent.logbook.close)
self.pack_start(button, False, False, 0)
self.buttons["CLOSE_LOGBOOK"] = button
:arg application: The PyQSO application containing the main Gtk window, etc.
"""
self.pack_start(Gtk.SeparatorToolItem(), False, False, 0)
self.application = application
self.builder = self.application.builder
# Add record
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_ADD, Gtk.IconSize.BUTTON)
button = Gtk.Button()
button.add(icon)
button.set_tooltip_text('Add Record')
button.connect("clicked", parent.logbook.add_record_callback)
self.pack_start(button, False, False, 0)
self.buttons["ADD_RECORD"] = button
self.buttons = {}
# Edit record
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_EDIT, Gtk.IconSize.BUTTON)
button = Gtk.Button()
button.add(icon)
button.set_tooltip_text('Edit Record')
button.connect("clicked", parent.logbook.edit_record_callback, None, None)
self.pack_start(button, False, False, 0)
self.buttons["EDIT_RECORD"] = button
# Create logbook
self.buttons["NEW_LOGBOOK"] = self.builder.get_object("toolbar_new_logbook")
self.buttons["NEW_LOGBOOK"].connect("clicked", self.application.logbook.new)
# Delete record
icon = Gtk.Image()
icon.set_from_stock(Gtk.STOCK_DELETE, Gtk.IconSize.BUTTON)
button = Gtk.Button()
button.add(icon)
button.set_tooltip_text('Delete Record')
button.connect("clicked", parent.logbook.delete_record_callback)
self.pack_start(button, False, False, 0)
self.buttons["DELETE_RECORD"] = button
# Open logbook
self.buttons["OPEN_LOGBOOK"] = self.builder.get_object("toolbar_open_logbook")
self.buttons["OPEN_LOGBOOK"].connect("clicked", self.application.logbook.open)
self.pack_start(Gtk.SeparatorToolItem(), False, False, 0)
# Close logbook
self.buttons["CLOSE_LOGBOOK"] = self.builder.get_object("toolbar_close_logbook")
self.buttons["CLOSE_LOGBOOK"].connect("clicked", self.application.logbook.close)
# Filter log
label = Gtk.Label("Filter by callsign: ")
self.pack_start(label, False, False, 0)
self.filter_source = Gtk.Entry()
self.filter_source.set_width_chars(11)
self.filter_source.connect_after("changed", parent.logbook.filter_logs)
self.pack_start(self.filter_source, False, False, 0)
# Add record
self.buttons["ADD_RECORD"] = self.builder.get_object("toolbar_add_record")
self.buttons["ADD_RECORD"].connect("clicked", self.application.logbook.add_record_callback)
self.set_logbook_button_sensitive(True)
self.set_record_buttons_sensitive(False)
# Edit record
self.buttons["EDIT_RECORD"] = self.builder.get_object("toolbar_edit_record")
self.buttons["EDIT_RECORD"].connect("clicked", self.application.logbook.edit_record_callback)
self.filter_source.set_sensitive(False)
# Delete record
self.buttons["DELETE_RECORD"] = self.builder.get_object("toolbar_delete_record")
self.buttons["DELETE_RECORD"].connect("clicked", self.application.logbook.delete_record_callback)
logging.debug("Toolbar ready!")
# Filter log
self.filter_source = self.builder.get_object("filter_source")
self.filter_source.connect_after("changed", self.application.logbook.filter_logs)
return
# Set sensitivities.
self.set_logbook_button_sensitive(True)
self.set_record_buttons_sensitive(False)
self.filter_source.set_sensitive(False)
def set_logbook_button_sensitive(self, sensitive):
logging.debug("Setting the 'Create/Open Logbook' toolbar item's sensitivity to: %s..." % sensitive)
self.buttons["OPEN_LOGBOOK"].set_sensitive(sensitive)
self.buttons["CLOSE_LOGBOOK"].set_sensitive(not sensitive)
logging.debug("Set the 'Create/Open Logbook' toolbar item's sensitivity to: %s." % sensitive)
return
return
def set_record_buttons_sensitive(self, sensitive):
logging.debug("Setting record-related menu item sensitivity to: %s..." % sensitive)
for button_name in ["ADD_RECORD", "EDIT_RECORD", "DELETE_RECORD"]:
self.buttons[button_name].set_sensitive(sensitive)
logging.debug("Set record-related menu item sensitivity to: %s." % sensitive)
return
def set_logbook_button_sensitive(self, sensitive):
""" Enable/disable logbook-related toolbar items.
:arg bool sensitive: If True, enable the 'new logbook' and 'open logbook' toolbar items. If False, disable them.
"""
self.buttons["NEW_LOGBOOK"].set_sensitive(sensitive)
self.buttons["OPEN_LOGBOOK"].set_sensitive(sensitive)
self.buttons["CLOSE_LOGBOOK"].set_sensitive(not sensitive)
return
def set_record_buttons_sensitive(self, sensitive):
""" Enable/disable record-related toolbar items.
:arg bool sensitive: If True, enable all the record-related toolbar items. If False, disable them all.
"""
for button_name in ["ADD_RECORD", "EDIT_RECORD", "DELETE_RECORD"]:
self.buttons[button_name].set_sensitive(sensitive)
return

Wyświetl plik

@ -1,7 +1,6 @@
#!/usr/bin/env python
# File: toolbox.py
#!/usr/bin/env python3
# Copyright (C) 2013 Christian Jacobs.
# Copyright (C) 2013-2018 Christian Thomas Jacobs.
# This file is part of PyQSO.
@ -18,47 +17,42 @@
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk, GObject
import logging
from pyqso.dx_cluster import DXCluster
from pyqso.world_map import WorldMap
from pyqso.awards import Awards
from pyqso.dx_cluster import *
from pyqso.grey_line import *
from pyqso.awards import *
class Toolbox(Gtk.Frame):
""" Contains a Gtk.Notebook full of amateur radio-related tools. """
class Toolbox:
def __init__(self, parent):
logging.debug("Setting up the toolbox...")
Gtk.Frame.__init__(self)
self.set_label("Toolbox")
self.parent = parent
""" Contains a Gtk.Notebook full of amateur radio-related tools. """
self.tools = Gtk.Notebook()
def __init__(self, application):
""" Instantiate and insert the various tools into the toolbox.
self.dx_cluster = DXCluster(self.parent)
self.tools.insert_page(self.dx_cluster, Gtk.Label("DX Cluster"), 0)
self.grey_line = GreyLine(self.parent)
self.tools.insert_page(self.grey_line, Gtk.Label("Grey Line"), 1)
self.awards = Awards(self.parent)
self.tools.insert_page(self.awards, Gtk.Label("Awards"), 2)
:arg application: The PyQSO application containing the main Gtk window, etc.
"""
self.add(self.tools)
self.tools.connect_after("switch-page", self._on_switch_page)
self.application = application
self.builder = self.application.builder
logging.debug("Toolbox ready!")
self.tools = self.builder.get_object("tools")
return
self.dx_cluster = DXCluster(self.application)
self.world_map = WorldMap(self.application)
self.awards = Awards(self.application)
def toggle_visible_callback(self, widget=None):
""" Show/hide the toolbox. """
self.set_visible(not self.get_visible())
return
self.tools.connect_after("switch-page", self.on_switch_page)
def _on_switch_page(self, widget, label, new_page):
""" Re-draw the Grey Line if the user switches to the grey line tab. """
if(type(label) == GreyLine):
label.draw() # Note that 'label' is actually a GreyLine object.
return
return
def toggle_visible_callback(self, widget=None):
""" Show/hide the toolbox. """
toolbox_frame = self.builder.get_object("toolbox")
toolbox_frame.set_visible(not toolbox_frame.get_visible())
return
def on_switch_page(self, widget, label, new_page):
""" Re-draw the WorldMap if the user switches to the World Map tab. """
if(widget.get_tab_label(label).get_text() == "World Map"):
self.world_map.draw()
return

Plik binarny nie jest wyświetlany.

361
pyqso/world_map.py 100644
Wyświetl plik

@ -0,0 +1,361 @@
#!/usr/bin/env python3
# Copyright (C) 2013-2018 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import GObject
import logging
import sqlite3 as sqlite
import re
from os.path import expanduser
from datetime import datetime
try:
import configparser
except ImportError:
import ConfigParser as configparser
try:
import numpy
logging.info("Using version %s of numpy." % (numpy.__version__))
import matplotlib
logging.info("Using version %s of matplotlib." % (matplotlib.__version__))
import cartopy
logging.info("Using version %s of cartopy." % (cartopy.__version__))
from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo as FigureCanvas
from matplotlib.backends.backend_gtk3 import NavigationToolbar2GTK3
have_necessary_modules = True
except ImportError as e:
logging.warning(e)
logging.warning("Could not import a non-standard Python module needed by the WorldMap class, or the version of the non-standard module is too old. Check that all the PyQSO dependencies are satisfied.")
have_necessary_modules = False
try:
import geocoder
have_geocoder = True
except ImportError:
logging.warning("Could not import the geocoder module!")
have_geocoder = False
if(have_necessary_modules):
class NavigationToolbar(NavigationToolbar2GTK3):
""" Navigation tools for the World Map. """
# Only include a subset of the tools.
toolitems = [t for t in NavigationToolbar2GTK3.toolitems if t[0] in ("Home", "Zoom", "Save")]
class Point:
""" A point on the grey line map. """
def __init__(self, name, latitude, longitude, style="yo"):
""" Set up the point's attributes.
:arg str name: The name that identifies the point.
:arg float latitude: The latitude of the point on the map.
:arg float longitude: The longitude of the point on the map.
:arg str style: The style of the point when plotted. By default it is a filled yellow circle.
"""
self.name = name
self.latitude = latitude
self.longitude = longitude
self.style = style
return
class Maidenhead:
""" The Maidenhead Locator System. """
def __init__(self):
self.upper = "ABCDEFGHIJKLMNOPQR"
self.lower = "abcdefghijklmnopqrstuvwx"
return
def ll2gs(self, latitude, longitude, subsquare=False):
""" Convert latitude-longitude coordinates to a Maidenhead grid square locator.
This is based on the code by Walter Underwood, K6WRU (https://ham.stackexchange.com/questions/221/how-can-one-convert-from-lat-long-to-grid-square).
:arg float latitude: The latitude.
:arg float longitude: The longitude.
:arg bool subsquare: Option to include the subsquare (thereby obtaining a 6-character Maidenhead locator).
:rtype: str
:returns: The Maidenhead grid square locator.
"""
adjusted_latitude = latitude + 90
adjusted_longitude = longitude + 180
field_latitude = self.upper[int(adjusted_latitude/10)]
field_longitude = self.upper[int(adjusted_longitude/20)]
square_latitude = int(adjusted_latitude % 10)
square_longitude = int((adjusted_longitude/2) % 10)
if(subsquare):
adjusted_latitude_remainder = (adjusted_latitude - int(adjusted_latitude)) * 60
adjusted_longitude_remainder = ((adjusted_longitude) - int(adjusted_longitude/2)*2) * 60
subsquare_latitude = self.lower[int(adjusted_latitude_remainder/2.5)]
subsquare_longitude = self.lower[int(adjusted_longitude_remainder/5)]
return ("%s"*6) % (field_longitude, field_latitude, square_longitude, square_latitude, subsquare_longitude, subsquare_latitude)
else:
return ("%s"*4) % (field_longitude, field_latitude, square_longitude, square_latitude)
def gs2ll(self, grid_square):
""" Convert a Maidenhead grid square locator to latitude-longitude coordinates.
This is based on the gridSquareToLatLon function in HamGridSquare.js by Paul Brewer, KI6CQ (https://gist.github.com/DrPaulBrewer/4279e9d234a1bd6dd3c0), released under the MIT license.
:arg str grid_square: The Maidenhead grid square locator.
:rtype: tuple
:returns: The latitude-longitude coordinates in a tuple.
"""
m = re.match(r"^[A-X][A-X][0-9][0-9]$", grid_square)
if(m):
gs = m.group(0)
latitude = self.latitude4(gs)+0.5
longitude = self.longitude4(gs)+1.0
else:
m = re.match(r"^[A-X][A-X][0-9][0-9][a-x][a-x]$", grid_square)
if(m):
gs = m.group(0)
latitude = self.latitude4(gs) + (1.0/60.0)*2.5*(ord(gs[5])-ord("a")+0.5)
longitude = self.longitude4(gs) + (1.0/60.0)*5*(ord(gs[4])-ord("a")+0.5)
else:
raise ValueError("Unable to parse grid square string.")
return (latitude, longitude)
def latitude4(self, g):
return 10*(ord(g[1]) - ord("A")) + int(g[3])-90
def longitude4(self, g):
return 20*(ord(g[0]) - ord("A")) + 2*int(g[2])-180
class WorldMap:
""" A tool for visualising the world map. """
def __init__(self, application):
""" Set up the drawing canvas and the timer which will re-plot the world map every 30 minutes.
:arg application: The PyQSO application containing the main Gtk window, etc.
"""
logging.debug("Setting up the world map...")
self.application = application
self.builder = self.application.builder
self.points = []
if(have_necessary_modules):
self.fig = matplotlib.figure.Figure()
self.canvas = FigureCanvas(self.fig) # For embedding in the Gtk application
self.builder.get_object("world_map").pack_start(self.canvas, True, True, 0)
toolbar = NavigationToolbar(self.canvas, self.application.window)
self.builder.get_object("world_map").pack_start(toolbar, False, False, 0)
self.refresh_event = GObject.timeout_add(1800000, self.draw) # Re-draw the world map automatically after 30 minutes (if the world map tool is visible).
# Add the QTH coordinates for plotting, if available.
config = configparser.ConfigParser()
have_config = (config.read(expanduser('~/.config/pyqso/preferences.ini')) != [])
(section, option) = ("world_map", "show_qth")
if(have_config and config.has_option(section, option)):
if(config.getboolean(section, option)):
try:
qth_name = config.get("world_map", "qth_name")
qth_latitude = float(config.get("world_map", "qth_latitude"))
qth_longitude = float(config.get("world_map", "qth_longitude"))
self.add_point(qth_name, qth_latitude, qth_longitude, "ro")
except ValueError:
logging.warning("Unable to get the QTH name, latitude and/or longitude. The QTH will not be pinpointed on the world map. Check preferences?")
# Maidenhead grid squares.
self.maidenhead = Maidenhead()
self.show_grid_squares = False
self.shade_worked_grid_squares = False
(section, option) = ("world_map", "show_grid_squares")
if(have_config and config.has_option(section, option)):
self.show_grid_squares = config.getboolean(section, option)
(section, option) = ("world_map", "shade_worked_grid_squares")
if(have_config and config.has_option(section, option)):
self.shade_worked_grid_squares = config.getboolean(section, option)
self.builder.get_object("world_map").show_all()
logging.debug("World map ready!")
return
def add_point(self, name, latitude, longitude, style="yo"):
""" Add a point and re-draw the map.
:arg str name: The name that identifies the point.
:arg float latitude: The latitude of the point on the map.
:arg float longitude: The longitude of the point on the map.
:arg str style: The style of the point when plotted. By default it is a filled yellow circle.
"""
p = Point(name, latitude, longitude, style)
self.points.append(p)
self.draw()
return
def pinpoint(self, r):
""" Pinpoint the location of a QSO on the world map.
:arg r: The QSO record containing the location to pinpoint.
"""
if(have_geocoder):
callsign = r["CALL"]
gridsquare = r["GRIDSQUARE"]
country = r["COUNTRY"]
# Get the latitude-longitude coordinates. Use any GRIDSQUARE information first since this is likely to be more accurate than the COUNTRY field.
if(gridsquare):
try:
latitude, longitude = self.maidenhead.gs2ll(gridsquare)
logging.debug("QTH coordinates found: (%s, %s)", str(latitude), str(longitude))
self.add_point(callsign, latitude, longitude)
return
except ValueError:
logging.exception("Unable to lookup QTH coordinates.")
if(country):
try:
g = geocoder.google(country)
latitude, longitude = g.latlng
logging.debug("QTH coordinates found: (%s, %s)", str(latitude), str(longitude))
self.add_point(callsign, latitude, longitude)
return
except ValueError:
logging.exception("Unable to lookup QTH coordinates.")
except Exception:
logging.exception("Unable to lookup QTH coordinates. Check connection to the internets? Lookup limit reached?")
return
def get_worked_grid_squares(self, logbook):
""" Get the array of worked grid squares.
:arg logbook: The logbook containing logs which in turn contain QSOs.
:returns: A two-dimensional array of boolean values showing which grid squares have been worked.
:rtype: numpy.array
"""
worked_grid_squares = numpy.zeros((len(self.maidenhead.upper), len(self.maidenhead.upper)), dtype=bool)
for log in logbook.logs:
try:
records = log.records
for r in records:
if(r["GRIDSQUARE"]):
grid_square = r["GRIDSQUARE"][0:2].upper() # Only consider the field value (e.g. IO).
worked_grid_squares[self.maidenhead.upper.index(grid_square[1]), self.maidenhead.upper.index(grid_square[0])] = True
except sqlite.Error as e:
logging.error("Could not update the array of worked grid squares for log '%s' because of a database error." % log.name)
logging.exception(e)
return worked_grid_squares
def draw(self):
""" Draw the world map and the grey line on top of it.
:returns: Always returns True to satisfy the GObject timer, unless the necessary WorldMap dependencies are not satisfied (in which case, the method returns False so as to not re-draw the canvas).
:rtype: bool
"""
if(have_necessary_modules):
toolbox = self.builder.get_object("toolbox")
tools = self.builder.get_object("tools")
if(tools.get_current_page() != 1 or not toolbox.get_visible()):
# Don't re-draw if the world map is not visible.
return True # We need to return True in case this is method was called by a timer event.
else:
# Set up the world map.
logging.debug("Drawing the world map...")
self.fig.clf()
ax = self.fig.add_subplot(111, projection=cartopy.crs.PlateCarree())
ax.set_extent([-180, 180, -90, 90])
ax.set_aspect("auto")
gl = ax.gridlines(draw_labels=True)
gl.xlabels_top = False
gl.ylabels_right = False
gl.xformatter = cartopy.mpl.gridliner.LONGITUDE_FORMATTER
gl.yformatter = cartopy.mpl.gridliner.LATITUDE_FORMATTER
ax.add_feature(cartopy.feature.LAND, facecolor="olivedrab")
ax.add_feature(cartopy.feature.OCEAN, facecolor="cornflowerblue")
ax.add_feature(cartopy.feature.COASTLINE)
ax.add_feature(cartopy.feature.BORDERS, alpha=0.4)
# Draw the grey line. This is based on the code from the Cartopy Aurora Forecast example (http://scitools.org.uk/cartopy/docs/latest/gallery/aurora_forecast.html) and used under the Open Government Licence (http://scitools.org.uk/cartopy/docs/v0.15/copyright.html).
logging.debug("Drawing the grey line...")
dt = datetime.utcnow()
axial_tilt = 23.5
reference_solstice = datetime(2016, 6, 21, 22, 22)
days_per_year = 365.2425
seconds_per_day = 86400.0
days_since_reference = (dt - reference_solstice).total_seconds()/seconds_per_day
latitude = axial_tilt*numpy.cos(2*numpy.pi*days_since_reference/days_per_year)
seconds_since_midnight = (dt - datetime(dt.year, dt.month, dt.day)).seconds
longitude = -(seconds_since_midnight/seconds_per_day - 0.5)*360
pole_longitude = longitude
if latitude > 0:
pole_latitude = -90 + latitude
central_rotated_longitude = 180
else:
pole_latitude = 90 + latitude
central_rotated_longitude = 0
rotated_pole = cartopy.crs.RotatedPole(pole_latitude=pole_latitude, pole_longitude=pole_longitude, central_rotated_longitude=central_rotated_longitude)
x = numpy.empty(360)
y = numpy.empty(360)
x[:180] = -90
y[:180] = numpy.arange(-90, 90.)
x[180:] = 90
y[180:] = numpy.arange(90, -90., -1)
ax.fill(x, y, transform=rotated_pole, color="black", alpha=0.5)
# Plot points on the map.
if(self.points):
logging.debug("Plotting QTHs on the map...")
for p in self.points:
ax.plot(p.longitude, p.latitude, p.style, transform=cartopy.crs.PlateCarree())
projected_x, projected_y = ax.projection.transform_point(p.longitude, p.latitude, src_crs=cartopy.crs.PlateCarree())
ax.annotate(p.name, xy=(projected_x, projected_y), xytext=(0, 2.5), textcoords="offset points", color="white", size="small", weight="bold")
# Draw Maidenhead grid squares and shade in the worked squares.
x = numpy.linspace(-180, 180, len(list(self.maidenhead.upper))+1)
y = numpy.linspace(-90, 90, len(list(self.maidenhead.upper))+1)
if(self.show_grid_squares):
if(self.shade_worked_grid_squares):
worked_grid_squares = self.get_worked_grid_squares(self.application.logbook)
masked = numpy.ma.masked_array(worked_grid_squares, worked_grid_squares == 0)
else:
z = numpy.zeros((len(self.maidenhead.upper), len(self.maidenhead.upper)), dtype=bool)
masked = numpy.ma.masked_array(z, z == 0)
ax.pcolormesh(x, y, masked, transform=cartopy.crs.PlateCarree(), cmap="Reds", vmin=0, vmax=1, edgecolors="k", linewidth=1.5, alpha=0.4)
# Grid square labels.
for i in range(len(self.maidenhead.upper)):
for j in range(len(self.maidenhead.upper)):
text = self.maidenhead.upper[i]+self.maidenhead.upper[j]
ax.text((x[i]+x[i+1])/2.0, (y[j]+y[j+1])/2.0, text, ha="center", va="center", size="small", color="w", family="monospace", alpha=0.4)
return True
else:
return False # Don't try to re-draw the canvas if the necessary modules to do so could not be imported.

6
requirements.txt 100644
Wyświetl plik

@ -0,0 +1,6 @@
numpy
matplotlib>=1.3.0
cairocffi
cartopy>=0.16.0
sphinx
geocoder

Wyświetl plik

@ -1,7 +1,6 @@
#!/usr/bin/env python
# File: setup.py
#!/usr/bin/env python3
# Copyright (C) 2013 Christian Jacobs.
# Copyright (C) 2013-2018 Christian Thomas Jacobs.
# This file is part of PyQSO.
@ -18,16 +17,25 @@
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from distutils.core import setup
from setuptools import setup
setup(name='PyQSO',
version='0.1',
description='A contact logging tool for amateur radio operators.',
author='Christian Jacobs',
url='https://github.com/ctjacobs/pyqso',
packages=['pyqso'],
package_dir = {'pyqso': 'pyqso'},
setup(name="PyQSO",
version="1.1.0",
description="A contact logging tool for amateur radio operators.",
author="Christian Thomas Jacobs",
author_email="christian@christianjacobs.uk",
url="https://github.com/ctjacobs/pyqso",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
"Natural Language :: English",
"Programming Language :: Python :: 3",
"Topic :: Communications :: Ham Radio",
],
packages=["pyqso"],
package_dir={"pyqso": "pyqso"},
package_data={"pyqso": ["res/pyqso.glade", "res/log_64x64.png"]},
scripts=["bin/pyqso"],
data_files=[("icons", ["icons/log_64x64.png"])]
)
zip_safe=False
)

Wyświetl plik

@ -0,0 +1,4 @@
Some test ADI data.<eoh>
<call:4>TEST<band:3>40m<mode:2>CW
<qso_date:8:d>20130322<time_on:4>1955<eor>

Wyświetl plik

@ -0,0 +1,2 @@
Some test ADI data.<eoh>
<call:64>ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ<eor>

Wyświetl plik

@ -0,0 +1,2 @@
Some test ADI data.<eoh>
<call:4>test<eor>

Wyświetl plik

@ -0,0 +1 @@
Some test ADI data.<eoh>

Wyświetl plik

@ -0,0 +1,9 @@
Some test ADI data.<eoh>
<call:4>TEST<band:3>40m<mode:2>CW
<qso_date:8:d>20130322<time_on:4>1955<eor>
<call:8>TEST2ABC<band:3>20m<mode:3>SSB
<qso_date:8>20150227<time_on:4>0820<eor>
<call:5>HELLO<band:2>2m<mode:2>FM<qso_date:8:d>20150227<time_on:4>0832<eor>

Wyświetl plik

@ -0,0 +1 @@
<call:4>TEST<band:3>40m<mode:2>CW<qso_date:8:d>20130322<time_on:4>1955<eor>

Wyświetl plik

@ -0,0 +1 @@
This is a plain text file used for testing PyQSO. Trying to open this file in PyQSO should case an error, since it is not a valid database file.

BIN
tests/res/test.db 100644

Plik binarny nie jest wyświetlany.

200
tests/test_adif.py 100644
Wyświetl plik

@ -0,0 +1,200 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
import unittest
import os
from pyqso.adif import *
class TestADIF(unittest.TestCase):
""" The unit tests for the ADIF class. """
def setUp(self):
""" Set up the ADIF object needed for the unit tests. """
self.adif = ADIF()
def test_read(self):
""" Check that a single ADIF record can be read and parsed correctly. """
path = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "ADIF.test_read.adi")
records = self.adif.read(path)
expected_records = [{'TIME_ON': '1955', 'BAND': '40m', 'CALL': 'TEST', 'MODE': 'CW', 'QSO_DATE': '20130322'}]
print("Imported records: ", records)
print("Expected records: ", expected_records)
assert(len(records) == 1)
assert(len(list(records[0].keys())) == len(list(expected_records[0].keys())))
assert(records == expected_records)
def test_read_multiple(self):
""" Check that multiple ADIF records can be read and parsed correctly. """
path = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "ADIF.test_read_multiple.adi")
records = self.adif.read(path)
expected_records = [{'TIME_ON': '1955', 'BAND': '40m', 'CALL': 'TEST', 'MODE': 'CW', 'QSO_DATE': '20130322'}, {'TIME_ON': '0820', 'BAND': '20m', 'CALL': 'TEST2ABC', 'MODE': 'SSB', 'QSO_DATE': '20150227'}, {'TIME_ON': '0832', 'BAND': '2m', 'CALL': 'HELLO', 'MODE': 'FM', 'QSO_DATE': '20150227'}]
print("Imported records: ", records)
print("Expected records: ", expected_records)
assert(len(records) == 3)
for i in range(len(expected_records)):
assert(len(list(records[i].keys())) == len(list(expected_records[i].keys())))
assert(records == expected_records)
def test_read_alphabet(self):
""" Check that none of the letters of the alphabet are ignored during parsing. """
path = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "ADIF.test_read_alphabet.adi")
records = self.adif.read(path)
expected_records = [{'CALL': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'}]
print("Imported records: ", records)
print("Expected records: ", expected_records)
assert(len(records) == 1)
assert(len(list(records[0].keys())) == len(list(expected_records[0].keys())))
assert(records == expected_records)
def test_read_capitalisation(self):
""" Check that the CALL field is capitalised correctly. """
path = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "ADIF.test_read_capitalisation.adi")
records = self.adif.read(path)
expected_records = [{'CALL': 'TEST'}]
print("Imported records: ", records)
print("Expected records: ", expected_records)
assert(len(records) == 1)
assert(len(list(records[0].keys())) == len(list(expected_records[0].keys())))
assert(records == expected_records)
def test_read_header_only(self):
""" Check that no records are read in if the ADIF file only contains header information. """
path = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "ADIF.test_read_header_only.adi")
records = self.adif.read(path)
expected_records = []
print("Imported records: ", records)
print("Expected records: ", expected_records)
assert(len(records) == 0)
assert(records == expected_records)
def test_read_no_header(self):
""" Check that an ADIF file can be parsed with no header information. """
path = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "ADIF.test_read_no_header.adi")
records = self.adif.read(path)
expected_records = [{'TIME_ON': '1955', 'BAND': '40m', 'CALL': 'TEST', 'MODE': 'CW', 'QSO_DATE': '20130322'}]
print("Imported records: ", records)
print("Expected records: ", expected_records)
assert(len(records) == 1)
assert(len(list(records[0].keys())) == len(list(expected_records[0].keys())))
assert(records == expected_records)
def test_write(self):
""" Check that records can be written to an ADIF file correctly. """
records = [{"CALL": "TEST123", "QSO_DATE": "20120402", "TIME_ON": "1234", "FREQ": "145.500", "BAND": "2m", "MODE": "FM", "RST_SENT": "59", "RST_RCVD": "59"},
{"CALL": "TEST123", "QSO_DATE": "20130312", "TIME_ON": "0101", "FREQ": "145.750", "BAND": "2m", "MODE": "FM"}]
self.adif.write(records, "ADIF.test_write.adi")
f = open("ADIF.test_write.adi", 'r')
text = f.read()
print("File 'ADIF.test_write.adi' contains the following text:", text)
assert("""
<adif_ver:5>3.0.4
<programid:5>PyQSO
<programversion:5>1.1.0
<eoh>
<call:7>TEST123
<qso_date:8>20120402
<time_on:4>1234
<freq:7>145.500
<band:2>2m
<mode:2>FM
<rst_sent:2>59
<rst_rcvd:2>59
<eor>
<call:7>TEST123
<qso_date:8>20130312
<time_on:4>0101
<freq:7>145.750
<band:2>2m
<mode:2>FM
<eor>
""" in text) # Ignore the header line here, since it contains the date and time the ADIF file was written, which will change each time 'make unittest' is run.
f.close()
def test_write_sqlite3_Row(self):
""" Check that records can be written to an ADIF file from a test database file. """
import sqlite3
import os.path
path_to_test_database = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "test.db")
self.connection = sqlite3.connect(path_to_test_database)
self.connection.row_factory = sqlite3.Row
c = self.connection.cursor()
c.execute("SELECT * FROM test")
records = c.fetchall()
print(records)
self.adif.write(records, "ADIF.test_write_sqlite3_Row.adi")
f = open("ADIF.test_write_sqlite3_Row.adi", 'r')
text = f.read()
print("File 'ADIF.test_write_sqlite3_Row.adi' contains the following text:", text)
assert("""
<adif_ver:5>3.0.4
<programid:5>PyQSO
<programversion:5>1.1.0
<eoh>
<call:7>TEST123
<qso_date:8>20120402
<time_on:4>1234
<freq:7>145.500
<band:2>2m
<mode:2>FM
<rst_sent:2>59
<rst_rcvd:2>59
<eor>
<call:7>TEST456
<qso_date:8>20130312
<time_on:4>0101
<freq:7>145.750
<band:2>2m
<mode:2>FM
<eor>
""" in text) # Ignore the header line here, since it contains the date and time the ADIF file was written, which will change each time 'make unittest' is run.
f.close()
self.connection.close()
def test_is_valid(self):
""" Check that ADIF field validation is working correctly for different data types. """
assert(self.adif.is_valid("CALL", "TEST123", "S"))
assert(self.adif.is_valid("CALL", "F/MYCALL123MYCALL", "S"))
assert(self.adif.is_valid("QSO_DATE", "20120402", "D"))
assert(not self.adif.is_valid("QSO_DATE", "19000101", "D"))
assert(self.adif.is_valid("TIME_ON", "0000", "T"))
assert(self.adif.is_valid("TIME_ON", "235959", "T"))
assert(self.adif.is_valid("TIME_ON", "1230", "T"))
assert(self.adif.is_valid("TIME_ON", "155329", "T"))
assert(not self.adif.is_valid("TIME_ON", "2500", "T"))
assert(self.adif.is_valid("TX_PWR", "5", "N"))
assert(self.adif.is_valid("FREQ", "145.550", "N"))
assert(self.adif.is_valid("NOTES", "TEST123\nHELLO_WORLD", "M"))
assert(self.adif.is_valid("MODE", "FM", "E"))
assert(self.adif.is_valid("SUBMODE", "LSB", "E"))
if(__name__ == '__main__'):
unittest.main()

Wyświetl plik

@ -0,0 +1,54 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
try:
import unittest.mock as mock
except ImportError:
import mock
from pyqso.awards import *
from pyqso.logbook import Logbook
class TestAwards(unittest.TestCase):
""" The unit tests for the Awards class. """
def setUp(self):
""" Set up the objects needed for the unit tests. """
PyQSO = mock.MagicMock()
self.awards = Awards(application=PyQSO())
self.logbook = Logbook(application=PyQSO())
path_to_test_database = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "test.db")
success = self.logbook.db_connect(path_to_test_database)
assert(success)
self.logbook.logs = self.logbook.get_logs()
assert(self.logbook.logs is not None)
def test_count(self):
""" Check that there are 3 FM/AM/SSB/SSTV QSOs and 1 CW QSO. Note that the BAND must be specified in order to be counted. """
count = self.awards.count(self.logbook)
assert(sum(count[0]) == 3) # FM/AM/SSB/SSTV
assert(sum(count[1]) == 1) # CW
assert(sum(count[2]) == 1) # Other modes
assert(sum(count[3]) == 5) # Mixed
if(__name__ == '__main__'):
unittest.main()

Wyświetl plik

@ -0,0 +1,61 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
import unittest
from pyqso.cabrillo import *
class TestCabrillo(unittest.TestCase):
""" The unit tests for the Cabrillo class. """
def setUp(self):
""" Set up the Cabrillo object needed for the unit tests. """
self.cabrillo = Cabrillo()
return
def test_write(self):
""" Check that QSOs are written correctly in Cabrillo format. """
records = [{'TIME_ON': '1955', 'BAND': '40m', 'CALL': 'TEST', 'FREQ': "145.550", 'MODE': 'FM', 'QSO_DATE': '20130322', 'RST_SENT': '59 001', 'RST_RCVD': '59 002'}, {'TIME_ON': '0820', 'BAND': '20m', 'CALL': 'TEST2ABC', 'FREQ': "144.330", 'MODE': 'SSB', 'QSO_DATE': '20150227', 'RST_SENT': '55 020', 'RST_RCVD': '57 003'}, {'TIME_ON': '0832', 'BAND': '2m', 'CALL': 'HELLO', 'FREQ': "145.550", 'MODE': 'FM', 'QSO_DATE': '20150227', 'RST_SENT': '59 001', 'RST_RCVD': '59 002'}]
expected = """START-OF-LOG: 3.0
CREATED-BY: PyQSO v1.1.0
CALLSIGN: MYCALL
CONTEST: MYCONTEST
QSO: 145550.0 FM 2013-03-22 1955 MYCALL 59 001 TEST 59 002 0
QSO: 144330.0 PH 2015-02-27 0820 MYCALL 55 020 TEST2ABC 57 003 0
QSO: 145550.0 FM 2015-02-27 0832 MYCALL 59 001 HELLO 59 002 0
END-OF-LOG:"""
print("Expected Cabrillo file contents: ", expected)
mycall = "MYCALL"
mycontest = "MYCONTEST"
path = "Cabrillo.test_write.log"
self.cabrillo.write(records, path, contest=mycontest, mycall=mycall)
actual = ""
f = open(path, "r")
for line in f:
actual += line
f.close()
print("Actual Cabrillo file contents: ", actual)
assert(expected == actual)
if(__name__ == '__main__'):
unittest.main()

Wyświetl plik

@ -0,0 +1,45 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk
import unittest
try:
import unittest.mock as mock
except ImportError:
import mock
from pyqso.calendar_dialog import *
class TestCalendarDialog(unittest.TestCase):
""" The unit tests for the CalendarDialog class. """
def setUp(self):
""" Set up the objects needed for the unit tests. """
self.cd = CalendarDialog(application=mock.MagicMock())
self.cd.calendar = Gtk.Calendar()
self.cd.calendar.select_month(3, 2017) # Note: Months start from 0 when using the Calendar widget. So "3" represents April here.
self.cd.calendar.select_day(2)
def test_date(self):
""" Check that the date obtained from the Calendar is in the correct format. """
assert(self.cd.date == "20170402")
if(__name__ == '__main__'):
unittest.main()

Wyświetl plik

@ -0,0 +1,141 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
import unittest
try:
import unittest.mock as mock
except ImportError:
import mock
from pyqso.callsign_lookup import *
class TestCallsignLookup(unittest.TestCase):
""" The unit tests for the callsign lookup functionality. """
def setUp(self):
""" Set up the objects needed for the unit tests. """
self.qrz = CallsignLookupQRZ(parent=None)
self.hamqth = CallsignLookupHamQTH(parent=None)
def test_strip(self):
""" Check that a callsign with a prefix and a suffix is stripped correctly. """
assert strip("F/MYCALL/MM") == "MYCALL"
assert strip("F/MYCALL/M") == "MYCALL"
assert strip("HB9/MYCALL/P") == "MYCALL"
assert strip("HB9/MYCALL/QRP") == "MYCALL"
assert strip("HB9/MYCALL/A") == "MYCALL"
assert strip("HB9/MYCALL/AM") == "MYCALL"
assert strip("HB9/MYCALL/PM") == "MYCALL"
def test_strip_prefix_only(self):
""" Check that a callsign with only a prefix is stripped correctly. """
assert strip("F/MYCALL") == "MYCALL"
def test_strip_suffix_only(self):
""" Check that a callsign with only a suffix is stripped correctly. """
assert strip("MYCALL/M") == "MYCALL"
assert strip("MYCALL/P") == "MYCALL"
assert strip("MYCALL/A") == "MYCALL"
assert strip("MYCALL/MM") == "MYCALL"
assert strip("MYCALL/PM") == "MYCALL"
assert strip("MYCALL/AM") == "MYCALL"
assert strip("MYCALL/QRP") == "MYCALL"
def test_strip_no_prefix_or_suffix(self):
""" Check that a callsign with no prefix or suffix remains unmodified. """
callsign = "MYCALL"
assert strip(callsign) == "MYCALL"
def test_strip_too_many_components(self):
""" Check that a callsign with too many prefix/suffix components remains unmodified. """
callsign = "F/HB9/MYCALL/MM"
assert strip(callsign) == "F/HB9/MYCALL/MM"
def test_qrz_connect(self):
""" Check the example response from the qrz.com server, and make sure the session key has been correctly extracted. """
http_client.HTTPConnection = mock.Mock(spec=http_client.HTTPConnection)
http_client.HTTPResponse = mock.Mock(spec=http_client.HTTPResponse)
connection = http_client.HTTPConnection()
response = http_client.HTTPResponse()
response.read.return_value = b'<?xml version="1.0" encoding="utf-8" ?>\n<QRZDatabase version="1.33" xmlns="http://xmldata.qrz.com">\n<Session>\n<Key>3b1fd1d3ba495189984f93ff67bd45b6</Key>\n<Count>61</Count>\n<SubExp>non-subscriber</SubExp>\n<GMTime>Sun Nov 22 21:25:34 2015</GMTime>\n<Remark>cpu: 0.147s</Remark>\n</Session>\n</QRZDatabase>\n'
connection.getresponse.return_value = response
result = self.qrz.connect("hello", "world")
assert(result)
assert(self.qrz.session_key == "3b1fd1d3ba495189984f93ff67bd45b6")
def test_qrz_lookup(self):
""" Check the example callsign lookup response from the qrz.com server, and make sure the callsign information has been correctly extracted. """
http_client.HTTPConnection = mock.Mock(spec=http_client.HTTPConnection)
http_client.HTTPResponse = mock.Mock(spec=http_client.HTTPResponse)
connection = http_client.HTTPConnection()
response = http_client.HTTPResponse()
response.read.return_value = b'<?xml version="1.0" encoding="utf-8" ?>\n<QRZDatabase version="1.33" xmlns="http://xmldata.qrz.com">\n<Callsign>\n<call>MYCALL</call>\n<fname>FIRSTNAME</fname>\n<name>LASTNAME</name>\n<addr2>ADDRESS2</addr2>\n<country>COUNTRY</country>\n</Callsign>\n<Session>\n<Key>3b1fd1d3ba495189984f93ff67bd45b6</Key>\n<Count>61</Count>\n<SubExp>non-subscriber</SubExp>\n<Message>A subscription is required to access the complete record.</Message>\n<GMTime>Sun Nov 22 21:34:46 2015</GMTime>\n<Remark>cpu: 0.026s</Remark>\n</Session>\n</QRZDatabase>\n'
connection.getresponse.return_value = response
self.qrz.connection = connection
self.qrz.session_key = "3b1fd1d3ba495189984f93ff67bd45b6"
fields_and_data = self.qrz.lookup("MYCALL")
assert(fields_and_data["NAME"] == "FIRSTNAME LASTNAME")
assert(fields_and_data["ADDRESS"] == "ADDRESS2")
assert(fields_and_data["COUNTRY"] == "COUNTRY")
def test_hamqth_connect(self):
""" Check the example response from the hamqth.com server, and make sure the session ID has been correctly extracted. """
http_client.HTTPSConnection = mock.Mock(spec=http_client.HTTPSConnection)
http_client.HTTPResponse = mock.Mock(spec=http_client.HTTPResponse)
connection = http_client.HTTPSConnection()
response = http_client.HTTPResponse()
response.read.return_value = b'<?xml version="1.0"?>\n<HamQTH version="2.6" xmlns="https://www.hamqth.com">\n<session>\n<session_id>09b0ae90050be03c452ad235a1f2915ad684393c</session_id>\n</session>\n</HamQTH>\n'
connection.getresponse.return_value = response
result = self.hamqth.connect("hello", "world")
assert(result)
assert(self.hamqth.session_id == "09b0ae90050be03c452ad235a1f2915ad684393c")
def test_hamqth_lookup(self):
""" Check the example callsign lookup response from the hamqth.com server, and make sure the callsign information has been correctly extracted. """
http_client.HTTPSConnection = mock.Mock(spec=http_client.HTTPSConnection)
http_client.HTTPResponse = mock.Mock(spec=http_client.HTTPResponse)
connection = http_client.HTTPSConnection()
response = http_client.HTTPResponse()
response.read.return_value = b'<?xml version="1.0"?>\n<HamQTH version="2.6" xmlns="https://www.hamqth.com">\n<search>\n<callsign>MYCALL</callsign>\n<nick>NAME</nick>\n<country>COUNTRY</country>\n<itu>ITU</itu>\n<cq>CQ</cq>\n<iota>IOTA</iota>\n<adr_street1>ADDRESS</adr_street1>\n</search>\n</HamQTH>\n'
connection.getresponse.return_value = response
self.hamqth.connection = connection
self.hamqth.session_id = "09b0ae90050be03c452ad235a1f2915ad684393c"
fields_and_data = self.hamqth.lookup("MYCALL")
assert(fields_and_data["NAME"] == "NAME")
assert(fields_and_data["ADDRESS"] == "ADDRESS")
assert(fields_and_data["COUNTRY"] == "COUNTRY")
assert(fields_and_data["CQZ"] == "CQ")
assert(fields_and_data["ITUZ"] == "ITU")
assert(fields_and_data["IOTA"] == "IOTA")
if(__name__ == '__main__'):
unittest.main()

Wyświetl plik

@ -0,0 +1,85 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk
import unittest
from pyqso.compare import *
class TestCompare(unittest.TestCase):
""" The unit tests for the comparison schemes. """
def setUp(self):
""" Set up the objects needed for the unit tests. """
data_types = [int] + [str]*3
self.model = Gtk.ListStore(*data_types)
row1 = [0, "100", "20150323", "1433"]
self.model.append(row1)
row2 = [1, "5000", "20160423", "1432"]
self.model.append(row2)
row3 = [2, "5000", "20160423", "1433"]
self.model.append(row3)
row4 = [3, "25", "20160423", "1433"]
self.model.append(row4)
return
def test_compare_default(self):
""" Check the correctness of the default comparison scheme. """
# Get the row iterables.
path = Gtk.TreePath(0)
iter1 = self.model.get_iter(path)
iter2 = self.model.iter_next(iter1)
iter3 = self.model.iter_next(iter2)
iter4 = self.model.iter_next(iter3)
# Compare values in the second column.
column_index = 1
result = compare_default(self.model, iter1, iter2, column_index)
assert(result == -1)
result = compare_default(self.model, iter2, iter3, column_index)
assert(result == 0)
result = compare_default(self.model, iter3, iter4, column_index)
assert(result == 1)
def test_compare_date_and_time(self):
""" Check that dates in yyyymmdd format are compared correctly. """
# Get the row iterables.
path = Gtk.TreePath(0)
iter1 = self.model.get_iter(path)
iter2 = self.model.iter_next(iter1)
iter3 = self.model.iter_next(iter2)
iter4 = self.model.iter_next(iter3)
# Compare values in the third (and fourth, if necessary) column.
column_index = 2
result = compare_date_and_time(self.model, iter1, iter2, [column_index, column_index+1])
assert(result == -1)
result = compare_date_and_time(self.model, iter2, iter3, [column_index, column_index+1])
assert(result == -1)
result = compare_date_and_time(self.model, iter3, iter4, [column_index, column_index+1])
assert(result == 0)
result = compare_date_and_time(self.model, iter4, iter1, [column_index, column_index+1])
assert(result == 1)
if(__name__ == '__main__'):
unittest.main()

Wyświetl plik

@ -0,0 +1,49 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
import unittest
try:
import unittest.mock as mock
except ImportError:
import mock
from pyqso.dx_cluster import *
class TestDXCluster(unittest.TestCase):
""" The unit tests for the DXCluster class. """
def setUp(self):
""" Set up the objects needed for the unit tests. """
PyQSO = mock.MagicMock()
self.dxcluster = DXCluster(application=PyQSO())
def test_on_telnet_io(self):
""" Check that the response from the Telnet server can be correctly decoded. """
telnetlib.Telnet = mock.Mock(spec=telnetlib.Telnet)
connection = telnetlib.Telnet("hello", "world")
connection.read_very_eager.return_value = b"Test message from the Telnet server."
self.dxcluster.connection = connection
result = self.dxcluster.on_telnet_io()
assert(result)
if(__name__ == '__main__'):
unittest.main()

227
tests/test_log.py 100644
Wyświetl plik

@ -0,0 +1,227 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
import unittest
from pyqso.log import *
class TestLog(unittest.TestCase):
""" The unit tests for the Log class. """
def setUp(self):
""" Create a connection to a temporary database and set up the objects needed for the unit tests. """
self.connection = sqlite.connect(":memory:")
self.connection.row_factory = sqlite.Row
self.field_names = ["CALL", "QSO_DATE", "TIME_ON", "FREQ", "BAND", "MODE", "RST_SENT", "RST_RCVD"]
self.fields_and_data = {"CALL": "TEST123", "QSO_DATE": "20130312", "TIME_ON": "1234", "FREQ": "145.500", "BAND": "2m", "MODE": "FM", "RST_SENT": "59", "RST_RCVD": "59"}
c = self.connection.cursor()
query = "CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT"
for field_name in self.field_names:
s = ", %s TEXT" % field_name.lower()
query = query + s
query = query + ")"
c.execute(query)
self.log = Log(self.connection, "test")
def tearDown(self):
""" Destroy the connection to the temporary database. """
self.connection.close()
def test_add_missing_db_columns(self):
""" Check that any missing columns in the database are added successfully. """
c = self.connection.cursor()
# 'Before' state.
column_names_before = []
c.execute("PRAGMA table_info(test)")
result = c.fetchall()
for t in result:
column_names_before.append(t[1].upper())
# Add missing columns.
self.log.add_missing_db_columns()
# 'After' state.
column_names_after = []
c.execute("PRAGMA table_info(test)")
result = c.fetchall()
for t in result:
column_names_after.append(t[1].upper())
print("Column names before: ", column_names_before)
print("Column names after: ", column_names_after)
assert(len(column_names_before) == len(self.field_names) + 1) # Added 1 here because of the "id" column in all database tables.
assert(len(column_names_after) == len(AVAILABLE_FIELD_NAMES_ORDERED) + 1)
for field_name in AVAILABLE_FIELD_NAMES_ORDERED:
assert(field_name in column_names_after)
def test_add_record(self):
""" Check that a single record can be successfully added. """
self.log.add_record(self.fields_and_data)
c = self.connection.cursor()
c.execute("SELECT * FROM test")
records = c.fetchall()
assert len(records) == 1
# Check that all the data has been added to all the fields.
for field_name in self.field_names:
print(self.fields_and_data[field_name], records[0][field_name])
assert self.fields_and_data[field_name] == records[0][field_name]
# Check consistency of index between Gtk.ListStore and the database.
assert(records[0]["id"] == 1)
iter = self.log.get_iter_first()
row_index = self.log.get_value(iter, 0)
assert(records[0]["id"] == row_index)
def test_add_record_multiple(self):
""" Check that multiple records can be successfully added in one go. """
self.log.add_record([self.fields_and_data]*5)
c = self.connection.cursor()
c.execute("SELECT * FROM test")
records = c.fetchall()
assert len(records) == 5
def test_delete_record(self):
""" Check that a record can be successfully deleted. """
query = "INSERT INTO test VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)"
c = self.connection.cursor()
c.execute(query, (self.fields_and_data["CALL"], self.fields_and_data["QSO_DATE"], self.fields_and_data["TIME_ON"], self.fields_and_data["FREQ"], self.fields_and_data["BAND"], self.fields_and_data["MODE"], self.fields_and_data["RST_SENT"], self.fields_and_data["RST_RCVD"]))
c.execute("SELECT * FROM test")
records_before = c.fetchall()
self.log.delete_record(1)
c.execute("SELECT * FROM test")
records_after = c.fetchall()
assert(len(records_before) == 1)
assert(len(records_after) == 0)
def test_edit_record(self):
""" Check that a record's fields can be successfully edited. """
query = "INSERT INTO test VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)"
c = self.connection.cursor()
c.execute(query, (self.fields_and_data["CALL"], self.fields_and_data["QSO_DATE"], self.fields_and_data["TIME_ON"], self.fields_and_data["FREQ"], self.fields_and_data["BAND"], self.fields_and_data["MODE"], self.fields_and_data["RST_SENT"], self.fields_and_data["RST_RCVD"]))
c.execute("SELECT * FROM test")
record_before = c.fetchall()[0]
self.log.edit_record(1, "CALL", "TEST456")
self.log.edit_record(1, "FREQ", "145.450")
c.execute("SELECT * FROM test")
record_after = c.fetchall()[0]
assert(record_before["CALL"] == "TEST123")
assert(record_after["CALL"] == "TEST456")
assert(record_before["FREQ"] == "145.500")
assert(record_after["FREQ"] == "145.450")
def test_get_record_by_index(self):
""" Check that a record can be retrieved using its index. """
query = "INSERT INTO test VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)"
c = self.connection.cursor()
c.execute(query, (self.fields_and_data["CALL"], self.fields_and_data["QSO_DATE"], self.fields_and_data["TIME_ON"], self.fields_and_data["FREQ"], self.fields_and_data["BAND"], self.fields_and_data["MODE"], self.fields_and_data["RST_SENT"], self.fields_and_data["RST_RCVD"]))
record = self.log.get_record_by_index(1)
print("Contents of retrieved record: ", record)
for field_name in list(record.keys()):
if(field_name.upper() == "ID"):
continue
else:
assert(record[field_name.upper()] == self.fields_and_data[field_name.upper()])
assert(len(record) == len(self.fields_and_data) + 1)
def test_records(self):
""" Check that all records in a log can be successfully retrieved. """
query = "INSERT INTO test VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)"
c = self.connection.cursor()
# Add the same record twice
c.execute(query, (self.fields_and_data["CALL"], self.fields_and_data["QSO_DATE"], self.fields_and_data["TIME_ON"], self.fields_and_data["FREQ"], self.fields_and_data["BAND"], self.fields_and_data["MODE"], self.fields_and_data["RST_SENT"], self.fields_and_data["RST_RCVD"]))
c.execute(query, (self.fields_and_data["CALL"], self.fields_and_data["QSO_DATE"], self.fields_and_data["TIME_ON"], self.fields_and_data["FREQ"], self.fields_and_data["BAND"], self.fields_and_data["MODE"], self.fields_and_data["RST_SENT"], self.fields_and_data["RST_RCVD"]))
records = self.log.records
print("Contents of all retrieved records: ", records)
assert(len(records) == 2) # There should be 2 records
for field_name in self.field_names:
assert(records[0][field_name] == self.fields_and_data[field_name])
assert(records[1][field_name] == self.fields_and_data[field_name])
def test_record_count(self):
""" Check that the total number of records in a log is calculated correctly. """
query = "INSERT INTO test VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)"
c = self.connection.cursor()
# Add the same record twice
c.execute(query, (self.fields_and_data["CALL"], self.fields_and_data["QSO_DATE"], self.fields_and_data["TIME_ON"], self.fields_and_data["FREQ"], self.fields_and_data["BAND"], self.fields_and_data["MODE"], self.fields_and_data["RST_SENT"], self.fields_and_data["RST_RCVD"]))
c.execute(query, (self.fields_and_data["CALL"], self.fields_and_data["QSO_DATE"], self.fields_and_data["TIME_ON"], self.fields_and_data["FREQ"], self.fields_and_data["BAND"], self.fields_and_data["MODE"], self.fields_and_data["RST_SENT"], self.fields_and_data["RST_RCVD"]))
record_count = self.log.record_count
print("Number of records in the log: ", record_count)
assert(record_count == 2) # There should be 2 records
def test_get_duplicates(self):
""" Insert n records, n-1 of which are duplicates, and check that the duplicates are successfully identified. """
query = "INSERT INTO test VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)"
c = self.connection.cursor()
n = 5 # The total number of records to insert.
for i in range(0, n):
c.execute(query, (self.fields_and_data["CALL"], self.fields_and_data["QSO_DATE"], self.fields_and_data["TIME_ON"], self.fields_and_data["FREQ"], self.fields_and_data["BAND"], self.fields_and_data["MODE"], self.fields_and_data["RST_SENT"], self.fields_and_data["RST_RCVD"]))
assert(len(self.log.get_duplicates()) == n-1) # Expecting n-1 duplicates.
def test_remove_duplicates(self):
""" Insert n records, n-1 of which are duplicates, and check that the duplicates are successfully removed. """
n = 5 # The total number of records to insert.
for i in range(0, n):
self.log.add_record(self.fields_and_data)
(number_of_duplicates, number_of_duplicates_removed) = self.log.remove_duplicates()
print("Number of duplicates: %d" % number_of_duplicates)
print("Number of duplicates removed: %d" % number_of_duplicates_removed)
assert(number_of_duplicates == number_of_duplicates_removed)
assert(number_of_duplicates == 4)
assert(self.log.record_count == 1)
def test_rename(self):
""" Check that a log can be successfully renamed. """
old_name = "test"
new_name = "hello"
success = self.log.rename(new_name)
assert(success)
with self.connection:
c = self.connection.cursor()
c.execute("SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE name=?)", [old_name])
exists = c.fetchone()
assert(exists[0] == 0) # Old log name should no longer exist.
c.execute("SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE name=?)", [new_name])
exists = c.fetchone()
assert(exists[0] == 1) # New log name should now exist.
assert(self.log.name == new_name)
if(__name__ == '__main__'):
unittest.main()

Wyświetl plik

@ -0,0 +1,144 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
import unittest
try:
import unittest.mock as mock
except ImportError:
import mock
import os
from shutil import copyfile
from pyqso.logbook import *
class TestLogbook(unittest.TestCase):
""" The unit tests for the Logbook class. """
@mock.patch('pyqso.logbook.Logbook.filter_by_callsign')
def setUp(self, mock_filter_by_callsign):
""" Set up the Logbook object and connection to the test database needed for the unit tests. """
self.logbook = Logbook(application=mock.MagicMock())
# Open the test database file.
path_to_test_database = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "test.db")
opened = self.logbook.open(path=path_to_test_database)
assert(opened)
assert(self.logbook.connection is not None)
# Check that the logs have been retrieved.
assert(len(self.logbook.logs) == 2)
assert(self.logbook.logs[0].name == "test")
assert(self.logbook.logs[1].name == "test2")
def tearDown(self):
""" Close the logbook and disconnect from the test database. """
self.logbook.notebook.get_n_pages.return_value = 0
closed = self.logbook.close()
assert(closed)
def test_db_disconnect(self):
""" Check that the logbook can disconnect from the database. """
disconnected = self.logbook.db_disconnect()
assert(disconnected)
# Attempt to disconnect again. This shouldn't do anything.
disconnected = self.logbook.db_disconnect()
assert(disconnected)
@mock.patch('pyqso.auxiliary_dialogs.handle_gtk_dialog')
@mock.patch('gi.repository.Gtk.FileChooserDialog')
def test_new(self, mock_FileChooserDialog, mock_handle_gtk_dialog):
""" Check that a new logbook can be created. """
mock_FileChooserDialog().run.return_value = Gtk.ResponseType.OK
mock_FileChooserDialog().get_filename.return_value = "Logbook.test_new.db"
self.logbook.new()
assert(os.path.isfile("Logbook.test_new.db"))
@mock.patch('pyqso.auxiliary_dialogs.handle_gtk_dialog')
def test_open_invalid_logbook(self, mock_handle_gtk_dialog):
""" Open an invalid database file (comprising only one line of plain text) and check that an error occurs. """
invalid_logbook = Logbook(application=mock.MagicMock())
path_to_invalid_database = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "invalid.db")
opened = invalid_logbook.open(path=path_to_invalid_database)
assert(not opened)
assert(not invalid_logbook.logs)
@mock.patch('pyqso.logbook.Logbook.render_log')
@mock.patch('pyqso.auxiliary_dialogs.handle_gtk_dialog')
@mock.patch('pyqso.logbook.LogNameDialog')
def test_new_log(self, mock_LogNameDialog, mock_handle_gtk_dialog, mock_render_log):
""" Create an empty logbook file, open it, and check that a new log can successfully be added. """
# Create a copy of the test database just for use in this particular test, since the contents will need to be modified.
path_to_test_database = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "test.db")
destination = "Logbook.test_new_log.db"
copyfile(path_to_test_database, destination)
opened = self.logbook.open(path=destination)
assert(opened)
mock_LogNameDialog().dialog.run.return_value = Gtk.ResponseType.OK
mock_LogNameDialog().name = "my_new_log"
self.logbook.new_log()
assert(len(self.logbook.logs) == 3)
assert(self.logbook.logs[-1].name == "my_new_log")
def test_log_name_exists(self):
""" Check that only the log called 'test' exists. """
assert(self.logbook.log_name_exists("test")) # Log 'test' exists.
assert(not self.logbook.log_name_exists("hello")) # Log 'hello' should not exist.
def test_log_count(self):
""" Check the log count. """
assert(self.logbook.log_count == 2)
def test_record_count(self):
""" Check the total number of records over all the logs in the logbook. """
assert(self.logbook.record_count == 7)
def test_filter_by_callsign(self):
""" Check that callsigns are filtered correctly. """
# Consider only the first record of the first log.
model = self.logbook.logs[0]
path = Gtk.TreePath(0)
iter = model.get_iter(path)
self.logbook.application.toolbar.filter_source.get_text.return_value = ""
present = self.logbook.filter_by_callsign(model, iter, data=None)
assert(present) # Show all the callsigns.
self.logbook.application.toolbar.filter_source.get_text.return_value = "TEST123"
present = self.logbook.filter_by_callsign(model, iter, data=None)
assert(present) # "TEST123" is present.
self.logbook.application.toolbar.filter_source.get_text.return_value = "TEST"
present = self.logbook.filter_by_callsign(model, iter, data=None)
assert(present) # "TEST" is present in "TEST123"
self.logbook.application.toolbar.filter_source.get_text.return_value = "HELLOWORLD"
present = self.logbook.filter_by_callsign(model, iter, data=None)
assert(not present) # "HELLOWORLD" is not present in "TEST123"
def test_get_log_index(self):
""" Check that a log's index can be resolved using the log's name. """
assert(self.logbook.get_log_index(name="test") == 0)
assert(self.logbook.get_log_index(name="test2") == 1)
assert(self.logbook.get_log_index(name="helloworld") is None)
if(__name__ == '__main__'):
unittest.main()

Wyświetl plik

@ -0,0 +1,52 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk
import unittest
try:
import unittest.mock as mock
except ImportError:
import mock
import os
from pyqso.printer import *
class TestPrinter(unittest.TestCase):
""" The unit tests for the Printer class. """
def setUp(self):
""" Set up the Printer object. """
PyQSO = mock.MagicMock()
self.printer = Printer(application=PyQSO())
self.printer.application.window = Gtk.Window()
def test_print_records(self):
""" Check that a list of records can be printed to a PDF file. """
self.printer.action = Gtk.PrintOperationAction.EXPORT
pdf = "Printer.test_print_records.pdf"
self.printer.operation.set_export_filename(pdf)
records = [{"id": 1, "CALL": "MYCALL", "QSO_DATE": "24062017", "TIME_ON": "1519", "FREQ": "145.550", "MODE": "FM", "RST_SENT": "59", "RST_RCVD": "57"}]
result = self.printer.print_records(records)
assert(result != Gtk.PrintOperationResult.ERROR)
assert(result == Gtk.PrintOperationResult.APPLY)
assert(os.path.exists(pdf))
if(__name__ == '__main__'):
unittest.main()

Wyświetl plik

@ -0,0 +1,111 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk
import unittest
try:
import unittest.mock as mock
except ImportError:
import mock
from pyqso.record_dialog import *
class TestRecordDialog(unittest.TestCase):
""" The unit tests for the RecordDialog class. """
def setUp(self):
""" Set up the objects needed for the unit tests. """
PyQSO = mock.MagicMock()
self.record_dialog = RecordDialog(application=PyQSO(), log=None)
self.record_dialog.frequency_unit = "MHz"
# Set up the necessary sources.
self.record_dialog.sources["FREQ"] = Gtk.Entry()
self.record_dialog.sources["BAND"] = Gtk.ComboBoxText()
for band in BANDS:
self.record_dialog.sources["BAND"].append_text(band)
self.record_dialog.sources["MODE"] = Gtk.ComboBoxText()
for mode in sorted(MODES.keys()):
self.record_dialog.sources["MODE"].append_text(mode)
self.record_dialog.sources["SUBMODE"] = Gtk.ComboBoxText()
self.record_dialog.sources["SUBMODE"].append_text("")
self.record_dialog.sources["SUBMODE"].set_active(0)
return
def test_autocomplete_band(self):
""" Given a frequency, check that the band field is automatically set to the correct value. """
self.record_dialog.sources["FREQ"].set_text("145.525")
self.record_dialog.autocomplete_band()
band = self.record_dialog.sources["BAND"].get_active_text()
assert(band == "2m")
self.record_dialog.sources["FREQ"].set_text("9001")
self.record_dialog.autocomplete_band()
band = self.record_dialog.sources["BAND"].get_active_text()
assert(band == "") # Frequency does not lie in any of the specified bands.
def test_convert_frequency(self):
""" Check that a frequency can be successfully converted from one unit to another. """
frequency = "7.140" # In MHz
converted = self.record_dialog.convert_frequency(frequency, from_unit="MHz", to_unit="AHz") # Unknown to_unit. This should return the input unmodified (and give an error message).
assert(converted == frequency)
converted = self.record_dialog.convert_frequency(frequency, from_unit="MHz", to_unit="kHz") # Convert from MHz to kHz.
assert(float(converted) == 1e3*float(frequency))
converted = self.record_dialog.convert_frequency(converted, from_unit="kHz", to_unit="MHz") # Convert from kHz back to MHz. This should give the original frequency.
assert(float(converted) == float(frequency))
# Floating-point data type.
frequency = 7.140 # In MHz
converted = self.record_dialog.convert_frequency(frequency, from_unit="MHz", to_unit="kHz")
assert(converted == frequency*1e3)
# Floating-point data type.
frequency = 7.140 # In MHz
converted = self.record_dialog.convert_frequency(frequency, from_unit="MHz", to_unit="MHz")
assert(converted == frequency)
# Empty string.
frequency = ""
converted = self.record_dialog.convert_frequency(frequency, from_unit="MHz", to_unit="kHz")
assert(converted == frequency)
# Not a valid frequency.
frequency = "HelloWorld"
converted = self.record_dialog.convert_frequency(frequency, from_unit="MHz", to_unit="kHz")
assert(converted == frequency)
def test_hamlib_autofill(self):
""" Check that FREQ, MODE and SUBMODE information can be retrieved from Hamlib's dummy rig (if the Hamlib module exists). """
if(have_hamlib):
rig_model = "RIG_MODEL_DUMMY"
rig_pathname = "/dev/Rig"
self.record_dialog.hamlib_autofill(rig_model, rig_pathname)
assert(self.record_dialog.sources["FREQ"].get_text() == "145.000000")
assert(self.record_dialog.sources["MODE"].get_active_text() == "FM")
assert(self.record_dialog.sources["SUBMODE"].get_active_text() == "")
else:
pass
if(__name__ == '__main__'):
unittest.main()

Wyświetl plik

@ -0,0 +1,72 @@
#!/usr/bin/env python3
# Copyright (C) 2017 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
try:
import unittest.mock as mock
except ImportError:
import mock
from pyqso.summary import *
from pyqso.logbook import Logbook
class TestSummary(unittest.TestCase):
""" The unit tests for the Summary class. """
def setUp(self):
""" Set up the objects needed for the unit tests and create a connection to the test database. """
PyQSO = mock.MagicMock()
self.summary = Summary(application=PyQSO())
self.summary.logbook = Logbook(application=PyQSO())
path_to_test_database = os.path.join(os.path.realpath(os.path.dirname(__file__)), "res", "test.db")
success = self.summary.logbook.db_connect(path_to_test_database)
assert(success)
self.summary.logbook.logs = self.summary.logbook.get_logs()
assert(self.summary.logbook.logs is not None)
def tearDown(self):
""" Destroy the connection to the test database. """
success = self.summary.logbook.db_disconnect()
assert(success)
def test_get_year_bounds(self):
""" Check that the years of the earliest and latest QSO are correct. """
year_min, year_max = self.summary.get_year_bounds()
assert(year_min == 2012)
assert(year_max == 2017)
def test_get_annual_contact_count(self):
""" Check that there are 3 QSOs in the year 2017. """
count = self.summary.get_annual_contact_count(2017)
april = datetime(2017, 4, 1)
april_count = count[april]
assert(april_count == 3) # A total of 3 contacts made in April.
assert(sum(count.values()) == 4) # A total of 4 contacts made that whole year.
def test_get_annual_mode_count(self):
""" Check that, in the year 2017, there was 1 QSO made using CW, 2 QSOs made using FM, and 1 QSO made using SSB. """
count = self.summary.get_annual_mode_count(2017)
assert(count["CW"] == 1)
assert(count["FM"] == 2)
assert(count["SSB"] == 1)
if(__name__ == '__main__'):
unittest.main()

Wyświetl plik

@ -0,0 +1,74 @@
#!/usr/bin/env python3
# Copyright (C) 2018 Christian Thomas Jacobs.
# This file is part of PyQSO.
# PyQSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyQSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyQSO. If not, see <http://www.gnu.org/licenses/>.
import unittest
try:
import unittest.mock as mock
except ImportError:
import mock
from pyqso.world_map import Maidenhead, WorldMap
class TestMaidenhead(unittest.TestCase):
""" The unit tests for the Maidenhead class. """
def setUp(self):
""" Set up the Maidenhead object needed for the unit tests. """
self.maidenhead = Maidenhead()
def test_ll2gs(self):
""" Check that a latitude-longitude coordinate can correctly be converted to a Maidenhead grid square. """
latitude = 51.0593
longitude = -1.4262
assert self.maidenhead.ll2gs(latitude, longitude, subsquare=False) == "IO91"
assert self.maidenhead.ll2gs(latitude, longitude, subsquare=True) == "IO91gb"
def test_gs2ll(self):
""" Check that a Maidenhead grid square can correctly be converted to a latitude-longitude coordinate. """
gs4 = "JN05"
assert self.maidenhead.gs2ll(gs4) == (45.5, 1.0)
gs6 = "JN05aa"
assert self.maidenhead.gs2ll(gs6) == (45.020833333333336, 0.041666666666666664)
gs6 = "IO91gb"
assert self.maidenhead.gs2ll(gs6) == (51.0625, -1.4583333333333335)
class TestWorldMap(unittest.TestCase):
""" The unit tests for the WorldMap class. """
def setUp(self):
""" Set up the WorldMap object needed for the unit tests. """
PyQSO = mock.MagicMock()
self.world_map = WorldMap(application=PyQSO())
def test_get_worked_grid_squares(self):
""" Check that the worked grid squares are determined correctly. """
Logbook = mock.MagicMock()
Log = mock.MagicMock()
logbook = Logbook()
l = Log()
l.records = [{"CALL": "TEST123", "COUNTRY": "England", "GRIDSQUARE": "IO91gb"}, {"CALL": "TEST456", "COUNTRY": "England", "GRIDSQUARE": "IO90hv"}, {"CALL": "TEST789", "COUNTRY": "England", "GRIDSQUARE": None}]
logbook.logs = [l]
worked_grid_squares = self.world_map.get_worked_grid_squares(logbook=logbook)
assert worked_grid_squares[14, 8] # IO square.
if(__name__ == '__main__'):
unittest.main()

3
tox.ini 100644
Wyświetl plik

@ -0,0 +1,3 @@
[flake8]
ignore = E501,F403,E226,E402,W503
exclude = .git,__pycache__,build