Porównaj commity
432 Commity
Autor | SHA1 | Data |
---|---|---|
Christian T. Jacobs | df629e7a64 | |
WB5VQX | 5efe5849ff | |
Christian Jacobs | 71624162bb | |
Christian Jacobs | f9837e14ba | |
Christian Jacobs | 99b5746f52 | |
Christian Jacobs | c6845c082e | |
Christian Jacobs | 095743e3ba | |
Christian Jacobs | ff8c6956fc | |
Christian Jacobs | 42d4966d9f | |
Christian Jacobs | 9cae123db1 | |
Christian Jacobs | 591ed62869 | |
Christian Jacobs | 108f0d00b5 | |
Christian Jacobs | 833da88ae2 | |
Christian Jacobs | d41d20779b | |
Christian Jacobs | f597122721 | |
Christian Jacobs | 3f29d763e4 | |
Christian Jacobs | 5988771a02 | |
Christian Jacobs | 9609b9c3d4 | |
Christian Jacobs | fd41340109 | |
Christian Jacobs | c0212f72d7 | |
Christian Jacobs | 05dee365b3 | |
Christian Jacobs | f1236f70e6 | |
Christian Jacobs | ed95a86710 | |
Christian Jacobs | 7dd02c35c0 | |
Christian Jacobs | d23dd54473 | |
Christian Jacobs | 1fcdb4f6ee | |
Christian Jacobs | 785d3b320f | |
Christian Jacobs | 6834673e28 | |
Christian Jacobs | b47ffa1366 | |
Christian Jacobs | d945d40064 | |
Christian T. Jacobs | ae8f45450a | |
Tomasz Nycz | b20e238ad9 | |
Christian Jacobs | 154673c189 | |
Christian T. Jacobs | 5198547c6c | |
Christian T. Jacobs | f222d5cc30 | |
Christian Jacobs | f283df065b | |
Christian Jacobs | 26e871bcab | |
Christian Jacobs | ee6018b04a | |
Christian Jacobs | 89f1ca46b4 | |
Christian Jacobs | 1ef87caf5e | |
Christian Jacobs | 946f03d95f | |
Christian T. Jacobs | 7a162b2a2d | |
Christian T. Jacobs | d06e326cbd | |
Christian T. Jacobs | 4550f841f7 | |
Christian T. Jacobs | 591fe60f87 | |
Christian T. Jacobs | b98421dd6d | |
Christian T. Jacobs | 4e044e72f7 | |
Christian T. Jacobs | 02c34387e5 | |
Christian T. Jacobs | 3fc6f3198a | |
Christian T. Jacobs | a09696b4a5 | |
Christian T. Jacobs | e00af44173 | |
Christian T. Jacobs | 63563b9085 | |
Christian T. Jacobs | 1b98e7695e | |
Christian T. Jacobs | 8dc9ed6aac | |
Christian T. Jacobs | af57a915fd | |
Christian T. Jacobs | 4d00a79620 | |
Christian T. Jacobs | f250d4c078 | |
Christian T. Jacobs | 21367d02a2 | |
Christian T. Jacobs | f6af59a5fd | |
Christian T. Jacobs | dd83014d9a | |
Christian T. Jacobs | bdd828ddb4 | |
Christian T. Jacobs | 80f60591b1 | |
Christian T. Jacobs | f4175ba40c | |
Christian T. Jacobs | e1ef6e8c4d | |
Christian T. Jacobs | ac888541a5 | |
Christian T. Jacobs | 00f4e7d12f | |
Christian T. Jacobs | adf0261bd2 | |
Christian T. Jacobs | 59fad31959 | |
Christian T. Jacobs | 7835dc1ff6 | |
Christian T. Jacobs | 21d5dd21ef | |
Christian T. Jacobs | e3f364f085 | |
Christian T. Jacobs | 93d8177932 | |
Christian T. Jacobs | 85fb4f6397 | |
Christian T. Jacobs | aa5094fa6f | |
Christian T. Jacobs | 21e2df09ac | |
Christian T. Jacobs | c777c924bb | |
Christian T. Jacobs | 660d993bc1 | |
Christian T. Jacobs | 7e28366aae | |
Christian T. Jacobs | a200eae434 | |
Christian T. Jacobs | 74256cd7b5 | |
Christian T. Jacobs | e3cd2d2e39 | |
Christian T. Jacobs | d1d053c74d | |
Christian T. Jacobs | dac5c11af9 | |
Christian T. Jacobs | 6a2cc5decf | |
Christian T. Jacobs | 443d12ab44 | |
Christian T. Jacobs | 29aa5b4465 | |
Christian T. Jacobs | 1c74cfd71d | |
Christian T. Jacobs | 5cbb43c11c | |
Christian T. Jacobs | c17b4f04fe | |
Christian T. Jacobs | 0b8bae0f9d | |
Christian T. Jacobs | 5ab266d168 | |
Christian T. Jacobs | 56e07c5f19 | |
Christian T. Jacobs | d34f1098aa | |
Christian T. Jacobs | 43054154b2 | |
Christian T. Jacobs | 4a595d7cbe | |
Christian T. Jacobs | 9e184b9feb | |
Christian T. Jacobs | 185e8dc104 | |
Christian T. Jacobs | a62abf9024 | |
Christian T. Jacobs | 28baab016d | |
Christian T. Jacobs | a105afe106 | |
Christian T. Jacobs | 05e6b7da80 | |
Christian T. Jacobs | 6d0b02b83e | |
Christian T. Jacobs | a4452f8c17 | |
Christian T. Jacobs | 52a8aa8d3f | |
Christian T. Jacobs | 622d180baa | |
Christian T. Jacobs | b405590fe8 | |
Christian T. Jacobs | 2e074df388 | |
Christian T. Jacobs | e34253adb2 | |
Christian T. Jacobs | 3e32142e8a | |
Christian T. Jacobs | 77047d5670 | |
Christian T. Jacobs | 7fee6c42b2 | |
Christian T. Jacobs | cf72d94035 | |
Christian T. Jacobs | b39d61cf33 | |
Christian T. Jacobs | 1cd94f5b43 | |
Christian T. Jacobs | b21f46f53c | |
Christian T. Jacobs | 7214b783b2 | |
Christian T. Jacobs | f3bf4ffc8c | |
Christian T. Jacobs | 70cf060d66 | |
Christian T. Jacobs | 2ddfc2d061 | |
Christian T. Jacobs | f3a7888183 | |
Christian T. Jacobs | b099111218 | |
Christian T. Jacobs | c00e0a7ecb | |
Christian T. Jacobs | 67d2050156 | |
Christian T. Jacobs | 4becec41ed | |
Christian T. Jacobs | b91c77f07b | |
Christian T. Jacobs | 7055f4f67d | |
Christian T. Jacobs | f816554816 | |
Christian T. Jacobs | 66ecabd737 | |
Christian T. Jacobs | 2d42acde9c | |
Christian T. Jacobs | f3bacf9dc7 | |
Christian T. Jacobs | 7f6c94982a | |
Christian T. Jacobs | 879e49b496 | |
Christian T. Jacobs | 4f61570828 | |
Christian T. Jacobs | 6b7d42e6dd | |
Christian T. Jacobs | 9a1371390e | |
Christian T. Jacobs | 75a8f0ce50 | |
Christian T. Jacobs | 65a3fe68d9 | |
Christian T. Jacobs | be7ad3bf1f | |
Christian T. Jacobs | 181312b2bc | |
Christian T. Jacobs | 4cf5a56c7e | |
Christian T. Jacobs | 3f467b2977 | |
Christian T. Jacobs | 7b1c452f3e | |
Christian T. Jacobs | 5c1d3aeef0 | |
Christian T. Jacobs | a09d5ab1ce | |
Christian T. Jacobs | 459322689a | |
Christian T. Jacobs | 4478e117fa | |
Christian T. Jacobs | b59d543dd2 | |
Christian T. Jacobs | 60a26bb2fa | |
Christian T. Jacobs | 34625292e2 | |
Christian T. Jacobs | f29ece0033 | |
Christian T. Jacobs | 73f785af7c | |
Christian T. Jacobs | 43b647b19e | |
Christian T. Jacobs | e407b9b3a1 | |
Christian T. Jacobs | 8bf0895da7 | |
Christian T. Jacobs | 69abd30027 | |
Christian T. Jacobs | 9a8fedf475 | |
Christian T. Jacobs | 6b1caa1a3c | |
Christian T. Jacobs | db1c050b78 | |
Christian T. Jacobs | a1d5640be3 | |
Christian T. Jacobs | 55d2af808d | |
Christian T. Jacobs | 50f01bf3ca | |
Christian T. Jacobs | 3ef2057dbe | |
Christian T. Jacobs | 3754f2347e | |
Christian T. Jacobs | 490fda7128 | |
Christian T. Jacobs | 803a5d4430 | |
Christian T. Jacobs | 9813344c58 | |
Christian T. Jacobs | b698900fe5 | |
Christian T. Jacobs | 15f38b4c43 | |
Christian T. Jacobs | d5ff95edb1 | |
Christian T. Jacobs | efb1f38e9a | |
Christian T. Jacobs | 8213b32b0a | |
Christian T. Jacobs | f6b029a269 | |
Christian T. Jacobs | 9efba69648 | |
Christian T. Jacobs | 49b544b463 | |
Christian T. Jacobs | bce1f98776 | |
Christian T. Jacobs | 500e3f6266 | |
Christian T. Jacobs | 904d02ce23 | |
Christian T. Jacobs | b9fb712f16 | |
Christian T. Jacobs | 69b4333e2a | |
Christian T. Jacobs | da9b31ea10 | |
Christian T. Jacobs | bba65693ca | |
Christian T. Jacobs | 37df41e93c | |
Christian T. Jacobs | 9f86e190ce | |
Christian T. Jacobs | bb4fa2a09c | |
Christian T. Jacobs | 40d6869ef9 | |
Christian T. Jacobs | 34dcc61b6f | |
Christian T. Jacobs | a11f7d275a | |
Christian T. Jacobs | b2b20a2edc | |
Christian T. Jacobs | 71e365ea22 | |
Christian T. Jacobs | a97993d7ae | |
Christian T. Jacobs | 2561f29fcc | |
Christian T. Jacobs | 6d978202f4 | |
Christian T. Jacobs | bd08213bd8 | |
Christian T. Jacobs | 8ccff558da | |
Christian T. Jacobs | aebab3eca7 | |
Christian T. Jacobs | 4276b544bc | |
Christian T. Jacobs | 7c263c9fe2 | |
Christian T. Jacobs | 6b069e280e | |
Christian T. Jacobs | 3288a1f47d | |
Christian T. Jacobs | ae352f790d | |
Christian T. Jacobs | 108f6850eb | |
Christian T. Jacobs | 0ba9a6e3e0 | |
Christian T. Jacobs | caff4ca18d | |
Christian T. Jacobs | 911c3f2309 | |
Christian T. Jacobs | 39ca881e2e | |
Christian T. Jacobs | fda54fe070 | |
Christian T. Jacobs | 879db074c9 | |
Christian T. Jacobs | 110e5fe700 | |
Christian T. Jacobs | 868d7b2c9c | |
Christian T. Jacobs | 3809b4b852 | |
Christian T. Jacobs | 9194a71a99 | |
Christian T. Jacobs | a6aa5813f5 | |
Christian T. Jacobs | 8d8276ff33 | |
Christian T. Jacobs | 41acc8be30 | |
Christian T. Jacobs | de85e53c64 | |
Christian T. Jacobs | 886cf159ec | |
Christian T. Jacobs | 39aa303959 | |
Christian T. Jacobs | 3a5a1525a5 | |
Christian T. Jacobs | 0953a2e431 | |
Christian T. Jacobs | 64cb2b2c15 | |
Christian T. Jacobs | 331d80a060 | |
Christian T. Jacobs | 9a6a1a24ae | |
Christian T. Jacobs | c53c7ab9a3 | |
Christian T. Jacobs | 68dfa0f9d6 | |
Christian T. Jacobs | 7df20bd28b | |
Christian T. Jacobs | 2a33f97505 | |
Christian T. Jacobs | 78033f9a01 | |
Christian T. Jacobs | f122e3cfde | |
Christian T. Jacobs | ae304e7fa9 | |
Christian T. Jacobs | 12ae7195f4 | |
Christian T. Jacobs | 522e461dee | |
Christian T. Jacobs | eb263e9ea4 | |
Christian T. Jacobs | c3bce781f1 | |
Christian T. Jacobs | fa96db7219 | |
Christian T. Jacobs | a3b3568d48 | |
Christian T. Jacobs | db80fac9fe | |
Christian T. Jacobs | 93e76b9b84 | |
Christian T. Jacobs | 0cdd59f3ef | |
Christian T. Jacobs | 35922cd493 | |
Christian T. Jacobs | eb4672f73c | |
Christian T. Jacobs | 6407c4a9cc | |
Christian T. Jacobs | 76b673475e | |
Christian T. Jacobs | 9e73b2abfa | |
Christian T. Jacobs | 5454c8e296 | |
Christian T. Jacobs | 2d30163e7d | |
Christian T. Jacobs | 74b393e0e1 | |
Christian T. Jacobs | 315997c1e5 | |
Christian T. Jacobs | 8a07c26fec | |
Christian T. Jacobs | 531749270c | |
Christian T. Jacobs | c10abde42a | |
Christian T. Jacobs | efc5f80be8 | |
Christian T. Jacobs | 0b63338367 | |
Christian T. Jacobs | 988cf6e854 | |
Christian T. Jacobs | a3bf4d9c8e | |
Christian T. Jacobs | 6c782094e7 | |
Christian T. Jacobs | 7a2aa12e47 | |
Christian T. Jacobs | 3caf3f9274 | |
Christian T. Jacobs | 1f4f95bcba | |
Christian T. Jacobs | 10d0b9d462 | |
Christian T. Jacobs | 2565a7512d | |
Christian T. Jacobs | 75a65891a9 | |
Christian T. Jacobs | 183d1c9d8d | |
Christian T. Jacobs | 2ef087c202 | |
Christian T. Jacobs | e10a25bccf | |
Christian T. Jacobs | 66d3f45be8 | |
Christian T. Jacobs | d78f0f74d7 | |
Christian T. Jacobs | b9c15c0e92 | |
Christian T. Jacobs | 9c954373b0 | |
Christian T. Jacobs | 95bad0fe72 | |
Christian T. Jacobs | 36de2328c4 | |
Christian T. Jacobs | a6d5839527 | |
Christian T. Jacobs | 296997ec4e | |
Christian T. Jacobs | 09a2d3e78b | |
Christian T. Jacobs | 60bfb3520e | |
Christian T. Jacobs | 005d5385b4 | |
Christian T. Jacobs | d5e0f2e007 | |
Christian T. Jacobs | 00a86c57bc | |
Christian T. Jacobs | 1eea1d5917 | |
Christian T. Jacobs | e168a417d1 | |
Christian T. Jacobs | 7fdedc51b4 | |
Christian T. Jacobs | f19d99b92c | |
Christian T. Jacobs | cbe93856b4 | |
Christian T. Jacobs | b89acae882 | |
Christian T. Jacobs | 0c3f76deb8 | |
Christian T. Jacobs | e04b604bf1 | |
Christian T. Jacobs | 6a8c2c1798 | |
Christian T. Jacobs | 3f0995086b | |
Christian T. Jacobs | 03eeb614ae | |
Christian T. Jacobs | 6dc8488e00 | |
Christian T. Jacobs | f266e6def8 | |
Christian T. Jacobs | fdc3a5f051 | |
Christian T. Jacobs | be1ae2af4d | |
Christian T. Jacobs | 7cd34fb59a | |
Christian T. Jacobs | 0456d1b3ec | |
Christian T. Jacobs | f976d840e2 | |
Christian T. Jacobs | 7b3f8d067b | |
Christian T. Jacobs | 98cfa7b9e1 | |
Christian T. Jacobs | 3eb3275d35 | |
Christian T. Jacobs | 304d35fe0f | |
Christian T. Jacobs | e977bc5e0f | |
Christian T. Jacobs | c9ffb5e11e | |
Christian T. Jacobs | 295eb79b91 | |
Christian T. Jacobs | ba6b570583 | |
Christian T. Jacobs | 389ab91072 | |
Christian T. Jacobs | 8d219a25da | |
Christian T. Jacobs | c8c9ae681e | |
Christian T. Jacobs | 5cc525c5c7 | |
Christian T. Jacobs | d70762ae01 | |
Christian T. Jacobs | 9baf2aaddd | |
Christian T. Jacobs | abaa467a88 | |
Christian T. Jacobs | ce46c14096 | |
Christian T. Jacobs | 08d21627e2 | |
Christian T. Jacobs | e733af215e | |
Christian T. Jacobs | 1e185318f7 | |
Christian T. Jacobs | 79d3451d56 | |
Christian T. Jacobs | 2524cd5d94 | |
Christian T. Jacobs | df27c359ac | |
Christian T. Jacobs | 948f1260cd | |
Christian T. Jacobs | a65e34db65 | |
Christian T. Jacobs | 4124c4c040 | |
Christian T. Jacobs | 047cea4cf5 | |
Christian T. Jacobs | 426c2dac29 | |
Christian T. Jacobs | a6edcf1fd6 | |
Christian T. Jacobs | 709d15af8b | |
Christian T. Jacobs | 72485d3bc7 | |
Christian T. Jacobs | 520ffb79de | |
Christian T. Jacobs | 591ac35bb5 | |
Christian T. Jacobs | 4c18f2099b | |
Christian T. Jacobs | 9456476961 | |
Christian T. Jacobs | b9901196db | |
Christian T. Jacobs | 238564d044 | |
Christian T. Jacobs | b29eebe0b4 | |
Christian T. Jacobs | b52ec714a7 | |
Christian T. Jacobs | 7e0c3f581b | |
Christian T. Jacobs | 9bc16c35e9 | |
Christian T. Jacobs | 1abf785d0e | |
Christian T. Jacobs | 662ebb3c06 | |
Christian T. Jacobs | 9ddaa56b73 | |
Christian T. Jacobs | 4b96f9591d | |
Christian T. Jacobs | 1c6a4d518a | |
Christian T. Jacobs | 82cfacc63b | |
Christian T. Jacobs | 8b5ea87b79 | |
Christian T. Jacobs | 03d322df21 | |
Christian T. Jacobs | 7d68b0aa73 | |
Christian T. Jacobs | f24cb30c82 | |
Christian T. Jacobs | 0e62c91380 | |
Christian T. Jacobs | d02239bd30 | |
Christian T. Jacobs | b29f0e54ca | |
Christian T. Jacobs | ad938a3d9a | |
Christian T. Jacobs | c993704e84 | |
Christian T. Jacobs | 1e5a657ca7 | |
Christian Jacobs | 1c47846289 | |
Christian T. Jacobs | 5f7056ed53 | |
Christian Jacobs | 98f27a36e2 | |
Christian Jacobs | 6de0a1f451 | |
Christian Jacobs | 56b476e66d | |
Christian Jacobs | 23a325367c | |
Christian Jacobs | cc436c4a42 | |
Christian Jacobs | f03f31c65b | |
Christian Jacobs | c610b9f13e | |
Christian Jacobs | 76f038a39b | |
Christian Jacobs | a5f4d80654 | |
Christian Jacobs | 608007d616 | |
Christian Jacobs | 3d40955b36 | |
Christian Jacobs | 524c6a0054 | |
Christian Jacobs | b9ce2153de | |
Christian Jacobs | 07274c6f60 | |
Christian Jacobs | 7c173206e1 | |
Christian Jacobs | a115e0f27d | |
Christian Jacobs | 7d941ce2fe | |
Christian Jacobs | cc933a3a9c | |
Christian Jacobs | 2a66389dc3 | |
Christian Jacobs | 3b72e0773b | |
Christian Jacobs | efbc51d6bf | |
Christian Jacobs | d6588c5761 | |
Christian Jacobs | 362c9fa5e5 | |
Christian Jacobs | e1e4784a07 | |
Christian Jacobs | 6f7d15cb33 | |
Christian Jacobs | 4164977747 | |
Christian Jacobs | 04305bfd42 | |
Christian Jacobs | 8a70fbc369 | |
Christian Jacobs | 05664b4f04 | |
Christian Jacobs | ea8777841a | |
Christian Jacobs | f9fdc32891 | |
Christian Jacobs | 2fcdc4833c | |
Christian Jacobs | dcd94634e8 | |
Christian Jacobs | 4b1f83eeef | |
Christian Jacobs | 534166bb9c | |
Christian Jacobs | 905c352af0 | |
Christian Jacobs | e957ae5864 | |
Christian Jacobs | ef9ca21ccb | |
Christian Jacobs | de01ceefdf | |
Christian Jacobs | 07954c18a8 | |
Christian Jacobs | 2b029d16e3 | |
njohnsn | fc94c8d511 | |
Christian Jacobs | 02d7b5446a | |
Christian Jacobs | 6ceac47c9a | |
Christian Jacobs | ce900209b0 | |
Christian Jacobs | 394dc1a345 | |
Christian Jacobs | 0cb85b0bb6 | |
Christian Jacobs | 165edd5023 | |
Christian Jacobs | 45abb28e38 | |
Christian Jacobs | bf26af984d | |
Christian Jacobs | 794d999587 | |
András Veres-Szentkirályi | 7d8b702bce | |
András Veres-Szentkirályi | e92c294dd4 | |
András Veres-Szentkirályi | 9094d197e9 | |
András Veres-Szentkirályi | 5054c99e7c | |
András Veres-Szentkirályi | 3f9434cd2e | |
András Veres-Szentkirályi | 500ca5977a | |
Christian Jacobs | 37685c9a4c | |
Christian Jacobs | c6002fbd7d | |
Christian Jacobs | e567c7a077 | |
Christian Jacobs | 4448f450ba | |
Christian Jacobs | 819a6a0e47 | |
Christian Jacobs | c1d4333662 | |
Christian Jacobs | 5e1376eddb | |
Christian Jacobs | dc32c2c23d | |
Christian Jacobs | 7529accdeb | |
Christian Jacobs | 6a90e9a0bd | |
Christian Jacobs | 160aa2133d | |
Christian Jacobs | a8083630c7 | |
Christian Jacobs | 3002f2439e | |
Christian Jacobs | 620e2e0954 | |
Christian Jacobs | eec02777d5 | |
Christian Jacobs | 00c365568b | |
Christian Jacobs | 838da2779b | |
Christian Jacobs | 1fdfc428a7 | |
Christian Jacobs | 2c5b7d9c55 | |
Christian Jacobs | edbc9ebdec | |
Christian Jacobs | d0ef8ccf9a | |
Christian Jacobs | 233b996784 |
|
@ -2,4 +2,3 @@
|
|||
pyqso.debug
|
||||
build/
|
||||
docs/build
|
||||
ADIF.test*.adi
|
||||
|
|
15
.travis.yml
|
@ -1,14 +1,17 @@
|
|||
sudo: required
|
||||
dist: trusty
|
||||
|
||||
language: python
|
||||
|
||||
python:
|
||||
- "2.7"
|
||||
|
||||
- "3.4"
|
||||
|
||||
virtualenv:
|
||||
system_site_packages: true
|
||||
|
||||
before_install:
|
||||
- sudo apt-get update -qq
|
||||
- sudo apt-get install -y python2.7 gir1.2-gtk-3.0 python-gi-cairo python-mpltoolkits.basemap python-numpy python-matplotlib python-libhamlib2 python-sphinx
|
||||
- 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"
|
||||
|
||||
|
@ -17,8 +20,12 @@ install:
|
|||
|
||||
before_script:
|
||||
- export PYTHONPATH=`pwd`:$PYTHONPATH
|
||||
- echo $PYTHONPATH
|
||||
- flake8 pyqso
|
||||
- flake8 tests
|
||||
- flake8 bin
|
||||
|
||||
script:
|
||||
- make unittest
|
||||
- make test
|
||||
- make docs
|
||||
- sudo make clean
|
||||
|
|
71
CHANGELOG.md
|
@ -1,12 +1,78 @@
|
|||
# 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 "EA3/MYCALL/M").
|
||||
- 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.
|
||||
|
@ -46,5 +112,8 @@
|
|||
- 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
|
||||
|
|
12
Makefile
|
@ -1,6 +1,6 @@
|
|||
#!/bin/sh
|
||||
|
||||
# Copyright (C) 2013 Christian T. Jacobs.
|
||||
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
|
||||
|
||||
# This file is part of PyQSO.
|
||||
|
||||
|
@ -17,26 +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/>.
|
||||
|
||||
.PHONY: input clean install docs unittest
|
||||
.PHONY: input clean install docs test
|
||||
|
||||
input: clean install docs
|
||||
|
||||
install:
|
||||
@echo "*** Installing PyQSO"
|
||||
python setup.py install
|
||||
pip3 install .
|
||||
|
||||
docs:
|
||||
@echo "*** Building the documentation"
|
||||
cd docs; make html; cd ..
|
||||
|
||||
unittest:
|
||||
test:
|
||||
@echo "*** Running the unit tests"
|
||||
python -m unittest discover --start-directory=pyqso --pattern=*.py --verbose
|
||||
python3 -m unittest discover --start-directory=tests --pattern=*.py --verbose
|
||||
|
||||
clean:
|
||||
@echo "*** Cleaning docs directory"
|
||||
cd docs; make clean; cd ..
|
||||
@echo "*** Cleaning pyqso directory"
|
||||
rm -f ADIF.test_*.adi; cd pyqso; rm -f *.pyc ADIF.test_*.adi; cd ..
|
||||
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
|
||||
|
|
100
README.md
|
@ -1,4 +1,4 @@
|
|||
Copyright (C) 2013 Christian T. Jacobs.
|
||||
Copyright (C) 2013-2018 Christian Thomas Jacobs.
|
||||
|
||||
This file is part of PyQSO.
|
||||
|
||||
|
@ -15,67 +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.
|
||||
|
||||
[![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)
|
||||
|
||||
Installation and running
|
||||
------------------------
|
||||
## Dependencies
|
||||
|
||||
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:
|
||||
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:
|
||||
|
||||
`make install`
|
||||
* python3
|
||||
* gir1.2-gtk-3.0
|
||||
* python3-gi-cairo
|
||||
|
||||
Note: 'sudo' may be needed for this. Once installed, the following command will run PyQSO:
|
||||
|
||||
`pyqso`
|
||||
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:
|
||||
|
||||
Alternatively, PyQSO can be run (without installing) with:
|
||||
sudo pip3 install -U -r requirements.txt
|
||||
|
||||
`python bin/pyqso`
|
||||
but the complete list is given below:
|
||||
|
||||
from PyQSO's base directory.
|
||||
* 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.
|
||||
|
||||
Documentation
|
||||
-------------
|
||||
### Hamlib support
|
||||
|
||||
The PyQSO documentation is stored in the `docs` directory. It can be built with the following command:
|
||||
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):
|
||||
|
||||
`make docs`
|
||||
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.
|
||||
|
||||
Alternatively, a ready-built version of the PyQSO documentation can be found on [Read the Docs](http://pyqso.readthedocs.org/en/latest/).
|
||||
|
||||
Dependencies
|
||||
------------
|
||||
|
||||
PyQSO depends on the following Debian packages:
|
||||
|
||||
* gir1.2-gtk-3.0
|
||||
* python2.7
|
||||
* python-gi-cairo (for log printing purposes)
|
||||
|
||||
The following extra packages are necessary to enable the grey line tool:
|
||||
|
||||
* python-mpltoolkits.basemap
|
||||
* python-numpy
|
||||
* python-matplotlib (version 1.3.0 or later)
|
||||
|
||||
The following extra package is necessary to enable Hamlib support:
|
||||
|
||||
* python-libhamlib2
|
||||
|
||||
The following extra package is necessary to build the documentation:
|
||||
|
||||
* python-sphinx
|
||||
|
||||
Contact
|
||||
-------
|
||||
|
||||
If you have any comments or questions about PyQSO, please send them via email to <c.jacobs10@imperial.ac.uk>.
|
||||
## Contact
|
||||
|
||||
If you have any comments or questions about PyQSO please send them via email to Christian Jacobs, M0UOS, at <christian@christianjacobs.uk>.
|
||||
|
|
244
bin/pyqso
|
@ -1,6 +1,6 @@
|
|||
#!/usr/bin/env python
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (C) 2012 Christian T. Jacobs.
|
||||
# Copyright (C) 2012-2018 Christian Thomas Jacobs.
|
||||
|
||||
# This file is part of PyQSO.
|
||||
|
||||
|
@ -17,155 +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
|
||||
from gi import require_version
|
||||
require_version('Gtk', '3.0')
|
||||
require_version('PangoCairo', '1.0')
|
||||
from gi.repository import Gtk, Gdk, GdkPixbuf
|
||||
import argparse
|
||||
import ConfigParser
|
||||
try:
|
||||
import configparser
|
||||
except ImportError:
|
||||
import ConfigParser as configparser
|
||||
import os
|
||||
import os.path
|
||||
import sys
|
||||
import signal
|
||||
import pkg_resources
|
||||
|
||||
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)
|
||||
|
||||
import logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
# 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.2")
|
||||
|
||||
# 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.2")
|
||||
about.set_authors(["Christian T. Jacobs (M6RDG)"])
|
||||
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 = 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()
|
||||
# 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()
|
||||
|
||||
# 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(args.logbook) # Populate the main window and show it
|
||||
Gtk.main() # Start up the event loop!
|
||||
# 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)
|
||||
|
||||
# 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!
|
||||
|
|
|
@ -19,7 +19,7 @@ ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) sou
|
|||
# the i18n builder cannot share the environment and doctrees with the others
|
||||
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
|
||||
|
||||
.PHONY: help clean aptdoc html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
|
||||
.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"
|
||||
|
|
|
@ -51,16 +51,16 @@ master_doc = 'index'
|
|||
|
||||
# General information about the project.
|
||||
project = u'PyQSO'
|
||||
copyright = u'2015, Christian T. Jacobs'
|
||||
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 = '0.2'
|
||||
version = '1.1.0'
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = '0.2'
|
||||
release = '1.1.0'
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
|
@ -189,22 +189,22 @@ htmlhelp_basename = 'PyQSOdoc'
|
|||
# -- Options for LaTeX output ---------------------------------------------
|
||||
|
||||
latex_elements = {
|
||||
# The paper size ('letterpaper' or 'a4paper').
|
||||
#'papersize': 'letterpaper',
|
||||
# The paper size ('letterpaper' or 'a4paper').
|
||||
#'papersize': 'letterpaper',
|
||||
|
||||
# The font size ('10pt', '11pt' or '12pt').
|
||||
#'pointsize': '10pt',
|
||||
# The font size ('10pt', '11pt' or '12pt').
|
||||
#'pointsize': '10pt',
|
||||
|
||||
# Additional stuff for the LaTeX preamble.
|
||||
#'preamble': '',
|
||||
# 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 T. Jacobs', 'manual'),
|
||||
('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
|
||||
|
@ -234,7 +234,7 @@ latex_documents = [
|
|||
# (source start file, name, description, authors, manual section).
|
||||
man_pages = [
|
||||
('index', 'pyqso', u'PyQSO Documentation',
|
||||
[u'Christian T. Jacobs'], 1)
|
||||
[u'Christian Thomas Jacobs, M0UOS'], 1)
|
||||
]
|
||||
|
||||
# If true, show URL addresses after external links.
|
||||
|
@ -247,9 +247,9 @@ man_pages = [
|
|||
# (source start file, target name, title, author,
|
||||
# dir menu entry, description, category)
|
||||
texinfo_documents = [
|
||||
('index', 'PyQSO', u'PyQSO Documentation',
|
||||
u'Christian T. Jacobs', 'PyQSO', 'A contact logging tool for amateur radio operators.',
|
||||
'Miscellaneous'),
|
||||
('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.
|
||||
|
|
|
@ -1,47 +1,54 @@
|
|||
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
|
||||
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
|
||||
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 and any additional software dependencies are satisfied
|
||||
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 installed via the
|
||||
terminal with the following command:
|
||||
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
|
||||
|
||||
make install
|
||||
python3 bin/pyqso
|
||||
|
||||
Note: ``sudo`` may be needed for this. Once installed, the following
|
||||
command will run 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
|
||||
|
||||
Alternatively, PyQSO can be run (without installing) with:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
python bin/pyqso
|
||||
|
||||
from PyQSO's base directory.
|
||||
|
||||
Command-line options
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
@ -87,7 +94,7 @@ Once the logbook has been opened, its name will appear in the status bar. All lo
|
|||
.. figure:: images/logbook.png
|
||||
:align: center
|
||||
|
||||
The PyQSO main window, showing the records in a log called ``HF``, and the DX cluster tool in the toolbox below it.
|
||||
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
|
||||
-----------------
|
||||
|
|
Przed Szerokość: | Wysokość: | Rozmiar: 11 KiB Po Szerokość: | Wysokość: | Rozmiar: 10 KiB |
Przed Szerokość: | Wysokość: | Rozmiar: 61 KiB Po Szerokość: | Wysokość: | Rozmiar: 58 KiB |
Przed Szerokość: | Wysokość: | Rozmiar: 43 KiB Po Szerokość: | Wysokość: | Rozmiar: 54 KiB |
Przed Szerokość: | Wysokość: | Rozmiar: 64 KiB |
Przed Szerokość: | Wysokość: | Rozmiar: 137 KiB Po Szerokość: | Wysokość: | Rozmiar: 202 KiB |
Po Szerokość: | Wysokość: | Rozmiar: 51 KiB |
Po Szerokość: | Wysokość: | Rozmiar: 154 KiB |
|
@ -17,4 +17,5 @@ Contents:
|
|||
record_management
|
||||
toolbox
|
||||
preferences
|
||||
|
||||
shortcuts
|
||||
pyqso
|
||||
|
|
|
@ -4,19 +4,17 @@ Introduction
|
|||
Overview
|
||||
--------
|
||||
|
||||
PyQSO is a logging tool for amateur radio operators. It provides a
|
||||
`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).
|
||||
- Customisable interface (e.g. only show callsign and frequency information).
|
||||
|
||||
- Import and export logs in ADIF format.
|
||||
- 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
|
||||
database.
|
||||
- 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.
|
||||
|
||||
|
@ -24,18 +22,17 @@ include:
|
|||
|
||||
- Connect to Telnet-based DX clusters.
|
||||
|
||||
- Progress tracker for the DXCC award.
|
||||
- Progress tracker for the `DXCC <http://www.arrl.org/dxcc/>`_ award.
|
||||
|
||||
- Grey line plotter.
|
||||
- World map with grey line and Maidenhead grid squares.
|
||||
|
||||
- Filter out QSOs based on the callsign field (e.g. only display
|
||||
contacts with callsigns beginning with "M6").
|
||||
- Filter QSOs based on callsign (e.g. only display contacts with callsigns beginning with "M6").
|
||||
|
||||
- Remove duplicate QSOs.
|
||||
|
||||
- Basic support for the Hamlib library.
|
||||
- Basic support for the `Hamlib <http://hamlib.sourceforge.net/>`_ library.
|
||||
|
||||
The source code for PyQSO is available for download from the `GitHub repository <https://github.com/ctjacobs/pyqso>`_.
|
||||
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
|
||||
------------------
|
||||
|
@ -43,7 +40,7 @@ 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 and another
|
||||
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.
|
||||
|
@ -58,10 +55,15 @@ log.
|
|||
Licensing
|
||||
---------
|
||||
|
||||
PyQSO is free software, released under the GNU General Public License. Please see the file called ``COPYING`` for more information.
|
||||
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 from/exporting to ADIF format, 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 grey line plotter, 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.
|
||||
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.
|
||||
|
||||
|
|
|
@ -11,7 +11,7 @@ Creating a new log
|
|||
------------------
|
||||
|
||||
To create a new log, click ``New Log`` in the ``Logbook`` menu and enter
|
||||
the desired name of the log (e.g. repeater\_contacts, dx, mobile\_log).
|
||||
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
|
||||
|
@ -19,16 +19,16 @@ 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
|
||||
**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 the `ADIF website <http://adif.org/>`_ for more information about these fields.
|
||||
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
|
||||
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.
|
||||
|
||||
|
@ -39,26 +39,29 @@ 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.
|
||||
|
||||
Importing and exporting a log
|
||||
-----------------------------
|
||||
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/>`_ format. Select the log to export,
|
||||
and click ``Export Log`` in the ``Logbook`` menu.
|
||||
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.
|
||||
|
||||
Similarly, records can be imported from an ADIF file. Upon importing,
|
||||
**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
|
||||
existing log in the logbook. To import, click ``Import Log...`` in the
|
||||
``Logbook`` menu.
|
||||
|
||||
Note that all data must conform to the ADIF standard, otherwise it will
|
||||
be ignored.
|
||||
Note that each QSO record being imported must conform to the ADIF standard, otherwise the record will be ignored.
|
||||
|
||||
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.
|
||||
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
|
||||
---------------------
|
||||
|
@ -70,7 +73,7 @@ contain ``xyz``.
|
|||
Sorting by field
|
||||
----------------
|
||||
|
||||
To sort a log by a particular field name, left-click the column header
|
||||
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.
|
||||
|
||||
|
|
|
@ -2,42 +2,65 @@ Preferences
|
|||
===========
|
||||
|
||||
PyQSO user preferences are stored in a configuration file located at
|
||||
``~/.pyqso.ini``, where ``~`` denotes the user's home directory.
|
||||
``~/.config/pyqso/preferences.ini``, where ``~`` denotes the user's home directory.
|
||||
|
||||
General
|
||||
-------
|
||||
|
||||
Under the ``General`` tab, the user can choose to show the toolbox (see
|
||||
the `Toolbox <toolbox.html>`_ section) when PyQSO is started.
|
||||
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 of them by unchecking them in the
|
||||
``View`` tab. PyQSO must be restarted in order for any changes to take
|
||||
effect.
|
||||
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 allows users to choose if the UTC timezone is used when autocompleting the date and time fields, and whether the band should be automatically determined from the frequency field. Default values for the Power and Mode fields can also be specified here.
|
||||
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/>`_
|
||||
database and perform callsign lookups. Note that these details are currently stored in plain text
|
||||
(unencrypted) format.
|
||||
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 EA3/MYCALL/P, only MYCALL will be looked up. If you get 'Callsign not found' errors, try enabling this option.
|
||||
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 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 that the radio device is set to and automatically fill in the
|
||||
Frequency field.
|
||||
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.
|
||||
|
|
|
@ -28,6 +28,38 @@ pyqso.awards module
|
|||
: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
|
||||
----------------------------
|
||||
|
||||
|
@ -36,6 +68,14 @@ pyqso.callsign_lookup module
|
|||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
pyqso.compare module
|
||||
--------------------
|
||||
|
||||
.. automodule:: pyqso.compare
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
pyqso.dx_cluster module
|
||||
-----------------------
|
||||
|
||||
|
@ -92,6 +132,14 @@ pyqso.preferences_dialog module
|
|||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
pyqso.printer module
|
||||
--------------------
|
||||
|
||||
.. automodule:: pyqso.printer
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
pyqso.record_dialog module
|
||||
--------------------------
|
||||
|
||||
|
@ -100,6 +148,14 @@ pyqso.record_dialog module
|
|||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
pyqso.summary module
|
||||
--------------------
|
||||
|
||||
.. automodule:: pyqso.summary
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
pyqso.telnet_connection_dialog module
|
||||
-------------------------------------
|
||||
|
||||
|
|
|
@ -17,7 +17,7 @@ A new QSO can be added by either:
|
|||
|
||||
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`` to save the
|
||||
are filled in automatically. When ready, click ``OK`` or press the Enter key to save the
|
||||
changes.
|
||||
|
||||
.. _figure:edit_record:
|
||||
|
@ -30,9 +30,9 @@ Callsign lookup
|
|||
~~~~~~~~~~~~~~~
|
||||
|
||||
PyQSO can also resolve station-related information (e.g. the operator's
|
||||
name, address, and ITU Zone) by clicking the ``Lookup on qrz.com``
|
||||
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/>`_ account information in the preferences dialog
|
||||
first supply their `qrz.com <http://qrz.com/>`_ or `hamqth.com <http://hamqth.com/>`_ account information in the preferences dialog
|
||||
window.
|
||||
|
||||
Editing a record
|
||||
|
@ -49,6 +49,17 @@ An existing record can be edited by:
|
|||
|
||||
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
|
||||
-----------------
|
||||
|
||||
|
@ -66,6 +77,5 @@ 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 ``Remove Duplicate Records`` in the
|
||||
duplicate of another if its data in the Callsign, Date, and Time fields are the same. Click ``Remove Duplicate Records`` in the
|
||||
``Records`` menu.
|
||||
|
|
|
@ -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
|
||||
============== ===========
|
||||
|
|
@ -15,13 +15,15 @@ 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 ``Connect to Telnet Server`` button and enter the DX server
|
||||
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. Once connected, the server output will appear in the DX
|
||||
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 and clicking the
|
||||
adjacent ``Send Command`` button.
|
||||
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
|
||||
|
@ -29,18 +31,20 @@ adjacent ``Send Command`` button.
|
|||
|
||||
The DX cluster frame.
|
||||
|
||||
Grey line
|
||||
World map
|
||||
---------
|
||||
|
||||
The grey line tool (see figure: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.
|
||||
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.
|
||||
|
||||
.. _figure:grey_line:
|
||||
.. figure:: images/grey_line.png
|
||||
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 grey line tool.
|
||||
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
|
||||
------
|
||||
|
|
962
pyqso/adif.py
|
@ -1,6 +1,6 @@
|
|||
#!/usr/bin/env python
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (C) 2013 Christian T. Jacobs.
|
||||
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
|
||||
|
||||
# This file is part of PyQSO.
|
||||
|
||||
|
@ -17,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, title="Error")
|
||||
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, title="Information")
|
||||
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, title="Question")
|
||||
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
|
||||
|
|
163
pyqso/awards.py
|
@ -1,6 +1,6 @@
|
|||
#!/usr/bin/env python
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (C) 2013 Christian T. Jacobs.
|
||||
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
|
||||
|
||||
# This file is part of PyQSO.
|
||||
|
||||
|
@ -17,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
|
||||
|
|
|
@ -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
|
|
@ -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
|
|
@ -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()
|
|
@ -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
|
|
@ -1,6 +1,6 @@
|
|||
#!/usr/bin/env python
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (C) 2013 Christian T. Jacobs.
|
||||
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
|
||||
|
||||
# This file is part of PyQSO.
|
||||
|
||||
|
@ -17,179 +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 unittest
|
||||
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...")
|
||||
try:
|
||||
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()
|
||||
except:
|
||||
error(parent=self.parent, message="Could not connect to the qrz.com server. Check connection to the internets?")
|
||||
return False
|
||||
|
||||
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
|
||||
""" Use qrz.com to lookup details about a particular callsign. """
|
||||
|
||||
# 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)
|
||||
def __init__(self, parent):
|
||||
""" Initialise a new callsign lookup handler.
|
||||
|
||||
return connected
|
||||
:arg parent: The parent Gtk dialog.
|
||||
"""
|
||||
self.parent = parent
|
||||
self.connection = None
|
||||
self.session_key = None
|
||||
return
|
||||
|
||||
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),
|
||||
and return the data in the dictionary called fields_and_data. """
|
||||
|
||||
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 = self.strip(full_callsign)
|
||||
else:
|
||||
callsign = full_callsign
|
||||
|
||||
# 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()
|
||||
def connect(self, username, password):
|
||||
""" Initiate a session with the qrz.com server. Hopefully this will provide a session key.
|
||||
|
||||
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
|
||||
: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...")
|
||||
|
||||
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
|
||||
# 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_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"] + ", " if len(callsign_addr1_node) > 0 else "") + callsign_addr2_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_state_node = callsign_node.getElementsByTagName('state')
|
||||
if(len(callsign_state_node) > 0):
|
||||
fields_and_data["STATE"] = callsign_state_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_country_node = callsign_node.getElementsByTagName('country')
|
||||
if(len(callsign_country_node) > 0):
|
||||
fields_and_data["COUNTRY"] = callsign_country_node[0].firstChild.nodeValue
|
||||
return connected
|
||||
|
||||
callsign_ccode_node = callsign_node.getElementsByTagName('ccode')
|
||||
if(len(callsign_ccode_node) > 0):
|
||||
fields_and_data["DXCC"] = callsign_ccode_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_cqzone_node = callsign_node.getElementsByTagName('cqzone')
|
||||
if(len(callsign_cqzone_node) > 0):
|
||||
fields_and_data["CQZ"] = callsign_cqzone_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_ituzone_node = callsign_node.getElementsByTagName('ituzone')
|
||||
if(len(callsign_ituzone_node) > 0):
|
||||
fields_and_data["ITUZ"] = callsign_ituzone_node[0].firstChild.nodeValue
|
||||
logging.debug("Looking up callsign. The full callsign (with a prefix and/or suffix) is %s." % 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[0].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
|
||||
# Remove any prefix or suffix from the callsign before performing the lookup.
|
||||
if(ignore_prefix_suffix):
|
||||
callsign = strip(full_callsign)
|
||||
else:
|
||||
callsign = full_callsign
|
||||
|
||||
def strip(self, full_callsign):
|
||||
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):
|
||||
# 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):
|
||||
|
||||
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))
|
||||
# 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 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:
|
||||
logging.debug("No prefix or suffix found. Callsign to lookup is %s." % callsign)
|
||||
|
||||
else:
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
callsign = full_callsign
|
||||
return callsign
|
||||
|
||||
class TestCallsignLookup(unittest.TestCase):
|
||||
""" The unit tests for the CallsignLookup class. """
|
||||
|
||||
def setUp(self):
|
||||
""" Set up the CallsignLookup object needed for the unit tests. """
|
||||
self.cl = CallsignLookup(parent=None)
|
||||
|
||||
def test_strip(self):
|
||||
callsign = "EA3/MYCALL/MM"
|
||||
assert self.cl.strip(callsign) == "MYCALL"
|
||||
|
||||
def test_strip_prefix_only(self):
|
||||
callsign = "EA3/MYCALL"
|
||||
assert self.cl.strip(callsign) == "MYCALL"
|
||||
|
||||
def test_strip_suffix_only(self):
|
||||
callsign = "MYCALL/M"
|
||||
assert self.cl.strip(callsign) == "MYCALL"
|
||||
|
||||
def test_strip_no_prefix_or_suffix(self):
|
||||
callsign = "MYCALL"
|
||||
assert self.cl.strip(callsign) == "MYCALL"
|
||||
|
||||
if(__name__ == '__main__'):
|
||||
unittest.main()
|
||||
except ValueError:
|
||||
callsign = full_callsign
|
||||
return callsign
|
||||
|
|
|
@ -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
|
|
@ -1,6 +1,6 @@
|
|||
#!/usr/bin/env python
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (C) 2013 Christian T. Jacobs.
|
||||
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
|
||||
|
||||
# This file is part of PyQSO.
|
||||
|
||||
|
@ -17,166 +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()
|
||||
try:
|
||||
text = text.replace(u"\u0007", "") # Remove the BEL Unicode character from the end of the line
|
||||
except UnicodeDecodeError as e:
|
||||
# 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)
|
||||
|
||||
# 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
|
||||
|
||||
# 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):
|
||||
|
||||
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
|
||||
|
|
|
@ -1,84 +0,0 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (C) 2013 Christian T. 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
|
||||
logging.debug("Using version %s of matplotlib." % (matplotlib.__version__))
|
||||
matplotlib.use('Agg')
|
||||
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, or the version of the non-standard module is too old. 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.
|
||||
|
596
pyqso/log.py
|
@ -1,6 +1,6 @@
|
|||
#!/usr/bin/env python
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (C) 2013 Christian T. Jacobs.
|
||||
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
|
||||
|
||||
# This file is part of PyQSO.
|
||||
|
||||
|
@ -17,372 +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):
|
||||
""" Remove any duplicate records from the log. Return the total number of duplicates, and the number of duplicates that were successfully removed. Hopefully these will be the same. """
|
||||
duplicates = self.get_duplicates()
|
||||
if(len(duplicates) == 0):
|
||||
return (0, 0) # Nothing to do here.
|
||||
def remove_duplicates(self):
|
||||
""" Remove any duplicate records from the log.
|
||||
|
||||
removed = 0 # Count the number of records that are removed. Hopefully this will be the same as len(duplicates).
|
||||
while removed != len(duplicates): # Unfortunately, in certain cases, extra passes may be necessary to ensure that all duplicates are removed.
|
||||
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.
|
||||
: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.
|
||||
|
||||
assert(removed == len(duplicates))
|
||||
return (len(duplicates), removed)
|
||||
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.
|
||||
|
||||
def get_duplicates(self):
|
||||
""" Find the duplicates in the log, based on the CALL, QSO_DATE, TIME_ON, FREQ and MODE fields, and return a list of their row IDs. """
|
||||
duplicates = []
|
||||
try:
|
||||
with self.connection:
|
||||
c = self.connection.cursor()
|
||||
c.execute(
|
||||
"""SELECT rowid FROM %s WHERE rowid NOT IN
|
||||
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.
|
||||
except (sqlite.Error, IndexError) as e:
|
||||
logging.exception(e)
|
||||
return duplicates
|
||||
|
||||
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:
|
||||
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
|
||||
|
||||
def get_record_by_index(self, index):
|
||||
""" Return a record with a given index in the log.
|
||||
|
||||
: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
|
||||
|
||||
def test_log_get_duplicates(self):
|
||||
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.
|
||||
|
||||
if(__name__ == '__main__'):
|
||||
unittest.main()
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
#!/usr/bin/env python
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (C) 2013 Christian T. Jacobs.
|
||||
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
|
||||
|
||||
# This file is part of PyQSO.
|
||||
|
||||
|
@ -17,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()
|
||||
|
|
2020
pyqso/logbook.py
349
pyqso/menu.py
|
@ -1,8 +1,8 @@
|
|||
#!/usr/bin/env python
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (C) 2012 Christian T. 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
|
||||
|
@ -17,253 +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)
|
||||
""" The menu bar along the top of the main window. """
|
||||
|
||||
# Create logbook
|
||||
mitem_connect = Gtk.ImageMenuItem("Create a New Logbook...")
|
||||
icon = Gtk.Image()
|
||||
icon.set_from_stock(Gtk.STOCK_NEW, Gtk.IconSize.MENU)
|
||||
mitem_connect.set_image(icon)
|
||||
mitem_connect.connect("activate", parent.logbook.new)
|
||||
subm_logbook.append(mitem_connect)
|
||||
self.items["NEW_LOGBOOK"] = mitem_connect
|
||||
|
||||
# Open logbook
|
||||
mitem_connect = Gtk.ImageMenuItem("Open an 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
|
||||
def __init__(self, application):
|
||||
""" Set up all menu items and connect to the various functions.
|
||||
|
||||
# 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
|
||||
:arg application: The PyQSO application containing the main Gtk window, etc.
|
||||
"""
|
||||
|
||||
subm_logbook.append(Gtk.SeparatorMenuItem())
|
||||
self.application = application
|
||||
self.builder = self.application.builder
|
||||
|
||||
# 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
|
||||
# Collect Gtk menu items and connect signals.
|
||||
self.items = {}
|
||||
|
||||
# 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
|
||||
# New logbook
|
||||
self.items["NEW_LOGBOOK"] = self.builder.get_object("mitem_new_logbook")
|
||||
self.items["NEW_LOGBOOK"].connect("activate", self.application.logbook.new)
|
||||
|
||||
subm_logbook.append(Gtk.SeparatorMenuItem())
|
||||
# Open logbook
|
||||
self.items["OPEN_LOGBOOK"] = self.builder.get_object("mitem_open_logbook")
|
||||
self.items["OPEN_LOGBOOK"].connect("activate", self.application.logbook.open)
|
||||
|
||||
# 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
|
||||
# Close logbook
|
||||
self.items["CLOSE_LOGBOOK"] = self.builder.get_object("mitem_close_logbook")
|
||||
self.items["CLOSE_LOGBOOK"].connect("activate", self.application.logbook.close)
|
||||
|
||||
# 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())
|
||||
# New log
|
||||
self.items["NEW_LOG"] = self.builder.get_object("mitem_new_log")
|
||||
self.items["NEW_LOG"].connect("activate", self.application.logbook.new_log)
|
||||
|
||||
# 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
|
||||
# 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)
|
||||
|
||||
subm_logbook.append(Gtk.SeparatorMenuItem())
|
||||
# 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)
|
||||
|
||||
# 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
|
||||
# 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_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
|
||||
# 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_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 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_toolbox = Gtk.CheckMenuItem("Toolbox")
|
||||
config = ConfigParser.ConfigParser()
|
||||
have_config = (config.read(os.path.expanduser('~/.pyqso.ini')) != [])
|
||||
(section, option) = ("general", "show_toolbox")
|
||||
if(have_config and config.has_option(section, option)):
|
||||
mitem_toolbox.set_active(config.get(section, option) == "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
|
||||
# Print log
|
||||
self.items["PRINT_LOG"] = self.builder.get_object("mitem_print_log")
|
||||
self.items["PRINT_LOG"].connect("activate", self.application.logbook.print_log)
|
||||
|
||||
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
|
||||
|
||||
# Preferences
|
||||
self.items["PREFERENCES"] = self.builder.get_object("mitem_preferences")
|
||||
self.items["PREFERENCES"].connect("activate", self.application.show_preferences)
|
||||
|
||||
###### 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)
|
||||
# Quit
|
||||
self.items["QUIT"] = self.builder.get_object("mitem_quit")
|
||||
self.items["QUIT"].connect("activate", Gtk.main_quit)
|
||||
|
||||
self.set_logbook_item_sensitive(True)
|
||||
self.set_log_items_sensitive(False)
|
||||
self.set_record_items_sensitive(False)
|
||||
|
||||
logging.debug("Menu bar ready!")
|
||||
# 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)
|
||||
|
||||
return
|
||||
|
||||
def set_logbook_item_sensitive(self, sensitive):
|
||||
logging.debug("Setting the 'Create/Open Logbook' menu item's sensitivity to: %s..." % sensitive)
|
||||
self.items["NEW_LOGBOOK"].set_sensitive(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
|
||||
# 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_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
|
||||
# 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)
|
||||
|
||||
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
|
||||
# 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
|
||||
|
|
|
@ -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
|
|
@ -1,6 +1,6 @@
|
|||
#!/usr/bin/env python
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (C) 2013 Christian T. Jacobs.
|
||||
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
|
||||
|
||||
# This file is part of PyQSO.
|
||||
|
||||
|
@ -17,398 +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, MODES
|
||||
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.records = RecordsPage()
|
||||
self.preferences.insert_page(self.records, Gtk.Label("Records"), 2)
|
||||
logging.debug("Setting up the preferences dialog...")
|
||||
|
||||
self.vbox.pack_start(self.preferences, True, True, 2)
|
||||
self.show_all()
|
||||
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")
|
||||
|
||||
logging.debug("Preferences dialog ready!")
|
||||
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)
|
||||
|
||||
return
|
||||
self.dialog.show_all()
|
||||
|
||||
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()
|
||||
records_data = self.records.get_data()
|
||||
logging.debug("Preferences dialog ready!")
|
||||
|
||||
config = ConfigParser.ConfigParser()
|
||||
return
|
||||
|
||||
# General
|
||||
config.add_section("general")
|
||||
for key in general_data.keys():
|
||||
config.set("general", key.lower(), general_data[key])
|
||||
def commit(self):
|
||||
""" Commit the user preferences to the configuration file. """
|
||||
|
||||
# View
|
||||
config.add_section("view")
|
||||
for key in view_data.keys():
|
||||
config.set("view", key.lower(), view_data[key])
|
||||
logging.debug("Committing 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])
|
||||
|
||||
# Records
|
||||
config.add_section("records")
|
||||
for key in records_data.keys():
|
||||
config.set("records", key.lower(), records_data[key])
|
||||
config = configparser.ConfigParser()
|
||||
|
||||
with open(os.path.expanduser('~/.pyqso.ini'), 'w') as f:
|
||||
config.write(f)
|
||||
# General
|
||||
config.add_section("general")
|
||||
for key in list(self.general.data.keys()):
|
||||
config.set("general", key.lower(), str(self.general.data[key]))
|
||||
|
||||
return
|
||||
# View
|
||||
config.add_section("view")
|
||||
for key in list(self.view.data.keys()):
|
||||
config.set("view", key.lower(), str(self.view.data[key]))
|
||||
|
||||
class GeneralPage(Gtk.VBox):
|
||||
|
||||
def __init__(self):
|
||||
logging.debug("Setting up the General page of the preferences dialog...")
|
||||
# Records
|
||||
config.add_section("records")
|
||||
for key in list(self.records.data.keys()):
|
||||
config.set("records", key.lower(), str(self.records.data[key]))
|
||||
|
||||
Gtk.VBox.__init__(self, spacing=2)
|
||||
# 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]))
|
||||
|
||||
# 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')) != [])
|
||||
# Hamlib
|
||||
config.add_section("hamlib")
|
||||
for key in list(self.hamlib.data.keys()):
|
||||
config.set("hamlib", key.lower(), str(self.hamlib.data[key]))
|
||||
|
||||
self.sources = {}
|
||||
# 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]))
|
||||
|
||||
frame = Gtk.Frame()
|
||||
frame.set_label("Startup")
|
||||
hbox = Gtk.HBox()
|
||||
self.sources["SHOW_TOOLBOX"] = Gtk.CheckButton("Show toolbox by default")
|
||||
(section, option) = ("general", "show_toolbox")
|
||||
if(have_config and config.has_option(section, option)):
|
||||
self.sources["SHOW_TOOLBOX"].set_active(config.get(section, option) == "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)
|
||||
# Write the preferences to file.
|
||||
with open(os.path.expanduser(PREFERENCES_FILE), 'w') as f:
|
||||
config.write(f)
|
||||
|
||||
logging.debug("General page of the preferences dialog ready!")
|
||||
return
|
||||
return
|
||||
|
||||
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()
|
||||
return data
|
||||
|
||||
class ViewPage(Gtk.VBox):
|
||||
|
||||
def __init__(self):
|
||||
logging.debug("Setting up the View page of the preferences dialog...")
|
||||
class GeneralPage:
|
||||
|
||||
Gtk.VBox.__init__(self, spacing=2)
|
||||
""" The section of the preferences dialog containing general preferences. """
|
||||
|
||||
config = ConfigParser.ConfigParser()
|
||||
have_config = (config.read(os.path.expanduser('~/.pyqso.ini')) != [])
|
||||
def __init__(self, parent, builder):
|
||||
""" Set up the General page of the Preferences dialog. """
|
||||
|
||||
self.sources = {}
|
||||
self.parent = parent
|
||||
self.builder = builder
|
||||
self.sources = {}
|
||||
|
||||
# Visible fields frame
|
||||
frame = Gtk.Frame()
|
||||
frame.set_label("Visible fields")
|
||||
# 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) != [])
|
||||
|
||||
# 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 ])
|
||||
# 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)
|
||||
|
||||
# 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)
|
||||
|
||||
# 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())):
|
||||
button.set_active(config.get("view", field_name.lower()) == "True")
|
||||
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)
|
||||
frame.add(hbox)
|
||||
self.pack_start(frame, 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
|
||||
|
||||
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...")
|
||||
|
||||
Gtk.VBox.__init__(self, spacing=2)
|
||||
|
||||
config = ConfigParser.ConfigParser()
|
||||
have_config = (config.read(os.path.expanduser('~/.pyqso.ini')) != [])
|
||||
|
||||
self.sources = {}
|
||||
|
||||
frame = Gtk.Frame()
|
||||
frame.set_label("Hamlib support")
|
||||
|
||||
vbox_inner = Gtk.VBox(spacing=2)
|
||||
|
||||
self.sources["AUTOFILL"] = Gtk.CheckButton("Auto-fill Frequency field")
|
||||
(section, option) = ("hamlib", "autofill")
|
||||
if(have_config and config.has_option(section, option)):
|
||||
self.sources["AUTOFILL"].set_active(config.get(section, option) == "True")
|
||||
else:
|
||||
self.sources["AUTOFILL"].set_active(False)
|
||||
vbox_inner.pack_start(self.sources["AUTOFILL"], False, False, 2)
|
||||
|
||||
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)
|
||||
|
||||
# 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"] = Gtk.ComboBoxText()
|
||||
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.
|
||||
hbox_temp.pack_start(self.sources["RIG_MODEL"], True, True, 2)
|
||||
vbox_inner.pack_start(hbox_temp, False, False, 2)
|
||||
|
||||
# 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()
|
||||
(section, option) = ("hamlib", "rig_pathname")
|
||||
if(have_config and config.has_option(section, option)):
|
||||
self.sources["RIG_PATHNAME"].set_text(config.get(section, option))
|
||||
hbox_temp.pack_start(self.sources["RIG_PATHNAME"], True, True, 2)
|
||||
vbox_inner.pack_start(hbox_temp, False, False, 2)
|
||||
|
||||
frame.add(vbox_inner)
|
||||
self.pack_start(frame, True, True, 2)
|
||||
|
||||
logging.debug("Hamlib page of the preferences dialog ready!")
|
||||
return
|
||||
|
||||
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
|
||||
|
||||
class RecordsPage(Gtk.VBox):
|
||||
|
||||
def __init__(self):
|
||||
logging.debug("Setting up the Records page of the preferences dialog...")
|
||||
|
||||
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(os.path.expanduser('~/.pyqso.ini')) != [])
|
||||
|
||||
self.sources = {}
|
||||
|
||||
# Autocomplete frame
|
||||
frame = Gtk.Frame()
|
||||
frame.set_label("Autocomplete")
|
||||
vbox = Gtk.VBox()
|
||||
self.sources["AUTOCOMPLETE_BAND"] = Gtk.CheckButton("Autocomplete the Band field")
|
||||
(section, option) = ("records", "autocomplete_band")
|
||||
if(have_config and config.has_option(section, option)):
|
||||
self.sources["AUTOCOMPLETE_BAND"].set_active(config.get(section, option) == "True")
|
||||
else:
|
||||
self.sources["AUTOCOMPLETE_BAND"].set_active(True)
|
||||
vbox.pack_start(self.sources["AUTOCOMPLETE_BAND"], False, False, 2)
|
||||
|
||||
self.sources["USE_UTC"] = Gtk.CheckButton("Use UTC when autocompleting the Date and Time")
|
||||
(section, option) = ("records", "use_utc")
|
||||
if(have_config and config.has_option(section, option)):
|
||||
self.sources["USE_UTC"].set_active(config.get(section, option) == "True")
|
||||
else:
|
||||
self.sources["USE_UTC"].set_active(True)
|
||||
vbox.pack_start(self.sources["USE_UTC"], False, False, 2)
|
||||
|
||||
frame.add(vbox)
|
||||
self.pack_start(frame, False, False, 2)
|
||||
@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
|
||||
|
||||
|
||||
## Default values frame
|
||||
frame = Gtk.Frame()
|
||||
frame.set_label("Default values")
|
||||
vbox = Gtk.VBox()
|
||||
|
||||
# Mode
|
||||
hbox_temp = Gtk.HBox()
|
||||
label = Gtk.Label("Mode: ")
|
||||
label.set_width_chars(17)
|
||||
label.set_alignment(0, 0.5)
|
||||
hbox_temp.pack_start(label, False, False, 2)
|
||||
|
||||
self.sources["DEFAULT_MODE"] = Gtk.ComboBoxText()
|
||||
for mode in MODES:
|
||||
self.sources["DEFAULT_MODE"].append_text(mode)
|
||||
(section, option) = ("records", "default_mode")
|
||||
if(have_config and config.has_option(section, option)):
|
||||
self.sources["DEFAULT_MODE"].set_active(MODES.index(config.get(section, option)))
|
||||
else:
|
||||
self.sources["DEFAULT_MODE"].set_active(MODES.index(""))
|
||||
hbox_temp.pack_start(self.sources["DEFAULT_MODE"], False, False, 2)
|
||||
vbox.pack_start(hbox_temp, False, False, 2)
|
||||
class RecordsPage:
|
||||
|
||||
# Power
|
||||
hbox_temp = Gtk.HBox()
|
||||
label = Gtk.Label("TX Power (W): ")
|
||||
label.set_width_chars(17)
|
||||
label.set_alignment(0, 0.5)
|
||||
hbox_temp.pack_start(label, False, False, 2)
|
||||
|
||||
self.sources["DEFAULT_POWER"] = Gtk.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("")
|
||||
hbox_temp.pack_start(self.sources["DEFAULT_POWER"], False, False, 2)
|
||||
vbox.pack_start(hbox_temp, False, False, 2)
|
||||
|
||||
frame.add(vbox)
|
||||
self.pack_start(frame, False, False, 2)
|
||||
|
||||
|
||||
# Callsign lookup frame
|
||||
frame = Gtk.Frame()
|
||||
frame.set_label("Callsign lookup")
|
||||
vbox = Gtk.VBox()
|
||||
""" The section of the preferences dialog containing record-related preferences. """
|
||||
|
||||
subframe = Gtk.Frame()
|
||||
subframe.set_label("Login details (qrz.com)")
|
||||
inner_vbox = Gtk.VBox()
|
||||
def __init__(self, parent, builder):
|
||||
""" Set up the Record page of the Preferences dialog. """
|
||||
|
||||
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()
|
||||
(section, option) = ("records", "qrz_username")
|
||||
if(have_config and config.has_option(section, option)):
|
||||
self.sources["QRZ_USERNAME"].set_text(config.get(section, option))
|
||||
hbox.pack_start(self.sources["QRZ_USERNAME"], False, False, 2)
|
||||
inner_vbox.pack_start(hbox, False, False, 2)
|
||||
self.parent = parent
|
||||
self.builder = builder
|
||||
self.sources = {}
|
||||
|
||||
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.
|
||||
(section, option) = ("records", "qrz_password")
|
||||
if(have_config and config.has_option(section, option)):
|
||||
self.sources["QRZ_PASSWORD"].set_text(base64.b64decode(config.get(section, option)))
|
||||
hbox.pack_start(self.sources["QRZ_PASSWORD"], False, False, 2)
|
||||
inner_vbox.pack_start(hbox, False, False, 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) != [])
|
||||
|
||||
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)
|
||||
# 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)
|
||||
|
||||
subframe.add(inner_vbox)
|
||||
vbox.pack_start(subframe, 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)
|
||||
|
||||
self.sources["IGNORE_PREFIX_SUFFIX"] = Gtk.CheckButton("Ignore callsign prefixes and/or suffixes")
|
||||
(section, option) = ("records", "ignore_prefix_suffix")
|
||||
if(have_config and config.has_option(section, option)):
|
||||
self.sources["IGNORE_PREFIX_SUFFIX"].set_active(config.get(section, option) == "True")
|
||||
else:
|
||||
self.sources["IGNORE_PREFIX_SUFFIX"].set_active(True)
|
||||
vbox.pack_start(self.sources["IGNORE_PREFIX_SUFFIX"], False, False, 2)
|
||||
|
||||
frame.add(vbox)
|
||||
self.pack_start(frame, False, False, 2)
|
||||
|
||||
logging.debug("Records page of the preferences dialog ready!")
|
||||
return
|
||||
# Default values
|
||||
|
||||
def get_data(self):
|
||||
logging.debug("Retrieving data from the Records page of the preferences dialog...")
|
||||
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_POWER"] = self.sources["DEFAULT_POWER"].get_text()
|
||||
|
||||
data["QRZ_USERNAME"] = self.sources["QRZ_USERNAME"].get_text()
|
||||
data["QRZ_PASSWORD"] = base64.b64encode(self.sources["QRZ_PASSWORD"].get_text())
|
||||
data["IGNORE_PREFIX_SUFFIX"] = self.sources["IGNORE_PREFIX_SUFFIX"].get_active()
|
||||
return data
|
||||
# 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)
|
||||
|
||||
# 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))
|
||||
|
||||
# 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("")
|
||||
|
||||
# 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"))
|
||||
|
||||
# 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(""))
|
||||
|
||||
# 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
|
||||
|
|
|
@ -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
|
Przed Szerokość: | Wysokość: | Rozmiar: 667 B Po Szerokość: | Wysokość: | Rozmiar: 667 B |
Przed Szerokość: | Wysokość: | Rozmiar: 47 KiB Po Szerokość: | Wysokość: | Rozmiar: 47 KiB |
Przed Szerokość: | Wysokość: | Rozmiar: 6.8 KiB Po Szerokość: | Wysokość: | Rozmiar: 6.8 KiB |
|
@ -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
|
|
@ -1,6 +1,6 @@
|
|||
#!/usr/bin/env python
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (C) 2013 Christian T. Jacobs.
|
||||
# Copyright (C) 2017 Christian Thomas Jacobs.
|
||||
|
||||
# This file is part of PyQSO.
|
||||
|
||||
|
@ -17,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()
|
||||
|
|
145
pyqso/toolbar.py
|
@ -1,6 +1,6 @@
|
|||
#!/usr/bin/env python
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (C) 2013 Christian T. Jacobs.
|
||||
# Copyright (C) 2013-2017 Christian Thomas Jacobs.
|
||||
|
||||
# This file is part of PyQSO.
|
||||
|
||||
|
@ -17,113 +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 logbook
|
||||
icon = Gtk.Image()
|
||||
icon.set_from_stock(Gtk.STOCK_NEW, Gtk.IconSize.BUTTON)
|
||||
button = Gtk.Button()
|
||||
button.add(icon)
|
||||
button.set_tooltip_text('Create a New Logbook')
|
||||
button.connect("clicked", parent.logbook.new)
|
||||
self.pack_start(button, False, False, 0)
|
||||
self.buttons["NEW_LOGBOOK"] = button
|
||||
|
||||
# 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 an 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["NEW_LOGBOOK"].set_sensitive(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
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
#!/usr/bin/env python
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (C) 2013 Christian T. Jacobs.
|
||||
# Copyright (C) 2013-2018 Christian Thomas Jacobs.
|
||||
|
||||
# This file is part of PyQSO.
|
||||
|
||||
|
@ -17,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
|
||||
|
|
|
@ -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.
|
|
@ -0,0 +1,6 @@
|
|||
numpy
|
||||
matplotlib>=1.3.0
|
||||
cairocffi
|
||||
cartopy>=0.16.0
|
||||
sphinx
|
||||
geocoder
|
36
setup.py
|
@ -1,6 +1,6 @@
|
|||
#!/usr/bin/env python
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (C) 2013 Christian T. Jacobs.
|
||||
# Copyright (C) 2013-2018 Christian Thomas Jacobs.
|
||||
|
||||
# This file is part of PyQSO.
|
||||
|
||||
|
@ -17,17 +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.2',
|
||||
description='A contact logging tool for amateur radio operators.',
|
||||
author='Christian T. Jacobs',
|
||||
author_email='c.jacobs10@imperial.ac.uk',
|
||||
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
|
||||
)
|
||||
|
|
|
@ -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>
|
|
@ -0,0 +1,2 @@
|
|||
Some test ADI data.<eoh>
|
||||
<call:64>ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ<eor>
|
|
@ -0,0 +1,2 @@
|
|||
Some test ADI data.<eoh>
|
||||
<call:4>test<eor>
|
|
@ -0,0 +1 @@
|
|||
Some test ADI data.<eoh>
|
|
@ -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>
|
|
@ -0,0 +1 @@
|
|||
<call:4>TEST<band:3>40m<mode:2>CW<qso_date:8:d>20130322<time_on:4>1955<eor>
|
|
@ -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.
|
|
@ -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()
|
|
@ -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()
|
|
@ -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()
|
|
@ -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()
|
|
@ -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()
|
|
@ -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()
|
|
@ -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()
|
|
@ -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()
|
|
@ -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()
|
|
@ -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()
|
|
@ -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()
|
|
@ -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()
|
|
@ -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()
|
|
@ -0,0 +1,3 @@
|
|||
[flake8]
|
||||
ignore = E501,F403,E226,E402,W503
|
||||
exclude = .git,__pycache__,build
|