├── .gitignore
├── LICENSE
├── README.md
├── docs
├── newt.py
├── snack_lib.md
├── test_checkboxtree.py
└── usage.md
├── images
├── 5.jpg
└── test.jpg
├── src
├── config.py
├── py_menu.py
├── three_page.py
└── w_lib
│ ├── __init__.py
│ ├── blog.py
│ ├── http_util.py
│ └── pysnack
│ ├── __init__.py
│ ├── _snackmodule.so
│ ├── snack.py
│ └── snack_lib.py
└── tools
├── install_lib.sh
└── w_lib64
├── libnewt.so.0.52
├── libnewt.so.0.52.11
├── libslang.so.2
└── libslang.so.2.2.1
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | #*.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | env/
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 |
27 | # PyInstaller
28 | # Usually these files are written by a python script from a template
29 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
30 | *.manifest
31 | *.spec
32 |
33 | # Installer logs
34 | pip-log.txt
35 | pip-delete-this-directory.txt
36 |
37 | # Unit test / coverage reports
38 | htmlcov/
39 | .tox/
40 | .coverage
41 | .coverage.*
42 | .cache
43 | nosetests.xml
44 | coverage.xml
45 | *,cover
46 | .hypothesis/
47 |
48 | # Translations
49 | *.mo
50 | *.pot
51 |
52 | # Django stuff:
53 | *.log
54 | local_settings.py
55 |
56 | # Flask stuff:
57 | instance/
58 | .webassets-cache
59 |
60 | # Scrapy stuff:
61 | .scrapy
62 |
63 | # Sphinx documentation
64 | docs/_build/
65 |
66 | # PyBuilder
67 | target/
68 |
69 | # IPython Notebook
70 | .ipynb_checkpoints
71 |
72 | # pyenv
73 | .python-version
74 |
75 | # celery beat schedule file
76 | celerybeat-schedule
77 |
78 | # dotenv
79 | .env
80 |
81 | # virtualenv
82 | venv/
83 | ENV/
84 |
85 | # Spyder project settings
86 | .spyderproject
87 |
88 | # Rope project settings
89 | .ropeproject
90 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # py_menu
2 |
3 |
4 |
5 | * [1 背景和目标](#1-背景和目标)
6 | * [1.1 背景](#11-背景)
7 | * [1.2 目标](#12-目标)
8 | * [2 名词解释](#2-名词解释)
9 | * [3 假设和依赖](#3-假设和依赖)
10 | * [3.1 依赖](#31-依赖)
11 | * [4 使用](#4-使用)
12 | * [5 相关项目](#5-相关项目)
13 | * [5.1 类似项目](#51-类似项目)
14 | * [5.2 使用了 py_menu 的项目](#52-使用了-py_menu-的项目)
15 | * [6 Version](#6-version)
16 | * [7 参加步骤](#7-参加步骤)
17 | * [8 小额捐款](#8-小额捐款)
18 |
19 |
20 |
21 | 更简单操作和使用的终端菜单及管理
22 |
23 | 
24 |
25 | ## 1 背景和目标
26 |
27 | ### 1.1 背景
28 |
29 | > * 平台可能会管理成千上万个实例,但什么来管理平台尼,需要有个程序来对特定平台的服务进行管理操作
30 | > * 管理常用操作程序
31 |
32 | ### 1.2 目标
33 |
34 | > * 框架与逻辑代码分离,备份代码时只需要备份主要逻辑代码即可
35 |
36 | ## 2 名词解释
37 |
38 | > * newt: 全称是:Not Erik’s Windowing Toolkit, 用在 RatHat 的 Linux 发行版本 (RHEL, Fedora 和 CentOS) 的安装程序项目 Anaconda 中
39 | > * snack: 官方 newt 库中还提供了 Python 封装库,名称为 snack(Snack 是 python 对 newt 的接口)
40 | > * [snack 前世今生](https://github.com/meetbill/py_menu/wiki)
41 | > * [snack 库提交历史](https://pagure.io/newt/history/snack.py?identifier=master)
42 |
43 | ## 3 假设和依赖
44 |
45 | ### 3.1 依赖
46 |
47 | 系统依赖: Centos 6.X 及以上
48 |
49 | ## 4 使用
50 |
51 | > * [py_menu 使用手册](docs/usage.md)
52 |
53 |
54 | 三层菜单点击确定后返回以下结果,是个 json
55 |
56 | 日志记录在 ./log/pymenu.log
57 | ```
58 | yes {'entry_test2': '0', 'entry_test3': '127.0.0.1', 'entry_test1': '0', 'radios': 'radios2', 'checks_list': ['checks4']}
59 | ```
60 | 点击 cancel 时,输出 no
61 |
62 | ## 5 相关项目
63 |
64 | ### 5.1 类似项目
65 | > * shell 终端菜单 --[shell_menu](https://github.com/meetbill/shell_menu.git)
66 |
67 | ### 5.2 使用了 py_menu 的项目
68 | > * MegaCli 终端界面管理工具 [Megatui](https://github.com/meetbill/MegaTUI)
69 |
70 | ## 6 Version
71 |
72 | * V1.2.4,2020-12-19 提醒页面移动到 snack_lib 库中
73 | * V1.2.3,2020-12-17 三级输出界面可接收参数,方便复用三级输出界面
74 | * V1.2.2,2019-02-18 (1) 更改日志方式;(2) 添加 Centos6.x `_snackmodule.so`
75 | * V1.2.1,2017-03-21 添加三级输出界面
76 | * V1.2.0,2017-03-17 将三级配置界面独立出来为 three_page.py,可以单独调试此页面
77 | * V1.1.1,2016-12-19 修复 bug,程序会保留二级菜单选项位置,假如从一级目录重新进入时,二级菜单选择位置没有报异常 bug
78 | * V1.1.0,2016-09-30 更新 doc,同时重新更新程序结构,使得更方便编写程序
79 | * V1.0.2,2016-09-29 添加日志,输出到 /var/log/menu_tool/acc.log 中
80 | * V1.0.1,2016-09-25 First edit
81 |
82 | ## 7 参加步骤
83 |
84 | * 在 GitHub 上 `fork` 到自己的仓库,然后 `clone` 到本地,并设置用户信息。
85 | ```
86 | $ git clone https://github.com/meetbill/py_menu.git
87 | $ cd py_menu
88 | $ git config user.name "yourname"
89 | $ git config user.email "your email"
90 | ```
91 | * 修改代码后提交,并推送到自己的仓库。
92 | ```
93 | $ #do some change on the content
94 | $ git commit -am "Fix issue #1: change helo to hello"
95 | $ git push
96 | ```
97 | * 在 GitHub 网站上提交 pull request。
98 | * 定期使用项目仓库内容更新自己仓库内容。
99 | ```
100 | $ git remote add upstream https://github.com/meetbill/py_menu.git
101 | $ git fetch upstream
102 | $ git checkout master
103 | $ git rebase upstream/master
104 | $ git push -f origin master
105 | ```
106 | ## 8 小额捐款
107 |
108 | 如果你觉得 py_menu 对你有帮助,可以对作者进行小额捐款(支付宝)
109 |
110 | 
111 |
--------------------------------------------------------------------------------
/docs/newt.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | from snack import *
4 |
5 |
6 | def help(screen, text):
7 | raise ValueError, "foo"
8 | ButtonChoiceWindow(screen, "Help", text, help="Help on help")
9 |
10 |
11 | t = TextboxReflowed(25, "Some text which needs to be wrapped at a good place.")
12 | li = Listbox(5, width=20, returnExit=1)
13 | li.append("First", "f")
14 | li.append("Second", "s")
15 | li.insert("Another", "a", "f")
16 | li.delete("a")
17 | ct = CheckboxTree(5, scroll=1)
18 | ct.append("Colors")
19 | ct.addItem("Red", (0, snackArgs['append']), "red item key")
20 | ct.addItem("Yellow", (0, snackArgs['append']))
21 | ct.addItem("Blue", (0, snackArgs['append']))
22 | ct.append("Flavors")
23 | ct.addItem("Vanilla", (1, snackArgs['append']))
24 | ct.addItem("Chocolate", (1, snackArgs['append']))
25 | ct.addItem("Stawberry", (1, snackArgs['append']))
26 | ct.append("Numbers")
27 | ct.addItem("1", (2, snackArgs['append']))
28 | ct.addItem("2", (2, snackArgs['append']))
29 | ct.addItem("3", (2, snackArgs['append']))
30 | ct.append("Names")
31 | ct.addItem("Matt", (3, snackArgs['append']))
32 | ct.addItem("Shawn", (3, snackArgs['append']))
33 | ct.addItem("Wilson", (3, snackArgs['append']))
34 | ct.append("Months")
35 | ct.addItem("February", (4, snackArgs['append']))
36 | ct.addItem("August", (4, snackArgs['append']))
37 | ct.addItem("September", (4, snackArgs['append']))
38 | ct.append("Events")
39 | ct.addItem("Christmas", (5, snackArgs['append']))
40 | ct.addItem("Labor Day", (5, snackArgs['append']))
41 | ct.addItem("My Vacation", (5, snackArgs['append']))
42 | b = Button("Button")
43 | e = Entry(15, "Entry")
44 | l = Label("label")
45 | cb = Checkbox("checkbox")
46 | r1 = SingleRadioButton("Radio 1", None, 1)
47 | r2 = SingleRadioButton("Radio 2", r1)
48 |
49 |
50 | def something():
51 | print
52 | hello
53 |
54 |
55 | screen = SnackScreen()
56 |
57 | screen.helpCallback(help)
58 |
59 | foo = EntryWindow(screen, 'Title', 'This is some text for the entry window',
60 | ['prompt', 'more', 'info'])
61 |
62 | lbcw = ListboxChoiceWindow(screen, 'Title 2',
63 | 'Choose one item from the list below:',
64 | ('One', 'Two', 'Three', 'Four', 'Five'), default=2,
65 | help="Help for a listbox")
66 |
67 | sg = Grid(2, 3)
68 | sg.setField(b, 0, 0, anchorLeft=1)
69 | sg.setField(e, 1, 0, (1, 0, 0, 0), anchorLeft=1, anchorTop=1)
70 | sg.setField(l, 0, 1, (0, 1, 0, 0), anchorLeft=1)
71 | sg.setField(cb, 1, 1, (1, 1, 0, 0), anchorLeft=1)
72 | sg.setField(r1, 0, 2, (0, 0, 0, 0), anchorLeft=1)
73 | sg.setField(r2, 1, 2, (1, 0, 0, 0), anchorLeft=1)
74 |
75 | g = Grid(1, 3)
76 |
77 | g.setField(t, 0, 0)
78 | g.setField(li, 0, 1, (0, 1, 0, 1))
79 | g.setField(sg, 0, 2)
80 |
81 | g.place(1, 1)
82 |
83 | screen.gridWrappedWindow(g, "title")
84 |
85 | f = Form("This is some help")
86 | f.add(li)
87 | f.add(b)
88 | f.add(e)
89 | f.add(l)
90 | f.add(cb)
91 | f.add(r1)
92 | f.add(r2)
93 | f.add(t)
94 |
95 | res = f.run()
96 |
97 | screen.popWindow()
98 |
99 | g = GridForm(screen, "Tree", 1, 2)
100 | g.add(ct, 0, 0, (0, 0, 0, 1))
101 | g.add(Button("Ok"), 0, 1)
102 | g.runOnce()
103 |
104 | screen.finish()
105 |
106 | print
107 | "val", e.value()
108 | print
109 | "check", cb.value()
110 | print
111 | "r1", r1.selected()
112 | print
113 | "listbox", li.current()
114 | # returns a tuple of the wrapped text, the actual width, and the actual height
115 | print
116 | res
117 |
118 | print
119 | foo
120 | print
121 | 'lbcw', lbcw
122 | print
123 | "ct selected", ct.getSelection()
124 | print
125 | "ct current", ct.getCurrent()
126 |
127 |
--------------------------------------------------------------------------------
/docs/snack_lib.md:
--------------------------------------------------------------------------------
1 | ## snack_lib
2 |
3 |
4 |
5 | * [1 使用](#1-使用)
6 | * [2 功能](#2-功能)
7 | * [2.1 编辑窗口](#21-编辑窗口)
8 | * [2.1 提醒及输出窗口](#21-提醒及输出窗口)
9 |
10 |
11 |
12 | ## 1 使用
13 |
14 | snack_lib 可以独立使用
15 |
16 | ```
17 | #cd py_menu/w_lib/pysnack
18 | #python snack_lib.py
19 | ```
20 |
21 | 此库包含如下功能
22 |
23 | > * 编辑窗口(Mask 类)
24 | > * 提醒窗口及输出窗口(Snack_output 类)
25 | > * 确认窗口(conformwindows 方法)
26 |
27 | ## 2 功能
28 |
29 | ### 2.1 编辑窗口
30 | ```
31 | +-------------------------------+
32 | | +-------------+-------------+ |
33 | | | label | text | |
34 | | +-------------+-------------+ |
35 | | | label | entry | |
36 | | +-------------+-------------+-+---------subgrid
37 | | | label | checks | |
38 | | +-------------+-------------+ |
39 | | | label | radios | |
40 | | +-------------+-------------+ |
41 | | | label |checks_entry | |
42 | | +-------------+-------------+ |
43 | | +---------------------------+ |
44 | | | | |
45 | | | button +-+---------buttons
46 | | | | |
47 | | +---------------------------+ |
48 | +-------------------------------+---------gridform
49 | ```
50 |
51 | 日志会输出到 `/tmp/test_snack_lib.log`
52 | ```
53 | yes {'entry_test2': '0', 'entry_test3': '127.0.0.1', 'entry_test1': '0', 'radios': 'radios2', 'checks_list': ['checks4']}
54 | ```
55 | ### 2.1 提醒及输出窗口
56 |
57 | ```
58 | def test_Snack_output(screen):
59 | m = Snack_output(screen, "test_windows1_2", 35 )
60 | m.text("ceshijjjjjjjjjjjxdffffffffffffffff")
61 | m.text("xxxfffxxxxxxxxxxxxxx")
62 | m.text("xxxxxxxxxxxxxxxxx")
63 | m.text("xxxxxxxxxxxxxxxxx")
64 | m.text("xxxxxxxxxxxxxxxxx")
65 | m.run(43,3)
66 | ```
67 |
68 |
--------------------------------------------------------------------------------
/docs/test_checkboxtree.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | from snack import *
4 |
5 | screen = SnackScreen()
6 |
7 | g = GridForm(screen, "My Test", 1, 4)
8 | # --------------------------------------------------------------------
9 | li = Listbox(height = 3, width = 20, returnExit = 1)
10 | li.append("First", 1)
11 | li.append("Second", 2)
12 | li.append("Third", 3)
13 | g.add(li, 0, 0, padding = (0, 0, 0, 1))
14 | # --------------------------------------------------------------------
15 | rb = RadioBar(screen, (
16 | ("This", -1, 0),
17 | ("Default", "default", 1),
18 | ("That", "that", 0) ))
19 | g.add(rb, 0, 1, padding = (0, 0, 0, 1))
20 | # --------------------------------------------------------------------
21 | ct = CheckboxTree(height = 5, scroll = 1)
22 | ct.append("Colors")
23 | ct.addItem("Red", (0, snackArgs['append']))
24 | ct.addItem("Yellow", (0, snackArgs['append']))
25 | ct.addItem("Blue", (0, snackArgs['append']))
26 | ct.append("Flavors")
27 | ct.append("Numbers")
28 | ct.addItem("1", (2, snackArgs['append']))
29 | ct.addItem("2", (2, snackArgs['append']))
30 | ct.addItem("3", (2, snackArgs['append']))
31 | ct.append("Names")
32 | ct.append("Months")
33 | ct.append("Events")
34 | g.add(ct, 0, 2, padding = (0, 0, 0, 1))
35 | # --------------------------------------------------------------------
36 | bb = ButtonBar(screen, (("Ok", "ok"), ("Cancel", "cancel")))
37 | g.add(bb, 0, 3)
38 | # --------------------------------------------------------------------
39 | result = g.runOnce()
40 | screen.finish()
41 | # --------------------------------------------------------------------
42 | print result
43 | print "listbox:", li.current()
44 | print "rb:", rb.getSelection()
45 | print "bb:", bb.buttonPressed(result)
46 | print "checkboxtree:", ct.getSelection()
47 |
--------------------------------------------------------------------------------
/docs/usage.md:
--------------------------------------------------------------------------------
1 | ## py_menu 使用手册
2 |
3 |
4 |
5 | * [1 项目简介](#1-项目简介)
6 | * [1.1 已测试环境](#11-已测试环境)
7 | * [2 使用篇](#2-使用篇)
8 | * [2.1 启动](#21-启动)
9 | * [2.2 一级及二级菜单](#22-一级及二级菜单)
10 | * [2.3 三级菜单](#23-三级菜单)
11 | * [2.3.1 概述](#231-概述)
12 | * [2.3.2 三级编辑窗口功能实现](#232-三级编辑窗口功能实现)
13 | * [2.3.3 三级 output 窗口](#233-三级-output-窗口)
14 | * [2.4 添加调试日志](#24-添加调试日志)
15 | * [3 原理篇](#3-原理篇)
16 | * [3.1 整体显示](#31-整体显示)
17 | * [3.2 构图](#32-构图)
18 | * [3.2.1 一层和二层](#321-一层和二层)
19 | * [3.2.2 三层目录](#322-三层目录)
20 | * [3.3 函数实现](#33-函数实现)
21 | * [3.3.1 一级及二级菜单](#331-一级及二级菜单)
22 | * [3.3.2 三级编辑窗口](#332-三级编辑窗口)
23 | * [3.3.3 二级菜单配置中往三级编辑窗口函数跳转实现](#333-二级菜单配置中往三级编辑窗口函数跳转实现)
24 | * [4 常见问题](#4-常见问题)
25 | * [4.1 中文乱码](#41-中文乱码)
26 |
27 |
28 |
29 | ## 1 项目简介
30 |
31 | 本项目主要更新两部分
32 |
33 | > * py_menu 整体框架
34 | > * 第三级编辑页的底层函数库 [w_lib/pysnack/snack_lib.py](./snack_lib.md) , 此库可以单独使用
35 |
36 | ### 1.1 已测试环境
37 |
38 | > * centos 6/7
39 | > * suse 12
40 |
41 | ## 2 使用篇
42 | ### 2.1 启动
43 |
44 | 先执行 `python py_menu.py` 看能否输出界面, 可正常输出时,则可正常使用
45 |
46 | > suse 系统可能会缺少库,可以通过以下方法解决:
47 | ```
48 | #cd tools
49 | #bash install_lib.sh
50 | ```
51 |
52 | 界面修改操作仅需要修改 config.py 和 three_page.py 两个文件
53 |
54 | ### 2.2 一级及二级菜单
55 |
56 | 一级及二级目录显示,只需要修改 config.py 文件
57 | ```
58 | config_first = {
59 | 'name': '主目录',
60 | 'items': ['a) 功能分类 1',
61 | 'b) 功能分类 2',
62 | 'c) 功能分类 3',
63 | ],
64 | }
65 |
66 | config_secondary = [{
67 | 'name': 'window1',
68 | 'items': [("二级目录 1_1","three1_1funtion", {}),
69 | ("二级目录 1_2","three1_2funtion", {}),
70 | ("二级目录 1_3","three1_3funtion", {}),
71 | ],
72 | },
73 | {
74 | 'name': 'window2',
75 | 'items': [("二级目录 2_1","three2_1funtion", {}),
76 | ("二级目录 2_2","three2_2funtion", {}),
77 | ],
78 | },
79 | {
80 | 'name': 'window3',
81 | 'items': [("二级目录 3_1","three3_1funtion", {}),
82 | ],
83 | },
84 | ]
85 | ```
86 | > * 一级目录中的 items『列表』即使终端菜单界面上的列表显示
87 | > * 二级目录中的 items『列表』即使终端菜单界面上的列表显示,items 列表中的元素是元组,元组的第一个元素是二级菜单的列表项,第二个元素是指定三级的功能
88 | > * config_first 中 items 的元素个数必须和 config_secondary 列表的元素个数一致,即保证一级目录都有对应的二级目录窗口
89 |
90 | ### 2.3 三级菜单
91 |
92 | #### 2.3.1 概述
93 |
94 | 常用三级窗口如下
95 | > * [snack_lib](./snack_lib.md)
96 | > * 编辑窗口 (Mask 类)
97 | > * 提醒窗口及输出窗口 (Snack_output 类)
98 | > * 确认窗口 (conformwindows 方法)
99 | > * snack 库
100 | > * 选择窗口 ListboxChoiceWindow
101 |
102 | #### 2.3.2 三级编辑窗口功能实现
103 |
104 | 三级编辑窗口,编辑 three_page.py
105 | ```
106 | def three1_1funtion(screen, *args, **kargs):
107 | m = Mask(screen, "test_windows1_1", 35 )
108 | m.text("label_test0","ceshi_text")
109 | m.entry( "label_test1", "entry_test1", "0" )
110 | m.entry( "label_test2", "entry_test2", "0" )
111 | m.entry( "label_test3", "entry_test3", "127.0.0.1" )
112 | m.checks( "复选框","checks_list",[
113 | ('checks_name1','checks1',0),
114 | ('checks_name2','checks2',0),
115 | ('checks_name3','checks3',0),
116 | ('checks_name4','checks4',1),
117 | ('checks_name5','checks5',0),
118 | ('checks_name6','checks6',0),
119 | ('checks_name7','checks7',0),
120 | ],
121 | height= 5
122 | )
123 | m.radios( "单选框","radios", [
124 | ('radios_name1','radios1', 0),
125 | ('radios_name2','radios2', 1),
126 | ('radios_name3','radios3', 0) ] )
127 |
128 | m.buttons( yes="Sava&Quit", no="Quit" )
129 | (cmd, results) = m.run(43,3)
130 |
131 | logger.debug(str(cmd)+" "+str(results))
132 | if cmd == "yes":
133 | rx = conformwindows(screen, "确认操作")
134 | if rx[0] == "yes" or rx[1] == "F12":
135 | """exe"""
136 | return
137 | else:
138 | logger.debug("cancel this operation")
139 | return
140 | else:
141 | return
142 | ```
143 | #### 2.3.3 三级 output 窗口
144 |
145 | 三级 output 窗口,编辑 three_page.py
146 | ```
147 | def three1_2funtion(screen, *args, **kargs):
148 | m = Snack_output(screen, "test_windows1_2", 35 )
149 | m.text("ceshijjjjjjjjjjjxdffffffffffffffff")
150 | m.text("xxxfffxxxxxxxxxxxxxx")
151 | m.text("xxxxxxxxxxxxxxxxx")
152 | m.text("xxxxxxxxxxxxxxxxx")
153 | m.text("xxxxxxxxxxxxxxxxx")
154 | m.run(43,3)
155 | ```
156 | ### 2.4 添加调试日志
157 |
158 | 在 `three_page.py` 中添加功能时,可能需要输出下调试日志,可以通过添加下面操作实现
159 |
160 | ```
161 | # messages 是需要输出的信息
162 | logger.debug(str(messages))
163 | ```
164 |
165 | ## 3 原理篇
166 | ### 3.1 整体显示
167 |
168 | ```
169 | +--------++-------++--------------+
170 | | || || |
171 | | || || |
172 | | || || |
173 | | || || |
174 | | || || +--+ +--+ |
175 | | || || +--+ +--+ |
176 | | || |+--------------+
177 | | +----+ || +---+ |
178 | | +----+ || +---+ |
179 | +--------++-------+
180 |
181 | ```
182 | > * 第一个列表窗口使用 g.run(1,3)-- 跳转到第二个窗口后仍然显示
183 | > * 第二个列表窗口使用 g.run(24,3)-- 跳转到第三个窗口后仍然显示
184 | > * 第三个编辑窗口使用 g.runOnce(45,3)-- 点击确定 / 取消后消失
185 |
186 |
187 | ### 3.2 构图
188 |
189 | #### 3.2.1 一层和二层
190 |
191 | ```
192 | +-----------------+
193 | | +-------------+ |
194 | | | list | |
195 | | +-------------+ |
196 | | +-------------+ |
197 | | | back | |
198 | | +-------------+ |
199 | +-----------------+
200 | ```
201 |
202 | #### 3.2.2 三层目录
203 |
204 | ```
205 | +-------------------------------+
206 | | +-------------+-------------+ |
207 | | | label | text | |
208 | | +-------------+-------------+ |
209 | | | label | entry | |
210 | | +-------------+-------------+-+---------subgrid
211 | | | label | checks | |
212 | | +-------------+-------------+ |
213 | | | label | radios | |
214 | | +-------------+-------------+ |
215 | | | label |checks_entry | |
216 | | +-------------+-------------+ |
217 | | +---------------------------+ |
218 | | | | |
219 | | | button +-+---------buttons
220 | | | | |
221 | | +---------------------------+ |
222 | +-------------------------------+---------gridform
223 | ```
224 | 第三层编辑窗口具体实现可查看 [snack_lib](snack_lib.md)
225 |
226 | ### 3.3 函数实现
227 |
228 | #### 3.3.1 一级及二级菜单
229 |
230 | 一级及二级菜单均是列表,故二级菜单可以进行复用,通过传入不同的列表值显示不同的菜单项
231 |
232 | > * self.main_location 标记一级菜单选择的第几行,会根据此参数,传给第二级菜单列表参数,显示对应二级窗口
233 | > * self.sec_location 标记二级菜单选择的第几行
234 |
235 | #### 3.3.2 三级编辑窗口
236 |
237 | 三级编辑窗口是对复选框、单选框、编辑框等进行了封装。点击确定后会继续弹出确认框。同时返回的是 json 串,非常容易处理
238 | #### 3.3.3 二级菜单配置中往三级编辑窗口函数跳转实现
239 |
240 | 二级菜单中,二级菜单配置是一个列表,列表中的元素是元组,第一个参数是二级菜单中的显示内容,第二个参数是跳转到的三级函数名字
241 |
242 | 'items': [("二级目录 3_1","three3_1funtion")],
243 |
244 | ## 4 常见问题
245 |
246 | ### 4.1 中文乱码
247 |
248 | 那么如何显示中文呢?
249 |
250 | > 系统必须安装中文语言包才行
251 | ```
252 | # yum -y groupinstall chinese-support
253 | ```
254 |
255 | > 设置相应的字符集
256 | ```
257 | ## 临时生效
258 | # export LANG="zh_CN.UTF-8" # 设置为中文
259 | # export LANG="en_US.UTF-8" # 设置为英文,我比较喜欢这样 export LANG=C
260 |
261 | ## 永久生效, 编辑 /etc/sysconfig/i18n
262 | LANG="zh_CN.UTF-8"
263 |
264 | ## 或者,编辑 /etc/profile 配置文件,添加如下一行
265 | export LANG="zh_CN.UTF-8"
266 | # 重新载入
267 | # . /etc/profile
268 |
269 | ## 查看当前的字符集
270 | # echo $LANG
271 | ```
272 |
273 | 好了,经过上面的设置,在终端上应该能够显示中文了。
274 |
275 | > ssh 远程终端乱码
276 | ```
277 | 如果 SSH 终端还是乱码,那么我们也需要对终端软件的编码进行设置。
278 | ```
279 |
--------------------------------------------------------------------------------
/images/5.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/meetbill/py_menu/31eb6b8ce5840be1984f30ddb74dc9bb0b70a5e2/images/5.jpg
--------------------------------------------------------------------------------
/images/test.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/meetbill/py_menu/31eb6b8ce5840be1984f30ddb74dc9bb0b70a5e2/images/test.jpg
--------------------------------------------------------------------------------
/src/config.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # coding=utf8
3 | """
4 | # Author: meetbill
5 | # Created Time : 2016-09-30 11:51:15
6 |
7 | # File Name: config.py
8 | # Description:
9 |
10 | """
11 | config_first = {
12 | 'name': '主目录',
13 | 'items': ['a)功能分类1',
14 | 'b)功能分类2',
15 | 'c)功能分类3',
16 | ],
17 | }
18 |
19 | config_secondary = [{
20 | 'name': 'window1',
21 | 'items': [("二级目录1_1", "three1_1funtion", {"name":"three1"}),
22 | ("二级目录1_2", "three1_2funtion", {}),
23 | ("二级目录1_3", "three1_3funtion", {}),
24 | ],
25 | },
26 | {
27 | 'name': 'window2',
28 | 'items': [("二级目录2_1", "three2_1funtion", {}),
29 | ("二级目录2_2", "three2_2funtion", {}),
30 | ],
31 | },
32 | {
33 | 'name': 'window3',
34 | 'items': [("二级目录3_1", "three3_1funtion", {}),
35 | ],
36 | },
37 | ]
38 |
--------------------------------------------------------------------------------
/src/py_menu.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # encoding=utf-8
3 |
4 | import traceback
5 | import os
6 | import sys
7 | import getopt
8 | import inspect
9 |
10 | from w_lib.pysnack.snack import *
11 | from w_lib.pysnack import snack_lib
12 | from w_lib import blog
13 | import config
14 | import three_page
15 |
16 | reload(sys)
17 | sys.setdefaultencoding('utf8')
18 | blog.init_log("./log/pymenu")
19 | _version_ = "1.2.4"
20 |
21 |
22 | def usage():
23 | print "<使用方法>"
24 | print "-h 本帮助"
25 |
26 |
27 | class MenuTool(object):
28 | def __init__(self):
29 |
30 | self.screen = SnackScreen()
31 | self.screen.setColor("ROOT", "white", "blue")
32 | self.screen.setColor("ENTRY", "white", "blue")
33 | self.screen.setColor("LABEL", "black", "white")
34 | self.screen.setColor("HELPLINE", "white", "blue")
35 | self.screen.setColor("TEXTBOX", "black", "yellow")
36 | self.main_location = 1
37 | self.sec_location = 1
38 |
39 | def main(self):
40 | try:
41 | self.first_menu()
42 | except Exception as e:
43 | self.screen.finish()
44 | print e
45 | print traceback.format_exc()
46 | finally:
47 | self.screen.finish()
48 | print "感谢使用!"
49 | return ''
50 |
51 | def quit(self):
52 | # 调用退出到命令行,输入exit返回
53 | buttons = ("是", "否")
54 | bb = ButtonBar(self.screen, buttons)
55 | g = GridForm(self.screen, "返回登陆界面?", 20, 16)
56 | g.add(bb, 1, 3, (10, 0, 10, 0), growx=1)
57 | rq = g.runOnce(32, 8)
58 | self.screen.popWindow()
59 | if rq == "ESC" or bb.buttonPressed(rq) == "否":
60 | self.first_menu()
61 | else:
62 | self.screen.finish()
63 | return
64 |
65 | def first_menu(self):
66 | # 主界面
67 | # 主memu菜单项位置
68 | while True:
69 | self.screen = SnackScreen()
70 | self.screen.finish()
71 | self.screen = SnackScreen()
72 | self.screen.setColor("ROOT", "white", "blue")
73 | self.screen.setColor("ENTRY", "white", "blue")
74 | self.screen.setColor("LABEL", "black", "white")
75 | self.screen.setColor("HELPLINE", "white", "blue")
76 | self.screen.setColor("TEXTBOX", "black", "yellow")
77 | self.screen.pushHelpLine("<%s> Powered by meetbill...请使用 TAB 在选项间切换" % _version_)
78 | li = Listbox(height=15, width=18, returnExit=1, showCursor=0)
79 |
80 | items_n = 1
81 | for items in config.config_first["items"]:
82 | li.append(items, items_n)
83 | items_n += 1
84 | li.setCurrent(self.main_location)
85 |
86 | bb = CompactButton('|->退出<-|')
87 | g = GridForm(self.screen, "manager", 1, 10)
88 | g.add(li, 0, 1)
89 | g.add(bb, 0, 2)
90 | g.add(Label(" "), 0, 3)
91 | g.add(Label("[管理利器]"), 0, 4)
92 | rc = g.run(1, 3)
93 | self.main_location = li.current()
94 | if rc == 'ESC' or 'snack.CompactButton' in str(rc):
95 | return self.quit()
96 | if li.current() in range(1, len(config.config_first["items"]) + 1):
97 | self.secondary_menu()
98 |
99 | # 第二层menu
100 | def secondary_menu(self):
101 | li = Listbox(height=15, width=14, returnExit=1, showCursor=0)
102 | bb = CompactButton('返回')
103 | secondary_window = config.config_secondary[self.main_location - 1]
104 | items_n = 1
105 | for items in secondary_window["items"]:
106 | li.append(items[0], items_n)
107 | items_n += 1
108 | while True:
109 | h = GridForm(self.screen, "请选择", 1, 16)
110 | if len(secondary_window["items"]) < self.sec_location:
111 | li.setCurrent(1)
112 | else:
113 | li.setCurrent(self.sec_location)
114 | h.add(li, 0, 1)
115 | h.add(bb, 0, 9)
116 | rc = h.run(24, 3)
117 |
118 | if "snack.CompactButton" in str(rc) or rc == 'ESC':
119 | return 0
120 | else:
121 | self.sec_location = li.current()
122 | if self.sec_location in range(1, len(secondary_window["items"]) + 1):
123 | name, func_name, func_kargs = secondary_window["items"][self.sec_location - 1]
124 | if func_name in dir(three_page):
125 | for fun in inspect.getmembers(three_page, callable):
126 | if func_name == fun[0]:
127 | fun[1](self.screen, **func_kargs)
128 | else:
129 | snack_lib.warwindows(self.screen, "警告", "没有找到对应的函数!")
130 | else:
131 | snack_lib.warwindows(self.screen, "测试", "xxx")
132 |
133 |
134 | try:
135 | if len(sys.argv) > 1:
136 | opts, args = getopt.getopt(sys.argv[1:], "h")
137 | for op, value in opts:
138 | if op == "-h":
139 | usage()
140 | sys.exit()
141 |
142 | if len(config.config_first["items"]) != len(config.config_secondary):
143 | print "一级目录个数与二级窗口个数不对应"
144 | sys.exit()
145 | if os.getenv('STY'):
146 | print "not support screen"
147 | sys.exit()
148 |
149 | menu = MenuTool()
150 | menu.main()
151 | except Exception as e:
152 | print e
153 | print "指定的参数无效"
154 | usage()
155 |
--------------------------------------------------------------------------------
/src/three_page.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # coding=utf8
3 | """
4 | # Author: meetbill
5 | # Created Time : 2017-03-16 21:36:04
6 |
7 | # File Name: three_page.py
8 | # Description:
9 |
10 | """
11 | import logging
12 |
13 | from w_lib.pysnack import snack_lib
14 |
15 |
16 | def three1_1funtion(screen, *args, **kargs):
17 | window_name = "name" in kargs.keys() and kargs["name"] or "test_windows1_1"
18 | m = snack_lib.Mask(screen, window_name, 35)
19 | m.text("label_test0", "ceshi_text")
20 | m.entry("label_test1", "entry_test1", "0")
21 | m.entry("label_test2", "entry_test2", "0")
22 | m.entry("label_test3", "entry_test3", "127.0.0.1")
23 | m.checks("复选框", "checks_list", [
24 | ('checks_name1', 'checks1', 0),
25 | ('checks_name2', 'checks2', 0),
26 | ('checks_name3', 'checks3', 0),
27 | ('checks_name4', 'checks4', 1),
28 | ('checks_name5', 'checks5', 0),
29 | ('checks_name6', 'checks6', 0),
30 | ('checks_name7', 'checks7', 0),
31 | ],
32 | height=5
33 | )
34 | m.radios("单选框", "radios", [
35 | ('radios_name1', 'radios1', 0),
36 | ('radios_name2', 'radios2', 1),
37 | ('radios_name3', 'radios3', 0)])
38 |
39 | m.buttons(yes="Sava&Quit", no="Quit")
40 | (cmd, results) = m.run(43, 3)
41 |
42 | logging.info(str(cmd) + " " + str(results))
43 | if cmd == "yes":
44 | rx = snack_lib.conformwindows(screen, "确认操作")
45 | if rx[0] == "yes" or rx[1] == "F12":
46 | """exe"""
47 | return
48 | else:
49 | logging.info("cancel this operation")
50 | return
51 | else:
52 | return
53 |
54 |
55 | def three1_2funtion(screen, *args, **kargs):
56 | m = snack_lib.SnackOutput(screen, "test_windows1_2", 35)
57 | m.text("ceshijjjjjjjjjjjxdffffffffffffffff")
58 | m.text("xxxfffxxxxxxxxxxxxxx")
59 | m.text("xxxxxxxxxxxxxxxxx")
60 | m.text("xxxxxxxxxxxxxxxxx")
61 | m.text("xxxxxxxxxxxxxxxxx")
62 | m.run(43, 3)
63 |
64 |
65 | if __name__ == "__main__":
66 | from snack import *
67 | try:
68 | screen = SnackScreen()
69 | screen.setColor("ROOT", "white", "blue")
70 | screen.setColor("ENTRY", "white", "blue")
71 | screen.setColor("LABEL", "black", "white")
72 | screen.setColor("HELPLINE", "white", "blue")
73 | screen.setColor("TEXTBOX", "black", "yellow")
74 | three1_2funtion(screen)
75 | except Exception as e:
76 | print e
77 | finally:
78 | screen.finish()
79 |
--------------------------------------------------------------------------------
/src/w_lib/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/meetbill/py_menu/31eb6b8ce5840be1984f30ddb74dc9bb0b70a5e2/src/w_lib/__init__.py
--------------------------------------------------------------------------------
/src/w_lib/blog.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # coding=utf8
3 | """
4 | # Author: meetbill
5 | # Created Time : 2016-08-01 10:59:26
6 |
7 | # File Name: blog.py
8 | # Description:
9 |
10 | """
11 | import sys
12 | import logging
13 | from logging.handlers import RotatingFileHandler
14 | import os
15 |
16 |
17 | class ColoredFormatter(logging.Formatter):
18 | '''A colorful formatter.'''
19 |
20 | def __init__(self, fmt=None, datefmt=None):
21 | logging.Formatter.__init__(self, fmt, datefmt)
22 | # Color escape string
23 | COLOR_RED = '\033[1;31m'
24 | COLOR_GREEN = '\033[1;32m'
25 | COLOR_YELLOW = '\033[1;33m'
26 | COLOR_BLUE = '\033[1;34m'
27 | COLOR_PURPLE = '\033[1;35m'
28 | COLOR_CYAN = '\033[1;36m'
29 | COLOR_GRAY = '\033[1;37m'
30 | COLOR_WHITE = '\033[1;38m'
31 | COLOR_RESET = '\033[1;0m'
32 |
33 | # Define log color
34 | self.LOG_COLORS = {
35 | 'DEBUG': '%s',
36 | 'INFO': COLOR_GREEN + '%s' + COLOR_RESET,
37 | 'WARNING': COLOR_YELLOW + '%s' + COLOR_RESET,
38 | 'ERROR': COLOR_RED + '%s' + COLOR_RESET,
39 | 'CRITICAL': COLOR_RED + '%s' + COLOR_RESET,
40 | 'EXCEPTION': COLOR_RED + '%s' + COLOR_RESET,
41 | }
42 |
43 | def format(self, record):
44 | level_name = record.levelname
45 | msg = logging.Formatter.format(self, record)
46 |
47 | return self.LOG_COLORS.get(level_name, '%s') % msg
48 |
49 |
50 | class Log(object):
51 |
52 | '''
53 | log
54 | '''
55 |
56 | def __init__(self, filename, level="debug", logid="meetbill",
57 | mbs=20, count=10, is_console=True):
58 | '''
59 | mbs: how many MB
60 | count: the count of remain
61 | '''
62 | try:
63 | self._level = level
64 | #print "init,level:",level,"\t","get_map_level:",self._level
65 | self._filename = filename
66 | self._logid = logid
67 | self._logger = logging.getLogger(self._logid)
68 | file_path = os.path.split(self._filename)[0]
69 | if not os.path.exists(file_path):
70 | os.makedirs(file_path)
71 |
72 | if not len(self._logger.handlers):
73 | self._logger.setLevel(self.get_map_level(self._level))
74 |
75 | fmt = '[%(asctime)s] %(levelname)s %(message)s'
76 | datefmt = '%Y-%m-%d %H:%M:%S'
77 | formatter = logging.Formatter(fmt, datefmt)
78 |
79 | maxBytes = int(mbs) * 1024 * 1024
80 | file_handler = RotatingFileHandler(
81 | self._filename, mode='a', maxBytes=maxBytes, backupCount=count)
82 | self._logger.setLevel(self.get_map_level(self._level))
83 | file_handler.setFormatter(formatter)
84 | self._logger.addHandler(file_handler)
85 |
86 | if is_console == True:
87 | stream_handler = logging.StreamHandler(sys.stderr)
88 | console_formatter = ColoredFormatter(fmt, datefmt)
89 | stream_handler.setFormatter(console_formatter)
90 | self._logger.addHandler(stream_handler)
91 | self._logger.propagate = False
92 |
93 | except Exception as expt:
94 | print expt
95 |
96 | def tolog(self, msg, level=None):
97 | try:
98 | level = level if level else self._level
99 | level = str(level).lower()
100 | level = self.get_map_level(level)
101 | if level == logging.DEBUG:
102 | self._logger.debug(msg)
103 | if level == logging.INFO:
104 | self._logger.info(msg)
105 | if level == logging.WARN:
106 | self._logger.warn(msg)
107 | if level == logging.ERROR:
108 | self._logger.error(msg)
109 | if level == logging.CRITICAL:
110 | self._logger.critical(msg)
111 | except Exception as expt:
112 | print expt
113 |
114 | def debug(self, msg):
115 | self.tolog(msg, level="debug")
116 |
117 | def info(self, msg):
118 | self.tolog(msg, level="info")
119 |
120 | def warn(self, msg):
121 | self.tolog(msg, level="warn")
122 |
123 | def error(self, msg):
124 | self.tolog(msg, level="error")
125 |
126 | def critical(self, msg):
127 | self.tolog(msg, level="critical")
128 |
129 | def get_map_level(self, level="debug"):
130 | level = str(level).lower()
131 | #print "get_map_level:",level
132 | if level == "debug":
133 | return logging.DEBUG
134 | if level == "info":
135 | return logging.INFO
136 | if level == "warn":
137 | return logging.WARN
138 | if level == "error":
139 | return logging.ERROR
140 | if level == "critical":
141 | return logging.CRITICAL
142 |
143 |
144 | def init_log(log_path, level=logging.INFO, when="D", backup=7,
145 | format="%(levelname)s: %(asctime)s: %(filename)s:%(lineno)d * %(thread)d %(message)s",
146 | datefmt="%m-%d %H:%M:%S"):
147 | """
148 | init_log - initialize log module
149 |
150 | Args:
151 | log_path - Log file path prefix.
152 | Log data will go to two files: log_path.log and log_path.log.wf
153 | Any non-exist parent directories will be created automatically
154 | level - msg above the level will be displayed
155 | DEBUG < INFO < WARNING < ERROR < CRITICAL
156 | the default value is logging.INFO
157 | when - how to split the log file by time interval
158 | 'S' : Seconds
159 | 'M' : Minutes
160 | 'H' : Hours
161 | 'D' : Days
162 | 'W' : Week day
163 | default value: 'D'
164 | format - format of the log
165 | default format:
166 | %(levelname)s: %(asctime)s: %(filename)s:%(lineno)d * %(thread)d %(message)s
167 | INFO: 12-09 18:02:42: log.py:40 * 139814749787872 HELLO WORLD
168 | backup - how many backup file to keep
169 | default value: 7
170 |
171 | Raises:
172 | OSError: fail to create log directories
173 | IOError: fail to open log file
174 | """
175 | formatter = logging.Formatter(format, datefmt)
176 | logger = logging.getLogger()
177 | logger.setLevel(level)
178 |
179 | dir = os.path.dirname(log_path)
180 | if not os.path.isdir(dir):
181 | os.makedirs(dir)
182 |
183 | handler = logging.handlers.TimedRotatingFileHandler(log_path + ".log",
184 | when=when,
185 | backupCount=backup)
186 | handler.setLevel(level)
187 | handler.setFormatter(formatter)
188 | logger.addHandler(handler)
189 |
190 | handler = logging.handlers.TimedRotatingFileHandler(log_path + ".log.wf",
191 | when=when,
192 | backupCount=backup)
193 | handler.setLevel(logging.WARNING)
194 | handler.setFormatter(formatter)
195 | logger.addHandler(handler)
196 |
197 |
198 | if __name__ == "__main__":
199 | # 通用模块日志
200 | init_log("./log/common.log")
201 | logging.info("info log")
202 | logging.warning("warning log")
203 | logging.error("error log")
204 | logging.debug("debug log")
205 | # 独立模块日志
206 | debug = True
207 | logpath = "./log/test.log"
208 | logger = Log(
209 | logpath,
210 | level="debug",
211 | logid="meetbill",
212 | is_console=debug,
213 | mbs=5,
214 | count=5)
215 |
216 | logstr = "helloworld"
217 | logger.error(logstr)
218 | logger.info(logstr)
219 | logger.warn(logstr)
220 | logger.debug(logstr)
221 |
--------------------------------------------------------------------------------
/src/w_lib/http_util.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # coding=utf8
3 | """
4 | # Author: wangbin34(meetbill)
5 | # Created Time : 2020-05-23 22:08:46
6 |
7 | # File Name: http_util.py
8 | # Description:
9 |
10 | Simple module to request HTTP
11 |
12 | get(url, **kwargs)
13 | post(url, **kwargs)
14 | download(url, **kwargs)
15 |
16 | RequestTool(
17 | 'http://127.0.0.1:8585',
18 | data = {},
19 | type = 'GET', # (str) GET POST default: POST
20 | is_decode_response = False, # (bool) If True, json ==> dict
21 | check_key = None, # (str) Check key
22 | check_value = None, # (str, int, list) Check value, May be a list
23 | referer = '',
24 | user_agent = '',
25 | cookie = None, # CookieJar, Cookie.S*Cookie, dict, string
26 | auth = {'usr':'', 'pwd':''}, # Only Basic Authorization
27 | debug = False
28 | )
29 | """
30 | from __future__ import absolute_import
31 | from __future__ import division
32 | from __future__ import unicode_literals
33 |
34 | import os
35 | import base64
36 | import sys
37 | import inspect
38 | import logging
39 | import time
40 | import json
41 |
42 |
43 | log = logging.getLogger("butterfly")
44 |
45 |
46 | PY2 = sys.version_info.major == 2
47 | PY3 = sys.version_info.major == 3
48 |
49 |
50 | if PY2:
51 | from urllib import ContentTooShortError
52 | from urllib2 import HTTPError, URLError
53 | from urllib import urlencode
54 | from urllib2 import Request as urlRequest
55 | from urllib2 import build_opener
56 | from urllib2 import HTTPHandler, HTTPSHandler, HTTPCookieProcessor
57 | import Cookie
58 | from cookielib import CookieJar
59 |
60 | if PY3:
61 | from urllib.error import ContentTooShortError, HTTPError, URLError
62 | from urllib.parse import urlencode
63 | from urllib.request import Request as urlRequest
64 | from urllib.request import build_opener
65 | from urllib.request import HTTPHandler, HTTPSHandler, HTTPCookieProcessor
66 | from http import cookies as Cookie
67 | from http.cookiejar import CookieJar
68 |
69 |
70 | _DEFAULT_TIMEOUT = 90
71 |
72 |
73 | def get(url, **kwargs):
74 | """
75 | http get request
76 | """
77 | kwargs.update(type='GET')
78 | kwargs.update(is_decode_response=True)
79 | return RequestTool(url, **kwargs)
80 |
81 |
82 | def post_form(url, **kwargs):
83 | """
84 | http post request
85 | """
86 | kwargs.update(type='POST')
87 | kwargs.update(post_type='form')
88 | kwargs.update(is_decode_response=True)
89 | return RequestTool(url, **kwargs)
90 |
91 |
92 | def post_json(url, **kwargs):
93 | """
94 | http post request
95 | """
96 | kwargs.update(type='POST')
97 | kwargs.update(post_type='json')
98 | kwargs.update(is_decode_response=True)
99 | return RequestTool(url, **kwargs)
100 |
101 |
102 | def download(url, local, **kwargs):
103 | """
104 | download file
105 | """
106 | if not local:
107 | raise ValueError('local filepath is empty')
108 | try:
109 | if not os.path.exists(os.path.dirname(local)):
110 | os.makedirs(os.path.dirname(local))
111 | res = RequestTool(url, **kwargs)
112 | read_size = 0
113 | real_size = int(res.header['content-length'])
114 | with open(local, 'wb') as f:
115 | while True:
116 | block = res.response.read(1024 * 8)
117 | if not block:
118 | break
119 | f.write(block)
120 | read_size += len(block)
121 | if read_size < real_size:
122 | raise ContentTooShortError(
123 | 'retrieval incomplete: got only {} out of {} bytes'.formate(read_size, real_size),
124 | None
125 | )
126 | except Exception as e:
127 | raise e
128 |
129 |
130 | class RequestTool(object):
131 | """
132 | Request Class
133 | """
134 |
135 | def __init__(self, url, **kwargs):
136 | """
137 | Request init
138 | """
139 | self.request = None
140 | self.response = None
141 | self.code = -1
142 | self.header = {}
143 | self.cookieJar = None
144 | self.reason = ''
145 | self.content = ''
146 | self.content_dict = {}
147 |
148 | # 是否将服务端返回结果从 json 转为 dict
149 | self.is_decode_response = kwargs.get('is_decode_response', False)
150 |
151 | data = kwargs.get('data', None)
152 | # 当请求是 GET 请求,同时传了 data 字典的话,post_type 默认是 form,会进行 urlencode,并拼接到请求 URL 上
153 | post_type = kwargs.get('post_type', 'form')
154 | if data is not None:
155 | if isinstance(data, dict):
156 | if post_type == 'json':
157 | data_str = json.dumps(data)
158 | else:
159 | # data = {"name":"meetbill", "age":"21"} ==> urlencode(data) = 'age=21&name=meetbill'
160 | data_str = urlencode(data)
161 |
162 | if not isinstance(data_str, basestring):
163 | raise ValueError('data must be string or dict')
164 | else:
165 | data_str = None
166 |
167 | request_type = kwargs.get('type', 'POST')
168 | if data_str and isinstance(request_type, basestring) and request_type.upper() != 'POST':
169 | # 如果是 GET 请求,则将 data 中的内容转为 url 的一部分
170 | url = '{}?{}'.format(url, data_str)
171 | data_str = None # GET data must be None
172 |
173 | self.request = urlRequest(url, data_str)
174 | # Content-type, 默认是 'application/x-www-form-urlencoded'
175 | if request_type.upper() == 'POST' and post_type == "json":
176 | self.request.add_header('Content-type', 'application/json')
177 |
178 | # referer
179 | referer = kwargs.get('referer', None)
180 | if referer:
181 | self.request.add_header('referer', referer)
182 |
183 | # user-agent
184 | user_agent = kwargs.get('user_agent', None)
185 | if user_agent:
186 | self.request.add_header('User-Agent', user_agent)
187 |
188 | # auth
189 | auth = kwargs.get('auth', None)
190 | if auth and isinstance(auth, dict) and 'usr' in auth:
191 | auth_string = base64.b64encode('{}:{}'.format(auth.get('usr', ''), auth.get('pwd', '')))
192 | self.request.add_header('Authorization', 'Basic {}'.format(auth_string))
193 |
194 | # cookie
195 | cookie = kwargs.get('cookie', None)
196 | cj = None
197 | if cookie:
198 | if isinstance(cookie, CookieJar):
199 | cj = cookie
200 | elif isinstance(cookie, dict):
201 | result = []
202 | for k, v in cookie.items():
203 | result.append('{}={}'.format(k, v))
204 | cookie = '; '.join(result)
205 | elif isinstance(cookie, Cookie.BaseCookie):
206 | cookie = cookie.output(header='')
207 | if isinstance(cookie, basestring):
208 | self.request.add_header('Cookie', cookie)
209 |
210 | if cj is None:
211 | cj = CookieJar()
212 |
213 | #! TODO: proxy
214 |
215 | # build opener
216 | debuglevel = 1 if kwargs.get('debug', False) else 0
217 | opener = build_opener(
218 | HTTPHandler(debuglevel=debuglevel),
219 | HTTPSHandler(debuglevel=debuglevel),
220 | HTTPCookieProcessor(cj)
221 | )
222 |
223 | # timeout
224 | timeout = kwargs.get('timeout')
225 | if not isinstance(timeout, int):
226 | timeout = _DEFAULT_TIMEOUT
227 |
228 | t_beginning = time.time()
229 | try:
230 | # opener.open accept a URL or a Request object
231 | # 程序中判断是字符串时按照 URL 来处理, 否则按照是已经封装好的 Request 处理
232 | self.response = opener.open(self.request, timeout=timeout)
233 | self.code = self.response.getcode()
234 | self.header = self.response.info().dict
235 | self.cookieJar = cj
236 | self.content = self.response.read()
237 | # 进行将 response 转为 dict
238 | if self.is_decode_response:
239 | self.content_dict = json.loads(self.content)
240 |
241 | # 检查 response 内容是否符合预期
242 | check_key = kwargs.get('check_key', None)
243 | check_value = kwargs.get('check_value', None)
244 | if check_key is not None and check_value is not None:
245 | # 检查 check_value 类型
246 | if isinstance(check_value, list):
247 | if self.content_dict[check_key] not in check_value:
248 | self.code = -1
249 | self.reason = "[response not match: {response_value} not in {check_value}]".format(
250 | response_value=self.content_dict[check_key],
251 | check_value=check_value
252 | )
253 | elif self.content_dict[check_key] != check_value:
254 | self.code = -1
255 | self.reason = "[response not match: {response_value} != {check_value}]".format(
256 | response_value=self.content_dict[check_key],
257 | check_value=check_value
258 | )
259 | except HTTPError as e:
260 | self.code = e.code
261 | self.reason = '{}'.format(e)
262 | except URLError as e:
263 | self.code = -1
264 | self.reason = e.reason
265 | except Exception as e:
266 | self.code = -1
267 | self.reason = '{}'.format(e)
268 |
269 | seconds_passed = time.time() - t_beginning
270 | cost_str = "%.6f" % seconds_passed
271 |
272 | # 打印日志
273 | f = inspect.currentframe().f_back
274 | file_name, lineno, func_name = self._get_backframe_info(f)
275 |
276 | log_msg = ("[file={file_name}:{func_name}:{lineno} "
277 | "type=http_{method} "
278 | "req_path={req_path} "
279 | "req_data={req_data} "
280 | "cost={cost} "
281 | "is_success={is_success} "
282 | "err_no={err_no} "
283 | "err_msg={err_msg} "
284 | "res_len={res_len} "
285 | "res_data={res_data} "
286 | "res_attr={res_attr}]".format(
287 | file_name=file_name, func_name=func_name, lineno=lineno,
288 | method=request_type,
289 | req_path=url,
290 | req_data=data,
291 | cost=cost_str,
292 | is_success=self.success(),
293 | err_no=self.code,
294 | err_msg=self.reason,
295 | res_len=len(self.content),
296 | res_data=self.content,
297 | res_attr=json.dumps(self.header)
298 | ))
299 |
300 | if self.success():
301 | log.info(log_msg)
302 | else:
303 | log.error(log_msg)
304 |
305 | def _get_backframe_info(self, f):
306 | """
307 | get backframe info
308 | """
309 | return f.f_back.f_code.co_filename, f.f_back.f_lineno, f.f_back.f_code.co_name
310 |
311 | def success(self):
312 | """
313 | check http code
314 | """
315 | return 200 <= self.code < 300
316 |
317 | def output(self):
318 | """
319 | return content
320 | """
321 | if self.is_decode_response:
322 | return self.content_dict
323 | else:
324 | return self.content
325 |
326 |
327 | if __name__ == "__main__":
328 | # Butterfly 例子
329 | # GET 请求,无参数
330 | print("[GET], no pargs---------------------------------")
331 | res = get("http://127.0.0.1:8585/x/ping", debug=True)
332 | if res.success():
333 | print(res.output())
334 | assert isinstance(res.output(), dict)
335 |
336 | print("[GET], no pargs---------------------------------, check status")
337 | res = get("http://127.0.0.1:8585/x/ping", check_key="stat", check_value=0)
338 | assert res.success() == False
339 | res = get("http://127.0.0.1:8585/x/ping", check_key="stat", check_value="OK")
340 | assert res.success() == True
341 | print res.output()
342 |
343 | print("[GET], have pargs---------------------------------")
344 | get("http://127.0.0.1:8585/x/hello?str_info=meetbill", debug=True)
345 |
346 | print("[POST], post json---------------------------------")
347 | post_json("http://127.0.0.1:8585/x/hello", data={"str_info": "meetbill"}, debug=True)
348 |
349 | print("[POST], post form---------------------------------[exe error]")
350 | post_form("http://127.0.0.1:8585/x/hello", data={"str_info": "meetbill"}, debug=True)
351 |
--------------------------------------------------------------------------------
/src/w_lib/pysnack/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/meetbill/py_menu/31eb6b8ce5840be1984f30ddb74dc9bb0b70a5e2/src/w_lib/pysnack/__init__.py
--------------------------------------------------------------------------------
/src/w_lib/pysnack/_snackmodule.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/meetbill/py_menu/31eb6b8ce5840be1984f30ddb74dc9bb0b70a5e2/src/w_lib/pysnack/_snackmodule.so
--------------------------------------------------------------------------------
/src/w_lib/pysnack/snack.py:
--------------------------------------------------------------------------------
1 | # snack.py: maps C extension module _snack to proper python types in module
2 | # snack.
3 | # The first section is a very literal mapping.
4 | # The second section contains convenience classes that amalgamate
5 | # the literal classes and make them more object-oriented.
6 |
7 | """
8 | This module provides the NEWT Windowing toolkit API for Python
9 | This is a lightweight text-mode windowing library, based on slang.
10 |
11 | Classes:
12 |
13 | - Widget
14 | - Button
15 | - CompactButton
16 | - Checkbox
17 | - SingleRadioButton
18 | - Listbox
19 | - Textbox
20 | - TextboxReflowed
21 | - Label
22 | - Scale
23 | - Entry
24 | - Form
25 | - Grid
26 | - SnackScreen
27 | - RadioGroup
28 | - RadioBar
29 | - ButtonBar
30 | - GridFormHelp
31 | - GridForm
32 | - CheckboxTree
33 | - Clistbox
34 |
35 | Functions:
36 |
37 | - ListboxChoiceWindow
38 | - ButtonChoiceWindow
39 | - EntryWindow
40 | """
41 |
42 | import _snack
43 | import types
44 | import string
45 |
46 | from _snack import FLAG_DISABLED, FLAGS_SET, FLAGS_RESET, FLAGS_TOGGLE, FD_READ, FD_WRITE, FD_EXCEPT
47 |
48 | LEFT = (-1, 0)
49 | DOWN = (-1, -1)
50 | CENTER = (0, 0)
51 | UP = (1, 1)
52 | RIGHT = (1, 0)
53 |
54 | snackArgs = {"append": -1}
55 |
56 |
57 | class Widget:
58 | """Base class for NEWT toolkit - Do not use directly
59 |
60 | methods:
61 |
62 | - Widget(self)
63 | - setCallback(self, obj, data = None) :
64 | The callback for when object activated.
65 | data is passed to obj.
66 | """
67 |
68 | def setCallback(self, obj, data=None):
69 | if data:
70 | self.w.setCallback(obj, data)
71 | else:
72 | self.w.setCallback(obj)
73 |
74 | def __init__(self):
75 | raise NotImplementedError
76 |
77 |
78 | class Button(Widget):
79 | """Basic button class, takes button text as parameter
80 |
81 | method:
82 |
83 | - Button(self, text): returns a button
84 | """
85 |
86 | def __init__(self, text):
87 | self.w = _snack.button(text)
88 |
89 |
90 | class CompactButton(Widget):
91 | """Compact Button class (less frilly button decoration).
92 |
93 | methods:
94 |
95 | - CompactButton(self,text) : create button, with text.
96 | """
97 |
98 | def __init__(self, text):
99 | self.w = _snack.compactbutton(text)
100 |
101 |
102 | class Checkbox(Widget):
103 | """A checkbox.
104 |
105 | methods:
106 |
107 | - Checkbox(self, text, isOn = 0) : text, and boolean as to default value
108 | - setValue(self) : set value
109 | - value(self, value) : return checkbox value
110 | - selected(self) : returns boolean
111 | - setFlags(self, flag, sense) : set flags
112 |
113 | flags: FLAG_DISABLED, FLAGS_SET, FLAGS_RESET
114 | """
115 |
116 | def value(self):
117 | return self.w.checkboxValue
118 |
119 | def selected(self):
120 | return self.w.checkboxValue != 0
121 |
122 | def setFlags(self, flag, sense):
123 |
124 | return self.w.checkboxSetFlags(flag, sense)
125 |
126 | def setValue(self, value):
127 | return self.w.checkboxSetValue(value)
128 |
129 | def __init__(self, text, isOn=0):
130 | self.w = _snack.checkbox(text, isOn)
131 |
132 |
133 | class SingleRadioButton(Widget):
134 | """Single Radio Button.
135 |
136 | methods:
137 |
138 | - SingleRadioButton(text, group, isOn = 0) : create button
139 | - selected(self) : returns bool, whether or not is selected.
140 | """
141 |
142 | def selected(self):
143 | return self.w.key == self.w.radioValue
144 |
145 | def __init__(self, text, group, isOn=0):
146 | if group:
147 | self.w = _snack.radiobutton(text, group.w, isOn)
148 | else:
149 | self.w = _snack.radiobutton(text, None, isOn)
150 |
151 |
152 | class Listbox(Widget):
153 | """Listbox class.
154 |
155 | methods:
156 |
157 | - Listbox(self, height, scroll = 0, returnExit = 0, width = 0, showCursor = 0, multiple = 0, border = 0)
158 | - insert(self, text, item, before) : insert element; before = key to item to insert before, or None.
159 | - delete(self, item) : delete item from list.
160 | - replace(self, text,item) : Replace a given item's text
161 | - current(self) : returns currently selected item
162 | - getSelection(self) : returns a list of selected items
163 | - setCurrent(self,i tem) : select current.
164 | - clear(self) : clear listbox
165 | """
166 |
167 | def append(self, text, item):
168 | key = self.w.listboxAddItem(text)
169 | self.key2item[key] = item
170 | self.item2key[item] = key
171 |
172 | def insert(self, text, item, before):
173 | if (not before):
174 | key = self.w.listboxInsertItem(text, 0)
175 | else:
176 | key = self.w.listboxInsertItem(text, self.item2key[before])
177 | self.key2item[key] = item
178 | self.item2key[item] = key
179 |
180 | def delete(self, item):
181 | self.w.listboxDeleteItem(self.item2key[item])
182 | del self.key2item[self.item2key[item]]
183 | del self.item2key[item]
184 |
185 | def replace(self, text, item):
186 | key = self.w.listboxInsertItem(text, self.item2key[item])
187 | self.w.listboxDeleteItem(self.item2key[item])
188 | del self.key2item[self.item2key[item]]
189 | self.item2key[item] = key
190 | self.key2item[key] = item
191 |
192 | def current(self):
193 | return self.key2item[self.w.listboxGetCurrent()]
194 |
195 | def getSelection(self):
196 | selection = []
197 | list = self.w.listboxGetSelection()
198 | for key in list:
199 | selection.append(self.key2item[key])
200 | return selection
201 |
202 | def setCurrent(self, item):
203 | self.w.listboxSetCurrent(self.item2key[item])
204 |
205 | def clear(self):
206 | self.key2item = {}
207 | self.item2key = {}
208 | self.w.listboxClear()
209 |
210 | def __init__(self, height, scroll=0, returnExit=0, width=0, showCursor=0, multiple=0, border=0):
211 | self.w = _snack.listbox(height, scroll, returnExit, showCursor, multiple, border)
212 | self.key2item = {}
213 | self.item2key = {}
214 | if (width):
215 | self.w.listboxSetWidth(width)
216 |
217 |
218 | class Textbox(Widget):
219 | """Textbox, container for text.
220 |
221 | methods:
222 |
223 | - Textbox(self, width, height, scroll = 0, wrap = 0): scroll, wrap are flags
224 | include scroll bars, or text wrap.
225 | - setText(text) : set text.
226 | - setHeight(height): set height.
227 | """
228 |
229 | def setText(self, text):
230 | self.w.textboxText(text)
231 |
232 | def setHeight(self, height):
233 | self.w.textboxHeight(height)
234 |
235 | def __init__(self, width, height, text, scroll=0, wrap=0):
236 | self.w = _snack.textbox(width, height, text, scroll, wrap)
237 |
238 |
239 | class TextboxReflowed(Textbox):
240 |
241 | def __init__(self, width, text, flexDown=5, flexUp=10, maxHeight=-1):
242 | (newtext, width, height) = reflow(text, width, flexDown, flexUp)
243 | if maxHeight != -1 and height > maxHeight:
244 | Textbox.__init__(self, width, maxHeight, newtext, 1)
245 | else:
246 | Textbox.__init__(self, width, height, newtext, 0)
247 |
248 |
249 | class Label(Widget):
250 | """A Label (simple text).
251 |
252 | methods:
253 |
254 | - Label(self,text) : create label
255 | - setText(self,text) : change text.
256 | - setColors(self, colorset) : change individual colors
257 | """
258 |
259 | def setText(self, text):
260 | self.w.labelText(text)
261 |
262 | def __init__(self, text):
263 | self.w = _snack.label(text)
264 |
265 | def setColors(self, colorset):
266 | self.w.labelSetColors(colorset)
267 |
268 |
269 | class Scale(Widget):
270 | """A Scale (progress bar).
271 |
272 | methods:
273 |
274 | - Scale(self,width, total) : create scale; width: size on screen, fullamount: integer.
275 | - set(self,amount) : set amount to integer.
276 | """
277 |
278 | def set(self, amount):
279 | self.w.scaleSet(amount)
280 |
281 | def __init__(self, width, total):
282 | self.w = _snack.scale(width, total)
283 |
284 |
285 | class Entry(Widget):
286 | """Entry widget.
287 |
288 | methods:
289 |
290 | - Entry(self, width, text = "", hidden = 0, password = 0, scroll = 1, returnExit = 0)
291 | constructor. hidden doesn't show text, password stars it out,
292 | scroll includes scroll bars;
293 | if returnExit is set, return from Form when exiting this element, else
294 | proceed to next entry widget.
295 | - value(self): return value.
296 | - set(text, cursorAtEnd = 1) : set the text
297 | - setFlags (flag, sense) : flags can be FLAG_DISABLED, FLAGS_SET, FLAGS_RESET, FLAGS_TOGGLE
298 | """
299 |
300 | def value(self):
301 | return self.w.entryValue
302 |
303 | def set(self, text, cursorAtEnd=1):
304 | return self.w.entrySetValue(text, cursorAtEnd)
305 |
306 | def setFlags(self, flag, sense):
307 | return self.w.entrySetFlags(flag, sense)
308 |
309 | def __init__(self, width, text="", hidden=0, password=0, scroll=1,
310 | returnExit=0):
311 | self.w = _snack.entry(width, text, hidden, password, scroll, returnExit)
312 |
313 |
314 | # Form uses hotkeys
315 | hotkeys = {"F1": _snack.KEY_F1, "F2": _snack.KEY_F2, "F3": _snack.KEY_F3,
316 | "F4": _snack.KEY_F4, "F5": _snack.KEY_F5, "F6": _snack.KEY_F6,
317 | "F7": _snack.KEY_F7, "F8": _snack.KEY_F8, "F9": _snack.KEY_F9,
318 | "F10": _snack.KEY_F10, "F11": _snack.KEY_F11,
319 | "F12": _snack.KEY_F12, "ESC": _snack.KEY_ESC,
320 | "ENTER": _snack.KEY_ENTER, "SUSPEND": _snack.KEY_SUSPEND,
321 | "BACKSPACE": _snack.KEY_BACKSPACE, "DELETE": _snack.KEY_DELETE,
322 | "INSERT": _snack.KEY_INSERT,
323 | " ": ord(" ")}
324 |
325 | for n in hotkeys.keys():
326 | hotkeys[hotkeys[n]] = n
327 | for o, c in [(ord(c), c) for c in string.ascii_letters + string.digits]:
328 | hotkeys[c] = o
329 | hotkeys[o] = c
330 |
331 |
332 | class Form:
333 | """ Base Form class, from which Grid, etc. inherit
334 |
335 | methods:
336 |
337 | - Form(self, helpArg = None) : constructor.
338 | - addHotKey(self, keyname) : keynames of form "F1" through "F12", "ESC"
339 | - add(self, widget) : Add a widget
340 | - run(self): run a form, expecting input
341 | - draw(self): draw form.
342 | - setTimer(self, timer) : add a timer
343 | - watchFile(self, file, flags) : watch a named file
344 | - setCurrent (self, co): Set a given widget as the current focus
345 | """
346 |
347 | def addHotKey(self, keyname):
348 | self.w.addhotkey(hotkeys[keyname])
349 |
350 | def add(self, widget):
351 | if 'hotkeys' in widget.__dict__:
352 | for key in widget.hotkeys.keys():
353 | self.addHotKey(key)
354 |
355 | if 'gridmembers' in widget.__dict__:
356 | for w in widget.gridmembers:
357 | self.add(w)
358 | elif 'w' in widget.__dict__:
359 | self.trans[widget.w.key] = widget
360 | return self.w.add(widget.w)
361 | return None
362 |
363 | def run(self):
364 | (what, which) = self.w.run()
365 | if (what == _snack.FORM_EXIT_WIDGET):
366 | return self.trans[which]
367 | elif (what == _snack.FORM_EXIT_TIMER):
368 | return "TIMER"
369 | elif (what == _snack.FORM_EXIT_FDREADY):
370 | return self.filemap[which]
371 |
372 | return hotkeys[which]
373 |
374 | def draw(self):
375 | self.w.draw()
376 | return None
377 |
378 | def __init__(self, helpArg=None):
379 | self.trans = {}
380 | self.filemap = {}
381 | self.w = _snack.form(helpArg)
382 | # we do the reference count for the helpArg in python! gross
383 | self.helpArg = helpArg
384 |
385 | def setCurrent(self, co):
386 | self.w.setcurrent(co.w)
387 |
388 | def setTimer(self, timer):
389 | self.w.settimer(timer)
390 |
391 | def watchFile(self, file, flags):
392 | self.filemap[file.fileno()] = file
393 | self.w.watchfd(file.fileno(), flags)
394 |
395 |
396 | class Grid:
397 | """Grid class.
398 |
399 | methods:
400 |
401 | - place(self,x,y): Return what is placed at (x,y)
402 | - setField(self, what, col, row, padding = (0, 0, 0, 0),
403 | anchorLeft = 0, anchorTop = 0, anchorRight = 0,
404 | anchorBottom = 0, growx = 0, growy = 0):
405 | used to add widget 'what' to grid.
406 | - Grid(self, *args): eg. g = Grid(2,3) for 2x3 grid
407 | """
408 |
409 | def place(self, x, y):
410 | return self.g.place(x, y)
411 |
412 | def setField(self, what, col, row, padding=(0, 0, 0, 0),
413 | anchorLeft=0, anchorTop=0, anchorRight=0,
414 | anchorBottom=0, growx=0, growy=0):
415 | self.gridmembers.append(what)
416 | anchorFlags = 0
417 | if (anchorLeft):
418 | anchorFlags = _snack.ANCHOR_LEFT
419 | elif (anchorRight):
420 | anchorFlags = _snack.ANCHOR_RIGHT
421 |
422 | if (anchorTop):
423 | anchorFlags = anchorFlags | _snack.ANCHOR_TOP
424 | elif (anchorBottom):
425 | anchorFlags = anchorFlags | _snack.ANCHOR_BOTTOM
426 |
427 | gridFlags = 0
428 | if (growx):
429 | gridFlags = _snack.GRID_GROWX
430 | if (growy):
431 | gridFlags = gridFlags | _snack.GRID_GROWY
432 |
433 | if ('g' in what.__dict__):
434 | return self.g.setfield(col, row, what.g, padding, anchorFlags,
435 | gridFlags)
436 | else:
437 | return self.g.setfield(col, row, what.w, padding, anchorFlags)
438 |
439 | def __init__(self, *args):
440 | self.g = _snack.grid(*args)
441 | self.gridmembers = []
442 |
443 |
444 | colorsets = {"ROOT": _snack.COLORSET_ROOT,
445 | "BORDER": _snack.COLORSET_BORDER,
446 | "WINDOW": _snack.COLORSET_WINDOW,
447 | "SHADOW": _snack.COLORSET_SHADOW,
448 | "TITLE": _snack.COLORSET_TITLE,
449 | "BUTTON": _snack.COLORSET_BUTTON,
450 | "ACTBUTTON": _snack.COLORSET_ACTBUTTON,
451 | "CHECKBOX": _snack.COLORSET_CHECKBOX,
452 | "ACTCHECKBOX": _snack.COLORSET_ACTCHECKBOX,
453 | "ENTRY": _snack.COLORSET_ENTRY,
454 | "LABEL": _snack.COLORSET_LABEL,
455 | "LISTBOX": _snack.COLORSET_LISTBOX,
456 | "ACTLISTBOX": _snack.COLORSET_ACTLISTBOX,
457 | "TEXTBOX": _snack.COLORSET_TEXTBOX,
458 | "ACTTEXTBOX": _snack.COLORSET_ACTTEXTBOX,
459 | "HELPLINE": _snack.COLORSET_HELPLINE,
460 | "ROOTTEXT": _snack.COLORSET_ROOTTEXT,
461 | "EMPTYSCALE": _snack.COLORSET_EMPTYSCALE,
462 | "FULLSCALE": _snack.COLORSET_FULLSCALE,
463 | "DISENTRY": _snack.COLORSET_DISENTRY,
464 | "COMPACTBUTTON": _snack.COLORSET_COMPACTBUTTON,
465 | "ACTSELLISTBOX": _snack.COLORSET_ACTSELLISTBOX,
466 | "SELLISTBOX": _snack.COLORSET_SELLISTBOX}
467 |
468 |
469 | class SnackScreen:
470 | """A Screen;
471 |
472 | methods:
473 |
474 | - Screen(self) : constructor
475 | - finish(self)
476 | - resume(self)
477 | - suspend(self)
478 | - doHelpCallback(self,arg) call callback with arg
479 | - helpCallback(self,cb): Set help callback
480 | - suspendcallback(self,cb, data=None) : set callback. data=data to pass to cb.
481 | - openWindow(self,left, top, width, height, title): Open a window.
482 | - pushHelpLine(self,text): put help line on screen. Returns current help line if text=None
483 | - setColor(self, colorset, fg, bg): Set foreground and background colors;
484 | colorset = key from snack.colorsets,
485 | fg & bg = english color names defined by S-Lang
486 | (ref: S-Lang Library C Programmer's Guide section:
487 | 8.4.4. Setting Character Attributes)
488 | """
489 |
490 | def __init__(self):
491 | _snack.init()
492 | (self.width, self.height) = _snack.size()
493 | self.pushHelpLine(None)
494 |
495 | def finish(self):
496 | return _snack.finish()
497 |
498 | def resume(self):
499 | _snack.resume()
500 |
501 | def suspend(self):
502 | _snack.suspend()
503 |
504 | def doHelpCallback(self, arg):
505 | self.helpCb(self, arg)
506 |
507 | def helpCallback(self, cb):
508 | self.helpCb = cb
509 | return _snack.helpcallback(self.doHelpCallback)
510 |
511 | def suspendCallback(self, cb, data=None):
512 | if data:
513 | return _snack.suspendcallback(cb, data)
514 | return _snack.suspendcallback(cb)
515 |
516 | def openWindow(self, left, top, width, height, title):
517 | return _snack.openwindow(left, top, width, height, title)
518 |
519 | def pushHelpLine(self, text):
520 | if (not text):
521 | return _snack.pushhelpline("*default*")
522 | else:
523 | return _snack.pushhelpline(text)
524 |
525 | def popHelpLine(self):
526 | return _snack.pophelpline()
527 |
528 | def drawRootText(self, left, top, text):
529 | return _snack.drawroottext(left, top, text)
530 |
531 | def centeredWindow(self, width, height, title):
532 | return _snack.centeredwindow(width, height, title)
533 |
534 | def gridWrappedWindow(self, grid, title, x=None, y=None):
535 | if x and y:
536 | return _snack.gridwrappedwindow(grid.g, title, x, y)
537 |
538 | return _snack.gridwrappedwindow(grid.g, title)
539 |
540 | def popWindow(self, refresh=True):
541 | if refresh:
542 | return _snack.popwindow()
543 | return _snack.popwindownorefresh()
544 |
545 | def refresh(self):
546 | return _snack.refresh()
547 |
548 | def setColor(self, colorset, fg, bg):
549 | if colorset in colorsets:
550 | return _snack.setcolor(colorsets[colorset], fg, bg)
551 | else:
552 | # assume colorset is an integer for the custom color set
553 | return _snack.setcolor(colorset, fg, bg)
554 |
555 |
556 | def reflow(text, width, flexDown=5, flexUp=5):
557 | """ returns a tuple of the wrapped text, the actual width, and the actual height
558 | """
559 | return _snack.reflow(text, width, flexDown, flexUp)
560 |
561 | # combo widgets
562 |
563 |
564 | class RadioGroup(Widget):
565 | """ Combo widget: Group of Radio buttons
566 |
567 | methods:
568 |
569 | - RadioGroup(self): constructor.
570 | - add(self,title, value, default = None): add a button. Returns button.
571 | - getSelection(self) : returns value of selected button | None
572 | """
573 |
574 | def __init__(self):
575 | self.prev = None
576 | self.buttonlist = []
577 |
578 | def add(self, title, value, default=None):
579 | if not self.prev and default is None:
580 | # If the first element is not explicitly set to
581 | # not be the default, make it be the default
582 | default = 1
583 | b = SingleRadioButton(title, self.prev, default)
584 | self.prev = b
585 | self.buttonlist.append((b, value))
586 | return b
587 |
588 | def getSelection(self):
589 | for (b, value) in self.buttonlist:
590 | if b.selected():
591 | return value
592 | return None
593 |
594 |
595 | class RadioBar(Grid):
596 | """ Bar of Radio buttons, based on Grid.
597 |
598 | methods:
599 |
600 | - RadioBar(self, screen, buttonlist) : constructor.
601 | - getSelection(self): return value of selected button
602 | """
603 |
604 | def __init__(self, screen, buttonlist):
605 | self.list = []
606 | self.item = 0
607 | self.group = RadioGroup()
608 | Grid.__init__(self, 1, len(buttonlist))
609 | for (title, value, default) in buttonlist:
610 | b = self.group.add(title, value, default)
611 | self.list.append((b, value))
612 | self.setField(b, 0, self.item, anchorLeft=1)
613 | self.item = self.item + 1
614 |
615 | def getSelection(self):
616 | return self.group.getSelection()
617 |
618 |
619 | # you normally want to pack a ButtonBar with growx = 1
620 |
621 | class ButtonBar(Grid):
622 | """ Bar of buttons, based on grid.
623 |
624 | methods:
625 |
626 | - ButtonBar(screen, buttonlist,buttonlist, compact = 0):
627 | - buttonPressed(self, result): Takes the widget returned by Form.run and looks to see
628 | if it was one of the widgets in the ButtonBar.
629 | """
630 |
631 | def __init__(self, screen, buttonlist, compact=0):
632 | self.list = []
633 | self.hotkeys = {}
634 | self.item = 0
635 | Grid.__init__(self, len(buttonlist), 1)
636 | for blist in buttonlist:
637 | if (isinstance(blist, types.StringType)):
638 | title = blist
639 | value = string.lower(blist)
640 | elif len(blist) == 2:
641 | (title, value) = blist
642 | else:
643 | (title, value, hotkey) = blist
644 | self.hotkeys[hotkey] = value
645 |
646 | if compact:
647 | b = CompactButton(title)
648 | else:
649 | b = Button(title)
650 | self.list.append((b, value))
651 | self.setField(b, self.item, 0, (1, 0, 1, 0))
652 | self.item = self.item + 1
653 |
654 | def buttonPressed(self, result):
655 | if result in self.hotkeys:
656 | return self.hotkeys[result]
657 |
658 | for (button, value) in self.list:
659 | if result == button:
660 | return value
661 | return None
662 |
663 |
664 | class GridFormHelp(Grid):
665 | """ Subclass of Grid, for the help form text.
666 |
667 | methods:
668 |
669 | - GridFormHelp(self, screen, title, help, *args) :
670 | - add (self, widget, col, row, padding = (0, 0, 0, 0),
671 | anchorLeft = 0, anchorTop = 0, anchorRight = 0,
672 | anchorBottom = 0, growx = 0, growy = 0):
673 | - runOnce(self, x = None, y = None): pop up the help window
674 | - addHotKey(self, keyname):
675 | - setTimer(self, keyname):
676 | - create(self, x = None, y = None):
677 | - run(self, x = None, y = None):
678 | - draw(self):
679 | - runPopup(self):
680 | - setCurrent (self, co):
681 | """
682 |
683 | def __init__(self, screen, title, help, *args):
684 | self.screen = screen
685 | self.title = title
686 | self.form = Form(help)
687 | self.childList = []
688 | self.form_created = 0
689 | args = list(args)
690 | args[:0] = [self]
691 | Grid.__init__(*tuple(args))
692 |
693 | def add(self, widget, col, row, padding=(0, 0, 0, 0),
694 | anchorLeft=0, anchorTop=0, anchorRight=0,
695 | anchorBottom=0, growx=0, growy=0):
696 | self.setField(widget, col, row, padding, anchorLeft,
697 | anchorTop, anchorRight, anchorBottom,
698 | growx, growy)
699 | self.childList.append(widget)
700 |
701 | def runOnce(self, x=None, y=None):
702 | result = self.run(x, y)
703 | self.screen.popWindow()
704 | return result
705 |
706 | def addHotKey(self, keyname):
707 | self.form.addHotKey(keyname)
708 |
709 | def setTimer(self, keyname):
710 | self.form.setTimer(keyname)
711 |
712 | def create(self, x=None, y=None):
713 | if not self.form_created:
714 | self.place(1, 1)
715 | for child in self.childList:
716 | self.form.add(child)
717 | self.screen.gridWrappedWindow(self, self.title, x, y)
718 | self.form_created = 1
719 |
720 | def run(self, x=None, y=None):
721 | self.create(x, y)
722 | return self.form.run()
723 |
724 | def draw(self):
725 | self.create()
726 | return self.form.draw()
727 |
728 | def runPopup(self):
729 | self.create()
730 | self.screen.gridWrappedWindow(self, self.title)
731 | result = self.form.run()
732 | self.screen.popWindow()
733 | return result
734 |
735 | def setCurrent(self, co):
736 | self.form.setCurrent(co)
737 |
738 |
739 | class GridForm(GridFormHelp):
740 | """ GridForm class (extends GridFormHelp):
741 |
742 | methods:
743 |
744 | - GridForm(self, screen, title, *args):
745 | """
746 |
747 | def __init__(self, screen, title, *args):
748 | myargs = (self, screen, title, None) + args
749 | GridFormHelp.__init__(*myargs)
750 |
751 |
752 | class CheckboxTree(Widget):
753 | """ CheckboxTree combo widget,
754 |
755 | methods:
756 |
757 | - CheckboxTree(self, height, scroll = 0, width = None, hide_checkbox = 0, unselectable = 0)
758 | constructor.
759 | - append(self, text, item = None, selected = 0):
760 | - addItem(self, text, path, item = None, selected = 0):
761 | - getCurrent(self):
762 | - getSelection(self):
763 | - setEntry(self, item, text):
764 | - setCurrent(self, item):
765 | - setEntryValue(self, item, selected = 1):
766 | - getEntryValue(self, item):
767 | """
768 |
769 | def append(self, text, item=None, selected=0):
770 | self.addItem(text, (snackArgs['append'], ), item, selected)
771 |
772 | def addItem(self, text, path, item=None, selected=0):
773 | if item is None:
774 | item = text
775 | key = self.w.checkboxtreeAddItem(text, path, selected)
776 | self.key2item[key] = item
777 | self.item2key[item] = key
778 |
779 | def getCurrent(self):
780 | curr = self.w.checkboxtreeGetCurrent()
781 | return self.key2item[curr]
782 |
783 | def __init__(self, height, scroll=0, width=None, hide_checkbox=0, unselectable=0):
784 | self.w = _snack.checkboxtree(height, scroll, hide_checkbox, unselectable)
785 | self.key2item = {}
786 | self.item2key = {}
787 | if (width):
788 | self.w.checkboxtreeSetWidth(width)
789 |
790 | def getSelection(self):
791 | selection = []
792 | list = self.w.checkboxtreeGetSelection()
793 | for key in list:
794 | selection.append(self.key2item[key])
795 | return selection
796 |
797 | def setEntry(self, item, text):
798 | self.w.checkboxtreeSetEntry(self.item2key[item], text)
799 |
800 | def setCurrent(self, item):
801 | self.w.checkboxtreeSetCurrent(self.item2key[item])
802 |
803 | def setEntryValue(self, item, selected=1):
804 | self.w.checkboxtreeSetEntryValue(self.item2key[item], selected)
805 |
806 | def getEntryValue(self, item):
807 | return self.w.checkboxtreeGetEntryValue(self.item2key[item])
808 |
809 |
810 | def ListboxChoiceWindow(screen, title, text, items,
811 | buttons=('Ok', 'Cancel'),
812 | width=40, scroll=0, height=-1, default=None,
813 | help=None):
814 | """
815 | - ListboxChoiceWindow(screen, title, text, items,
816 | buttons = ('Ok', 'Cancel'),
817 | width = 40, scroll = 0, height = -1, default = None,
818 | help = None):
819 | """
820 | if (height == -1):
821 | height = len(items)
822 |
823 | bb = ButtonBar(screen, buttons)
824 | t = TextboxReflowed(width, text)
825 | l = Listbox(height, scroll=scroll, returnExit=1)
826 | count = 0
827 | for item in items:
828 | if (isinstance(item, types.TupleType)):
829 | (text, key) = item
830 | else:
831 | text = item
832 | key = count
833 |
834 | if (default == count):
835 | default = key
836 | elif (default == item):
837 | default = key
838 |
839 | l.append(text, key)
840 | count = count + 1
841 |
842 | if (default is not None):
843 | l.setCurrent(default)
844 |
845 | g = GridFormHelp(screen, title, help, 1, 3)
846 | g.add(t, 0, 0)
847 | g.add(l, 0, 1, padding=(0, 1, 0, 1))
848 | g.add(bb, 0, 2, growx=1)
849 |
850 | rc = g.runOnce()
851 |
852 | return (bb.buttonPressed(rc), l.current())
853 |
854 |
855 | def ButtonChoiceWindow(screen, title, text,
856 | buttons=['Ok', 'Cancel'],
857 | width=40, x=None, y=None, help=None):
858 | """
859 | - ButtonChoiceWindow(screen, title, text,
860 | buttons = [ 'Ok', 'Cancel' ],
861 | width = 40, x = None, y = None, help = None):
862 | """
863 | bb = ButtonBar(screen, buttons)
864 | t = TextboxReflowed(width, text, maxHeight=screen.height - 12)
865 |
866 | g = GridFormHelp(screen, title, help, 1, 2)
867 | g.add(t, 0, 0, padding=(0, 0, 0, 1))
868 | g.add(bb, 0, 1, growx=1)
869 | return bb.buttonPressed(g.runOnce(x, y))
870 |
871 |
872 | def EntryWindow(screen, title, text, prompts, allowCancel=1, width=40,
873 | entryWidth=20, buttons=['Ok', 'Cancel'], help=None):
874 | """
875 | EntryWindow(screen, title, text, prompts, allowCancel = 1, width = 40,
876 | entryWidth = 20, buttons = [ 'Ok', 'Cancel' ], help = None):
877 | """
878 | bb = ButtonBar(screen, buttons)
879 | t = TextboxReflowed(width, text)
880 |
881 | count = 0
882 | for n in prompts:
883 | count = count + 1
884 |
885 | sg = Grid(2, count)
886 |
887 | count = 0
888 | entryList = []
889 | for n in prompts:
890 | if (isinstance(n, types.TupleType)):
891 | (n, e) = n
892 | if (type(e) in types.StringTypes):
893 | e = Entry(entryWidth, e)
894 | else:
895 | e = Entry(entryWidth)
896 |
897 | sg.setField(Label(n), 0, count, padding=(0, 0, 1, 0), anchorLeft=1)
898 | sg.setField(e, 1, count, anchorLeft=1)
899 | count = count + 1
900 | entryList.append(e)
901 |
902 | g = GridFormHelp(screen, title, help, 1, 3)
903 |
904 | g.add(t, 0, 0, padding=(0, 0, 0, 1))
905 | g.add(sg, 0, 1, padding=(0, 0, 0, 1))
906 | g.add(bb, 0, 2, growx=1)
907 |
908 | result = g.runOnce()
909 |
910 | entryValues = []
911 | count = 0
912 | for n in prompts:
913 | entryValues.append(entryList[count].value())
914 | count = count + 1
915 |
916 | return (bb.buttonPressed(result), tuple(entryValues))
917 |
918 |
919 | class CListbox(Grid):
920 | """Clistbox convenience class.
921 |
922 | methods:
923 |
924 | - Clistbox(self, height, cols, cols_widths, scroll = 0) : constructor
925 | - colFormText(self, col_text, align = None, adjust_width = 0) : column text.
926 | - append(self, col_text, item, col_text_align = None) :
927 | - insert(self, col_text, item, before, col_text_align = None)
928 | - delete(self, item)
929 | - replace(self, col_text, item, col_text_align = None)
930 | - current(self) : returns current item
931 | - setCurrent(self, item): sets an item as current
932 | - clear(self): clear the listbox
933 |
934 | Alignments may be LEFT, RIGHT, CENTER, None
935 | """
936 |
937 | def __init__(self, height, cols, col_widths, scroll=0,
938 | returnExit=0, width=0, col_pad=1,
939 | col_text_align=None, col_labels=None,
940 | col_label_align=None, adjust_width=0):
941 |
942 | self.cols = cols
943 | self.col_widths = col_widths[:]
944 | self.col_pad = col_pad
945 | self.col_text_align = col_text_align
946 |
947 | if col_labels is not None:
948 | Grid.__init__(self, 1, 2)
949 | box_y = 1
950 |
951 | lstr = self.colFormText(col_labels, col_label_align,
952 | adjust_width=adjust_width)
953 | self.label = Label(lstr)
954 | self.setField(self.label, 0, 0, anchorLeft=1)
955 |
956 | else:
957 | Grid.__init__(self, 1, 1)
958 | box_y = 0
959 |
960 | self.listbox = Listbox(height, scroll, returnExit, width)
961 | self.setField(self.listbox, 0, box_y, anchorRight=1)
962 |
963 | def colFormText(self, col_text, align=None, adjust_width=0):
964 | i = 0
965 | str = ""
966 | c_len = len(col_text)
967 | while (i < self.cols) and (i < c_len):
968 |
969 | cstr = col_text[i]
970 | cstrlen = _snack.wstrlen(cstr)
971 | if self.col_widths[i] < cstrlen:
972 | if adjust_width:
973 | self.col_widths[i] = cstrlen
974 | else:
975 | cstr = cstr[:self.col_widths[i]]
976 |
977 | delta = self.col_widths[i] - _snack.wstrlen(cstr)
978 |
979 | if delta > 0:
980 | if align is None:
981 | a = LEFT
982 | else:
983 | a = align[i]
984 |
985 | if a == LEFT:
986 | cstr = cstr + (" " * delta)
987 | if a == CENTER:
988 | cstr = (" " * (delta / 2)) + cstr + \
989 | (" " * ((delta + 1) / 2))
990 | if a == RIGHT:
991 | cstr = (" " * delta) + cstr
992 |
993 | if i != c_len - 1:
994 | pstr = (" " * self.col_pad)
995 | else:
996 | pstr = ""
997 |
998 | str = str + cstr + pstr
999 |
1000 | i = i + 1
1001 |
1002 | return str
1003 |
1004 | def append(self, col_text, item, col_text_align=None):
1005 | if col_text_align is None:
1006 | col_text_align = self.col_text_align
1007 | text = self.colFormText(col_text, col_text_align)
1008 | self.listbox.append(text, item)
1009 |
1010 | def insert(self, col_text, item, before, col_text_align=None):
1011 | if col_text_align is None:
1012 | col_text_align = self.col_text_align
1013 | text = self.colFormText(col_text, col_text_align)
1014 | self.listbox.insert(text, item, before)
1015 |
1016 | def delete(self, item):
1017 | self.listbox.delete(item)
1018 |
1019 | def replace(self, col_text, item, col_text_align=None):
1020 | if col_text_align is None:
1021 | col_text_align = self.col_text_align
1022 | text = self.colFormText(col_text, col_text_align)
1023 | self.listbox.replace(text, item)
1024 |
1025 | def current(self):
1026 | return self.listbox.current()
1027 |
1028 | def setCurrent(self, item):
1029 | self.listbox.setCurrent(item)
1030 |
1031 | def clear(self):
1032 | self.listbox.clear()
1033 |
1034 |
1035 | def customColorset(x):
1036 | return 30 + x
1037 |
--------------------------------------------------------------------------------
/src/w_lib/pysnack/snack_lib.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # coding=utf8
3 | from snack import *
4 |
5 |
6 | def warwindows(screen, title, text, help=None):
7 | """
8 | # 警告窗口
9 | """
10 | btn = Button("确定")
11 | war = GridForm(screen, title, 20, 16)
12 | war.add(Label(text), 0, 1)
13 | war.add(Label(""), 0, 2)
14 | war.add(btn, 0, 3)
15 | war.runOnce(43, 8)
16 | return 0
17 |
18 | def conformwindows(screen, text, help=None):
19 | """
20 | # 确认窗口
21 | """
22 | bb = ButtonBar(screen, (("确定", "yes"), ("取消", "no")), compact=1)
23 | g = GridForm(screen, text, 20, 16)
24 | g.add(Label(text), 0, 2)
25 | g.add(bb, 0, 3, (10, 0, 10, 0), growx=1)
26 | re = g.runOnce(43, 8)
27 | return (bb.buttonPressed(re), re)
28 |
29 |
30 | class Mask(object):
31 | """
32 | An input mask.
33 | """
34 |
35 | def __init__(self, screen, title="unnamed mask", width=30):
36 | """
37 | Creates an input mask with a title.
38 | The width is applied to the right side of the window.
39 | """
40 | self._width = width
41 | self._screen = screen
42 | self.g = GridForm(self._screen, title, 1, 20)
43 | self.subgrid = Grid(2, 20)
44 | self._row = 0
45 | self._row_grid = 0
46 | self._elements = {}
47 | self._buttons = 0
48 | self._checks_box = 0
49 | self._checks_entrylist = []
50 |
51 | def entry(self, label, name, text="", password=0):
52 | """
53 | Creates an entry for text.
54 | """
55 | self.subgrid.setField(Label(label), 0, self._row, (0, 0, 1, 1))
56 |
57 | self._elements[name] = Entry(self._width, text, password=password)
58 | self.subgrid.setField(self._elements[name], 1, self._row, (0, 0, 0, 1))
59 | self._row += 1
60 |
61 | def text(self, label="", text=""):
62 | """
63 | Creates text.
64 | """
65 | self.subgrid.setField(Label(label), 0, self._row, (0, 0, 0, 1))
66 | #self.subgrid.setField( TextboxReflowed(self._width,text) , 1, self._row, (0,0,0,1) )
67 | self.subgrid.setField(
68 | TextboxReflowed(
69 | self._width,
70 | text,
71 | flexDown=5,
72 | flexUp=10,
73 | maxHeight=-1),
74 | 1,
75 | self._row,
76 | (0,
77 | 0,
78 | 0,
79 | 1))
80 | self._row += 1
81 |
82 | def password(self, label, name, text=""):
83 | """
84 | Creates an password entry.
85 | """
86 | self.entry(label, name, text, password=1)
87 |
88 | def buttons(self, yes=u"确定", no=u"取消"):
89 | """
90 | Creates a set of buttons given as kwargs.
91 | IE: mask.buttons(yes="Yes", no="No")
92 | """
93 | self._buttons = ButtonBar(self._screen, ((yes, "yes"), (no, "no")))
94 | self.g.add(self.subgrid, 0, self._row_grid)
95 | self.g.add(self._buttons, 0, self._row_grid + 1)
96 | #self.g.add( self.subgrid, 0, self._row_grid)
97 | #self.g.add( self._buttons, 0, self._row_grid+1)
98 |
99 | def radios(self, label, name, options):
100 | """
101 | Creates a radio group.
102 | Options are given as [ (label, value, checked), ... ] where
103 | checked equ. 0/1.
104 | """
105 | self.subgrid.setField(Label(label), 0, self._row, (0, 0, 1, 1))
106 |
107 | self._elements[name] = RadioBar(self._screen, options)
108 | self.subgrid.setField(
109 | self._elements[name], 1, self._row, (0, 0, 0, 1), anchorLeft=1)
110 |
111 | self._row += 1
112 |
113 | def list(self, label, name, options, height=None, scroll=1):
114 | """
115 | Creates a single choice list.
116 | Options are given as [ (label, value, checked), ... ] where
117 | checked equ. 0/1.
118 | """
119 | self.subgrid.setField(Label(label), 0, self._row, (0, 0, 1, 1))
120 |
121 | if height is None:
122 | height = len(options)
123 | self._elements[name] = Listbox(
124 | height=height, width=self._width, scroll=scroll)
125 |
126 | for option in options:
127 | (key, value, selected) = option
128 | self._elements[name].append(key, value)
129 | if selected:
130 | self._elements[name].setCurrent(value)
131 |
132 | self.subgrid.setField(
133 | self._elements[name], 1, self._row, (0, 0, 0, 1), anchorLeft=1)
134 |
135 | self._row += 1
136 |
137 | def checks(self, label, name, options, height=None, scroll=1):
138 | """
139 | Creates a set of checkboxes.
140 | Options are given as [ (label, value, checked), ... ] where
141 | checked equ. 0/1.
142 | """
143 | self.subgrid.setField(Label(label), 0, self._row, (0, 0, 1, 1))
144 |
145 | if height is None:
146 | height = len(options)
147 |
148 | self._elements[name] = CheckboxTree(
149 | height=height, scroll=scroll, width=self._width)
150 |
151 | for option in options:
152 | (key, value, selected) = option
153 | self._elements[name].append(key, value, selected)
154 | self.subgrid.setField(
155 | self._elements[name],
156 | 1,
157 | self._row,
158 | (0,
159 | 0,
160 | 0,
161 | 1),
162 | anchorLeft=1,
163 | growx=1)
164 |
165 | self._row += 1
166 |
167 | def checks_entry(self, label, name, checked, entry_list):
168 | """
169 | (labelname,name,checked,[ (label, name,text), ... ])
170 | """
171 | self._checks_box = name
172 | self.subgrid.setField(Label(label), 0, self._row)
173 | self._elements[name] = Checkbox("")
174 | self.subgrid.setField(self._elements[name], 1, self._row, anchorLeft=1)
175 | self._elements[name].setCallback(self.checkBox_flag)
176 | if checked:
177 | self._elements[name].setValue('*')
178 | self._row += 1
179 | for option in entry_list:
180 | (label, name, text) = option
181 | self.subgrid.setField(Label(label), 0, self._row)
182 | self._elements[name] = Entry(self._width, text)
183 | self._checks_entrylist.append(name)
184 | self.subgrid.setField(
185 | self._elements[name], 1, self._row, (0, 0, 0, 1))
186 | self._row += 1
187 | self.checkBox_flag()
188 |
189 | def checkBox_flag(self):
190 | if self._checks_box:
191 | if self._elements[self._checks_box].selected():
192 | state = FLAGS_SET
193 | else:
194 | state = FLAGS_RESET
195 |
196 | for i in self._checks_entrylist:
197 | self._elements[i].setFlags(FLAG_DISABLED, state)
198 |
199 | def run(self, width=0, height=0):
200 | """
201 | Runs until a button is pressed.
202 | Returns [ button, { values } ].
203 | """
204 | if width and height:
205 | btn = self.g.runOnce(width, height)
206 | else:
207 | btn = self.g.runOnce()
208 | button = self._buttons.buttonPressed(btn)
209 |
210 | cmd = None
211 | results = {}
212 |
213 | cmd = button
214 | if btn == 'F12':
215 | cmd = 'F12'
216 |
217 | for name in self._elements:
218 | if 'value' in dir(self._elements[name]):
219 | results[name] = self._elements[name].value()
220 | if 'getSelection' in dir(self._elements[name]):
221 | results[name] = self._elements[name].getSelection()
222 | if 'current' in dir(self._elements[name]):
223 | results[name] = self._elements[name].current()
224 |
225 | return [cmd, results]
226 |
227 |
228 | class SnackOutput(object):
229 | def __init__(self, screen, title="unnamed mask", width=30):
230 | self._screen = screen
231 | self.g = GridForm(self._screen, title, 20, width)
232 | self._row = 0
233 |
234 | def text(self, text=""):
235 | """
236 | Creates text.
237 | """
238 | self.g.add(Label(text), 0, self._row, anchorLeft=1)
239 | self._row += 1
240 |
241 | def run(self, width=0, height=0):
242 | btn = Button("确定")
243 | self.g.add(btn, 0, self._row)
244 | self.g.runOnce(width, height)
245 |
246 | # test
247 |
248 |
249 | def test_Mask(screen, logger):
250 | m = Mask(screen, "test_windows", 35)
251 | m.text("label_test1", "ceshi_text")
252 | m.entry("label_test1", "entry_test1", "0")
253 | m.entry("label_test2", "entry_test2", "0")
254 | m.checks("复选框", "checks_list", [
255 | ('checks_name1', 'checks1', 0),
256 | ('checks_name2', 'checks2', 0),
257 | ('checks_name3', 'checks3', 0),
258 | ('checks_name4', 'checks4', 1),
259 | ('checks_name5', 'checks5', 0),
260 | ('checks_name6', 'checks6', 0),
261 | ('checks_name7', 'checks7', 0),
262 | ],
263 | height=3
264 | )
265 | m.radios("单选框", "radios", [
266 | ('radios_name1', 'radios1', 0),
267 | ('radios_name2', 'radios2', 1),
268 | ('radios_name3', 'radios3', 0)])
269 | m.checks_entry("空格选择下", "checks_entry", 1, [
270 | ('c_entry1', 'c_entry1', 'c_entry1')])
271 |
272 | m.buttons(yes="Sava&Quit", no="Quit")
273 | #(cmd, results) = m.run(12,3)
274 | (cmd, results) = m.run()
275 | logger.debug(str(cmd) + " " + str(results))
276 | if cmd == "yes":
277 | rx = conformwindows(screen, "确认操作")
278 | if rx[0] == "yes" or rx[1] == "F12":
279 | """exe"""
280 | return
281 | else:
282 | logger.debug("cancel this operation")
283 | return
284 | else:
285 | return
286 | # return cmd,results
287 |
288 |
289 | def test_snack_output(screen):
290 | m = Snack_output(screen, "test_windows1_2", 35)
291 | m.text("ceshijjjjjjjjjjjxdffffffffffffffff")
292 | m.text("xxxfffxxxxxxxxxxxxxx")
293 | m.text("xxxxxxxxxxxxxxxxx")
294 | m.text("xxxxxxxxxxxxxxxxx")
295 | m.text("xxxxxxxxxxxxxxxxx")
296 | m.run(43, 3)
297 |
298 |
299 | if __name__ == "__main__":
300 |
301 | import os
302 | import sys
303 | root_path = os.path.split(os.path.realpath(__file__))[0]
304 | sys.path.insert(0, os.path.join(root_path, '..'))
305 | from blog import Log
306 | debug = False
307 | logpath = "/tmp/test_snack_lib.log"
308 | logger = Log(logpath, level="debug", is_console=debug, mbs=5, count=5)
309 |
310 | # snack
311 | from snack_lib import *
312 | screen = SnackScreen()
313 | screen.setColor("ROOT", "white", "blue")
314 | screen.setColor("ENTRY", "white", "blue")
315 | screen.setColor("LABEL", "black", "white")
316 | screen.setColor("HELPLINE", "white", "blue")
317 | screen.setColor("TEXTBOX", "black", "yellow")
318 | # snack_end
319 | try:
320 | logger.debug("test_start===================================================")
321 | # ListboxChoiceWindow()
322 | action, selection = ListboxChoiceWindow(screen, 'Title 2',
323 | 'Choose one item from the list below:',
324 | ('exit page', 'entry_page'), default=0,
325 | help="Help for a listbox")
326 | logger.debug(action)
327 | logger.debug(selection)
328 | if action in (None, "ok"):
329 | if selection == 0:
330 | test_Mask(screen, logger)
331 | else:
332 | test_snack_output(screen)
333 | logger.debug("test_ok======================================================")
334 | except Exception as e:
335 | logger.debug(e)
336 | finally:
337 | screen.finish()
338 |
--------------------------------------------------------------------------------
/tools/install_lib.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #########################################################################
3 | # File Name: install_lib.sh
4 | # Author: meetbill
5 | # mail: meetbill@163.com
6 | # Created Time: 2017-10-21 00:18:40
7 | #########################################################################
8 | CUR_DIR=$(cd `dirname $0`; pwd)
9 | cd ${CUR_DIR}
10 | if [[ ! -e "/usr/lib64/libslang.so.2" ]]
11 | then
12 | echo "this system not have libslang.so.2 lib"
13 | cp -d ./w_lib64/libslang.so.2 /usr/lib64/
14 | cp ./w_lib64/libslang.so.2.2.1 /usr/lib64/
15 | chmod 777 /usr/lib64/libslang.so.2
16 | fi
17 |
18 | if [[ ! -e "/usr/lib64/libnewt.so.0.52" ]]
19 | then
20 | echo "this system not have libnewt.so.0.52"
21 | cp -d ./w_lib64/libnewt.so.0.52 /usr/lib64/
22 | cp ./w_lib64/libnewt.so.0.52.11 /usr/lib64/
23 | fi
24 |
25 |
26 |
--------------------------------------------------------------------------------
/tools/w_lib64/libnewt.so.0.52:
--------------------------------------------------------------------------------
1 | libnewt.so.0.52.11
--------------------------------------------------------------------------------
/tools/w_lib64/libnewt.so.0.52.11:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/meetbill/py_menu/31eb6b8ce5840be1984f30ddb74dc9bb0b70a5e2/tools/w_lib64/libnewt.so.0.52.11
--------------------------------------------------------------------------------
/tools/w_lib64/libslang.so.2:
--------------------------------------------------------------------------------
1 | libslang.so.2.2.1
--------------------------------------------------------------------------------
/tools/w_lib64/libslang.so.2.2.1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/meetbill/py_menu/31eb6b8ce5840be1984f30ddb74dc9bb0b70a5e2/tools/w_lib64/libslang.so.2.2.1
--------------------------------------------------------------------------------