repo
string
commit
string
message
string
diff
string
pawelkaczor/pawelkaczor.github.com
6a6f3b07c83385d81b91e283891a47eabfd9b14a
improve
diff --git a/_posts/mr-vcsh-prezto-user-guide.md b/_posts/mr-vcsh-prezto-user-guide.md index 8ab9565..c8d4c0a 100644 --- a/_posts/mr-vcsh-prezto-user-guide.md +++ b/_posts/mr-vcsh-prezto-user-guide.md @@ -1,99 +1,118 @@ # myrepos && vcsh && prezto - User Guide This document serves as a single source of information related to configuration of **myrepos & vcsh & prezto (zsh)** combo. # myrepos https://github.com/joeyh/myrepos **mr** - a tool to manage all your version control repos **mr** is configured by .mrconfig file, which list the repositories. **mr** supports vcsh repositories! #### vcsh repository configuration file - example ``` [$HOME/.config/vcsh/repo.d/documents.git] checkout = vcsh clone $DOCUMENTS_GIT_REPO documents vcsh_status = vcsh documents status ~/Documents grep = ack-grep "$@" ``` --- * **Note** **mr grep** will not work for vcsh repository unless the **grep** command is defined (as shown above). Make sure **ack-grep** is installed. Leave empty line at the end of the repo configuration file! This is necessary because the repo configs are **included** from the ~/.mrconfig file. Define **vcsh_status** only if you do not generate .gitignore file (see vcsh section for more details). --- -#### Commands +#### Less known mr commands - **mr ci** - Commits changes to each repository. (By default, changes are pushed to the remote repository too, when using distributed systems like git) The optional -m parameter allows specifying a commit message. # vcsh https://github.com/RichiH/vcsh vcsh - Version Control System for $HOME - multiple Git repositories in $HOME >> vcsh was designed with myrepos, a tool to manage Multiple Repositories, in mind and the two integrate very nicely. The myrepos tool (mr) has native support for vcsh repositories vcsh repositories are by default located under **$XDG_CONFIG_HOME/vcsh/repo.d** #### Ignored files >> vcsh can generate per-repo .gitignore files (in .gitignore.d/<repo_name>) by running vcsh write-gitignore <repo_name>. That will cause each git repo to ignore anything that is not specifically tracked in itself. This covers not only the git status use case but a few others as well. --- * **Note** Do not run **vcsh write-gitignore** for a repo if you expect new files to arrive often in that repo. If you do not generate .gitignore file for a repo, make sure you define **vcsh_status** command (see mr section above). Otherwise **mr st** and **vcsh status** commands will report many untracked files (because different git repos share the same ($HOME) working directory) - if I remember correctly. Once you run **vcsh write-gitignore** for a repo, newly added files will not be tracked automatically! You will have to add them manually to the repo!. The git add command can be used to add ignored files with the -f (force) option. After adding a file to the repo manually, you should rerun **vcsh write-gitignore** command. + You need to decide in which git repo you want to store the generated *~/.gitignore.d/<repo_name>* file. You can choose the repo the file was generated for. Or maybe you want to store all *~/.gitignore.d/* files in a separate repo? + + **TODO**: automate the workflow related to the maintenance of *~/.gitignore.d/* files. --- #### vcsh-modules https://github.com/lierdakil/vcsh-modules/wiki vcsh-modules is intended for improving support of **git submodules** in vcsh. +To define git submodules in a repository, create a configuration file *.gitmodules.d/<repo_name>* in the repository. The configuration file should specify git submodules. See example below: + +``` +[submodule ".config/awesome/vicious"] + path = .config/awesome/vicious + url = http://git.sysphere.org/vicious +[submodule ".config/awesome/uzful"] + path = .config/awesome/uzful + url = https://github.com/dodo/uzful.git +``` + +#### Less known vcsh commands + +* list-tracked - List all files tracked by vcsh +* which <substring> - Find substring in name of any tracked file + # Prezto https://github.com/sorin-ionescu/prezto My fork: https://github.com/pawelkaczor/prezto Prezto is a configuration framework for Zsh. The Prezto git repository should be cloned to **~/.zprezto** directory. It contains **git submodules** that point to external git repositories hosting **Prezto modules**. --- * **Note** To update the Prezto modules run: ```git submodule update --init --recursive``` from ~/.zprezto directory. You should fork the Prezto and clone from the fork. Add **upstream** remote (eg. https://github.com/sorin-ionescu/prezto) to your local prezto git repository if you cloned from your fork, so you can merge changes from the upstream. For some reason I have not configured Prezto as a vcsh repository. Perhaps because of some issues with **git submodules**. **TODO**: update **vcsh-modules** and try to configure Prezto as a vcsh repository. --- \ No newline at end of file
pawelkaczor/pawelkaczor.github.com
046dcadb440740823ad61c6aaef7a7707e96ce03
add "myrepos && vcsh && prezto - User Guide" post
diff --git a/_posts/mr-vcsh-prezto-user-guide.md b/_posts/mr-vcsh-prezto-user-guide.md new file mode 100644 index 0000000..696fde0 --- /dev/null +++ b/_posts/mr-vcsh-prezto-user-guide.md @@ -0,0 +1,96 @@ +# myrepos && vcsh && prezto - User Guide + +This document serves as a single source of information related to configuration of **myrepos & vcsh & prezto (zsh)** combo. + +# myrepos + +https://github.com/joeyh/myrepos + +**mr** - a tool to manage all your version control repos + +**mr** is configured by .mrconfig files, which list the repositories. + +**mr** supports vcsh repositories! + +#### vcsh repository configuration file - example + +``` +[$HOME/.config/vcsh/repo.d/documents.git] +checkout = vcsh clone https://[email protected]/pkaczor/documents.git documents +vcsh_status = vcsh documents status ~/Documents +grep = ack-grep "$@" +``` + +--- + * **Note** + **mr grep** will not work for vcsh repository unless the **grep** command is defined (as shown above). + + Make sure **ack-grep** is installed. + + Leave empty line at the end of the repo configuration file! This is necessary because the repo configs are **included** from the ~/.mrconfig file. + + Define **vcsh_status** only if you do not generate .gitignore file (see vcsh section for more details). +--- + + +#### Commands + +- **mr ci** - Commits changes to each repository. (By default, changes are pushed to the remote repository too, when using distributed systems like git) The optional -m parameter allows specifying a commit message. + + +# vcsh + +https://github.com/RichiH/vcsh + +vcsh - Version Control System for $HOME - multiple Git repositories in $HOME + +>> vcsh was designed with myrepos, a tool to manage Multiple Repositories, in mind and the two integrate very nicely. The myrepos tool (mr) has native support for vcsh repositories + + +vcsh repositories are by default located under **$XDG_CONFIG_HOME/vcsh/repo.d** + +#### Ignored files + +>> vcsh can generate per-repo .gitignore files (in .gitignore.d/<repo_name>) by running vcsh write-gitignore <repo_name>. That will cause each git repo to ignore anything that is not specifically tracked in itself. This covers not only the git status use case but a few others as well. + +--- +* **Note** + Do not run **vcsh write-gitignore** for a repo if you expect new files to arrive often in that repo. + + If you do not generate .gitignore file for a repo, make sure you define **vcsh_status** command (see mr section above). Otherwise **mr st** and **vcsh status** commands will report many untracked files (because different git repos share the same ($HOME) working directory) - if I remember correctly. + + Once you run **vcsh write-gitignore** for a repo, newly added files will not be tracked automatically! You will have to add them manually to the repo!. The git add command can be used to add ignored files with the -f (force) option. + + After adding a file to the repo manually, you should rerun **vcsh write-gitignore** command. +--- + +#### vcsh-modules + +https://github.com/lierdakil/vcsh-modules/wiki + +vcsh-modules is intended for improving support of **git submodules** in vcsh. + +# Prezto + +https://github.com/sorin-ionescu/prezto +My fork: https://github.com/pawelkaczor/prezto + +Prezto is a configuration framework for Zsh. + +The Prezto git repository should be cloned to **~/.zprezto** directory. It contains **git submodules** that point to external git repositories hosting **Prezto modules**. + +--- + * **Note** + To update the Prezto modules run: ```git submodule update --init --recursive``` from ~/.zprezto directory. + + You should fork the Prezto and clone from the fork. + + Add **upstream** remote (eg. https://github.com/sorin-ionescu/prezto) to your local prezto git repository if you cloned from your fork, so you can merge changes from the upstream. + + For some reason I have not configured Prezto as a vcsh repository. Perhaps because of some issues with **git submodules**. **TODO**: update **vcsh-modules** and try to configure Prezto as a vcsh repository. + +--- + + + +
pawelkaczor/pawelkaczor.github.com
8641e12ddbf53a3c2aa8a64917738b3f17a7eced
minor fixes
diff --git a/_posts/reactive-ddd/reactive-business-processes.md b/_posts/reactive-ddd/reactive-business-processes.md index b3acf05..855caaa 100644 --- a/_posts/reactive-ddd/reactive-business-processes.md +++ b/_posts/reactive-ddd/reactive-business-processes.md @@ -1,171 +1,182 @@ ### Reactive DDD with Akka - Reactive business processes - #### Introduction -In the previous [post](http://pkaczor.blogspot.com/2016/08/reactive-ddd-with-akka-putting-the-pieces-together.html) we learned how to implement a sample ordering service using the [Akka-DDD](https://github.com/pawelkaczor/akka-ddd) framework. The service exposed the `Reservation Office` responsible for preparing and confirming the reservation of products, that the client added to his/her shopping cart. We learned that an office is a command handling business entity whose sole responsibility is to validate and process the commands. If the command validation succeeds, an appropriate event is written to the office journal. The `Reservation Office` alone is obviously not able to execute the whole Ordering Process engaging activities like payment processing, invoicing and goods delivery. Therefore, to extend the functionality of the system we need to introduce two new subsystems / services: `Invoicing` and `Shipping`, that will be hosting `Invoicing Office` and `Shipping Office` respectively. The question arises, how to employ multiple offices to work on a business process and coordinate the workflow, so that the process is executed as defined by the business. To answer this question, we will first learn how to model a **business process** in a distributed system. Then we will review the implementation of a sample Ordering Process developed under the [ddd-leaven-akka-v2](https://github.com/pawelkaczor/ddd-leaven-akka-v2) project. Finally we will see how Akka-DDD facilitates the implementation of business processes in a distributed system. +In the previous [post](http://pkaczor.blogspot.com/2016/08/reactive-ddd-with-akka-putting-the-pieces-together.html) we learned how to implement a sample ordering service using the [Akka-DDD](https://github.com/pawelkaczor/akka-ddd) framework. The service exposed the `Reservation Office` responsible for preparing and confirming the reservation of products, that the client added to their shopping cart. We learned that an office is a command handling business entity whose sole responsibility is to validate and process the commands. If the command validation succeeds, an appropriate event is written to the office journal. + +The `Reservation Office` alone is obviously not able to execute the whole Ordering Process engaging activities like payment processing, invoicing and goods delivery. Therefore, to extend the functionality of the system we need to introduce two new subsystems / services: `Invoicing` and `Shipping`, that will be hosting `Invoicing Office` and `Shipping Office` respectively. + +The question arises, how to employ multiple offices to work on a business process and coordinate the workflow, so that the process is executed as defined by the business. To answer this question, we will first learn how to model a **business process** in a distributed system. Then we will review the implementation of a sample Ordering Process developed under the [ddd-leaven-akka-v2](https://github.com/pawelkaczor/ddd-leaven-akka-v2) project. Finally we will see how Akka-DDD facilitates the implementation of business processes in a distributed system. #### Business processes and SOA -To deliver a business value, an enterprise needs to perform its activities in a coordinated manner. Regardless of whether it is a production line or a decision chain, activities needs to be performed in a specific order accordingly to the rules defined by the business. The business process thus defines precisely what activities, in which order and under which conditions need to be performed, so that the desired business goal gets achieved. The coordination of the activities implies the information exchange between the collaborators. In the past, business processes were driven by the paper documents flying back and forth between process actors. Nowadays, when more and more activities are performed by computers and machines, the business process execution is realized as a message flow between services. Unfortunately though, for a variety of reasons, the implementation of the **Service-Oriented Architecture (SOA)**, very often ended up with a **Big Ball of Mud** as well as scalability and reliability issues (just to name a few) in the runtime. +To deliver a business value, an enterprise needs to perform its activities in a coordinated manner. Regardless of whether it is a production line or a decision chain, activities needs to be performed in a specific order accordingly to the rules defined by the business. The business process thus defines precisely what activities, in which order and under which conditions need to be performed, so that the desired business goal gets achieved. + +The coordination of the activities implies the information exchange between the collaborators. In the past, business processes were driven by the paper documents flying back and forth between process actors. Nowadays, when more and more activities are performed by computers and machines, the business process execution is realized as a message flow between services. Unfortunately though, for a variety of reasons, the implementation of the **Service-Oriented Architecture (SOA)**, very often ended up with a **Big Ball of Mud** as well as scalability and reliability issues (just to name a few) in the runtime. The recent move towards the **SOA 2.0** / Event-driven SOA / "SOA done Right" / Microservices (choose your favorite buzzword) enables delivering more light-weight, reliable / fault-tolerant and scalable SOA implementations. When it comes to modeling and executing business processes, the key realization is that since **business processes are event-driven**, the same events that get written to the office journals could be used to trigger the start or the continuation of business processes. If so, any business process can be implemented as an **event-sourced actor** (called **Process Manager**) assuming it gets subscribed to a single stream of events (coming from an arbitrary number of offices) it is interested in. Once an event is received, the Process Manager executes an action, usually by sending a command to an office, and updates its state by writing the event to its journal. In this way, the Process Manager coordinates the work of the offices within the process. What is important is that **the logic of a business process is expressed in terms of incoming events, state transitions and outgoing commands**. This seems to be a quite powerful domain specific language for describing business processes. Let's take a look at the definition of an sample Ordering Process, that is written using the DSL offered by the Akka-DDD: #### Ordering Process - definition ```scala startWhen { case _: ReservationConfirmed => New } andThen { case New => { case ReservationConfirmed(reservationId, customerId, totalAmount) => WaitingForPayment { ⟶ (CreateInvoice(processManagerId, reservationId, customerId, totalAmount, now())) ⟵ (PaymentExpired(processManagerId, reservationId)) in 3.minutes } } case WaitingForPayment => { case PaymentExpired(invoiceId, orderId) => ⟶ (CancelInvoice(invoiceId, orderId)) case OrderBilled(_, orderId, _, _) => DeliveryInProgress { ⟶ (CloseReservation(orderId)) ⟶ (CreateShipment(UUID(), orderId)) } case OrderBillingFailed(_, orderId) => Failed { ⟶ (CancelReservation(orderId)) } } } ``` Source: [OrderProcessManager.scala](https://github.com/pawelkaczor/ddd-leaven-akka-v2/blob/20161103/headquarters/write-back/src/main/scala/ecommerce/headquarters/processes/OrderProcessManager.scala) An order is represented as a process that is triggered by the `ReservationConfirmed` event published by the `Reservation Office`. As soon as the order is created, the `CreateInvoice` command is issued to the `Invoicing Office` and the status of the order is changed to `WaitingForPayment`. If the payment succeeds (the `OrderBilled` event is received from the `Invoicing` office within 3 minutes) the `CreateShipment` command is issued to the `Shipping Office` and the status of the order is changed to `DeliveryInProgress`. But, if the scheduled timeout message `PaymentExpired` is received while the order is still not billed, the `CancelInvoice`commands is issued to the `Invoicing Office` and eventually the process ends with a `Failed` status. I hope you agree, that the logic of the Ordering Process is easy to grasp by looking at the code above. We simply declare a set of state transitions with associated triggering events and resulting commands. Please note that ```⟵ (PaymentExpired(...)) in 3.minutes``` gets resolved to the following command: (```⟶ ScheduleEvent(PaymentExpired(...), now + 3.minutes)```) that will be issued to the specialized `Scheduling Office`. #### The Saga pattern -As the business process participants are distributed and communicate asynchronously (just like the human actors in the real world!) the only way to deal with a failure is to incorporate it into the business process logic. If a failure happens (a command rejected by the office, a command not processed at all (office stopped), an event not received within the configured timeout), the counteraction, called compensation, must be executed. For example, the creation of an invoice is compensated by its cancellation (see the Ordering Process above). Following this rule, we break the long running conversation (the business process) into multiple smaller actions and counteractions that can be coordinated in the distributed environment without the global / distributed transaction. This pattern for reaching the distributed consensus without a distributed transaction is called the **Saga** pattern and was first introduced by the Hector Garcia-Molina in the 1987. A Saga pattern can be implemented with or without the central component (coordinator) (see: [Orchestration vs. Choreography](http://stackoverflow.com/a/29808740)). The implementation of the Ordering Process follows the Orchestration pattern - the Ordering Process is managed by an actor, that is external to all process participants. +As the business process participants are distributed and communicate asynchronously (just like the human actors in the real world!) the only way to deal with a failure is to incorporate it into the business process logic. If a failure happens (a command rejected by the office, a command not processed at all (office stopped), an event not received within the configured timeout), the counteraction, called compensation, must be executed. For example, the creation of an invoice is compensated by its cancellation (see the Ordering Process above). Following this rule, we break the long running conversation (the business process) into multiple smaller actions and counteractions that can be coordinated in the distributed environment without the global / distributed transaction. + +This pattern for reaching the distributed consensus without a distributed transaction is called the **Saga** pattern and was first introduced by the Hector Garcia-Molina in the 1987. A Saga pattern can be implemented with or without the central component (coordinator) (see: [Orchestration vs. Choreography](http://stackoverflow.com/a/29808740)). The implementation of the Ordering Process follows the Orchestration pattern - the Ordering Process is managed by an actor, that is external to all process participants. #### Process Managers and the Coordination Office The execution of the logic of a particular business process instance is handled by the **Process Manager** actor. The Process Manager is a stateful / event-sourced actor, just like the regular Aggregate Root actor, except it receives events instead of commands. Just like the Aggregate Root actors, Process Manager actors work in the offices. Both the **Command Office** (hosting Aggregate Roots) and the **Coordination Office** (hosting Process Managers) can be started using the `OfficeFactory#office` method: ```scala office[Scheduler] // start Scheduling Command Office office[OrderProcessManager] // start Ordering Coordination Office ``` Source: [HeadquartersApp.scala](https://github.com/pawelkaczor/ddd-leaven-akka-v2/blob/20161103/headquarters/write-back/src/main/scala/ecommerce/headquarters/app/HeadquartersApp.scala) #### Let the events flow The Coordination Office is expected to correlate the received events with the business process instances using the `CorrelationID` meta-attribute of the event. Therefore to stream the events from the event store to a particular Coordination Office we need to create a `Source` (see: [Reading events from a journal](http://pkaczor.blogspot.com/2015/12/akka-ddd-integrating-eventstore.html#readingEvents)) emitting only these events that: 1) belong to the domain of the particular business process, 2) were assigned the `CorrelationID` meta-attribute. One way to address the first requirement is to create a journal ([aggregated business process journal](http://pkaczor.blogspot.com/2015/12/akka-ddd-integrating-eventstore.html#business_process_journal)), that aggregates the events belonging to the domain of a particular business process. Some Akka Persistence journal providers may support the automatic creation of journals that group events by [tags](http://doc.akka.io/api/akka/2.4/?akka.persistence.journal.Tagged#akka.persistence.journal.Tagged). Unfortunately, this functionality is not [yet](https://github.com/EventStore/EventStore.Akka.Persistence/issues/26) supported by the Event Store plugin, that is used by the Akka-DDD. Luckily though, using the Event Store projection mechanism, we can create the journal of the Ordering Process by activating the following projection: ```javascript fromStreams(['$ce-Reservation', '$ce-Invoice', 'currentDeadlines-global']). when({ 'ecommerce.sales.ReservationConfirmed' : function(s,e) { linkTo('order', e); }, 'ecommerce.invoicing.OrderBilled' : function(s,e) { linkTo('order', e); }, 'ecommerce.invoicing.OrderBillingFailed' : function(s,e) { linkTo('order', e); }, 'ecommerce.invoicing.PaymentExpired' : function(s,e) { linkTo('order', e); } }); ``` Source: [order-process.js](https://github.com/pawelkaczor/ddd-leaven-akka-v2/blob/20161103/headquarters/write-back/src/main/resources/projections/order-process.js) Now, the events from the `order` journal need to be assigned the `CorrelationID` and directed to the responsible Coordination Office. What is important and challenging though, is to ensure that the events get delivered in a reliable manner. #### Reliable events propagation By reliable delivery I mean effectively-once delivery, which takes place when: - message is delivered **at least once**, - message is processed (by the destination actor) **exactly-once**, - messages get processed (by the destination actor) in the order they were stored in the source journal. Effectively-once delivery (a.k.a. The Business Handshake Pattern) can easily be accomplished if the sender keeps track of the "in delivery" messages and the receiver keeps track of the processed messages. The implementation of the pattern becomes straightforward if both the sender and the receiver are event-sourced actors. For more detailed explanation of how the reliable delivery gets achieved, please refer to the [Reliable Delivery](https://github.com/pawelkaczor/akka-ddd/wiki/Reliable-Delivery) Akka-DDD wiki page. In our scenario, we already have the event-sourced Process Manager on the receiving side (the Coordination Office is just a transparent proxy). The missing component is the event-sourced actor on the sending side. As it is an infrastructure level component, it will automatically be created by the Akka-DDD framework, just after the Coordination Office gets started. The overall behavior of the actor that needs to be created matches the concept of the [Receptor](https://en.wikipedia.org/wiki/Transduction_(physiology)) — a sensor that reacts to a signal (stimulus), transforms it and propagates (stimulus transduction). The Akka-DDD provides the implementation of the Receptor that supports *reliable* event propagation, including the [**back-pressure**](http://www.reactivemanifesto.org/glossary#Back-Pressure) mechanism. #### Receptor A Receptor gets created by the [factory method](https://github.com/pawelkaczor/akka-ddd/blob/v1.3.1/akka-ddd-core/src/main/scala/pl/newicom/dddd/process/ReceptorSupport.scala#L14) based on the provided [configuration object](https://github.com/pawelkaczor/akka-ddd/blob/v1.3.1/akka-ddd-messaging/src/main/scala/pl/newicom/dddd/coordination/ReceptorBuilder.scala#L17). The configuration can be built using the simple [Receptor DSL](https://github.com/pawelkaczor/akka-ddd/blob/v1.3.1/akka-ddd-messaging/src/main/scala/pl/newicom/dddd/coordination/ReceptorBuilder.scala#L26). A [Receptor](https://github.com/pawelkaczor/akka-ddd/blob/v1.3.1/akka-ddd-core/src/main/scala/pl/newicom/dddd/process/Receptor.scala#L21) actor is a **durable subscriber**. During the initialization, it is [subscribing](https://github.com/pawelkaczor/akka-ddd/blob/v1.3.1/akka-ddd-core/src/main/scala/pl/newicom/dddd/process/Receptor.scala#L45) (by itself) to the event journal of the business entity that was provided as the `stimuliSource` in the configuration object. After the event has been received and stored in the receptor journal, the transformation function gets called and the result gets sent to the configured receiver. If the receiver address is to be obtained from an event, that gets propagated, then the `receiverResolver` function should be provided in the configuration. One might question the fact that the same events get written twice into the event store (first time to the office journal, second time to the receptor journal). I would like to clarify, that in fact this does not happen. The receptor is by default configured to use an **in-memory journal** and the only messages that get persisted are the snapshots of the receptor state. The snapshots get written to the snapshot store on a regular basis (every `n` events, where `n` is configurable) and contain the messages awaiting the delivery receipt. #### Coordination Office Receptor Having learned how to build a receptor, it should be easy to understand the behavior of the Coordination Office receptor by examining its [configuration](https://github.com/pawelkaczor/akka-ddd/blob/v1.3.1/akka-ddd-messaging/src/main/scala/pl/newicom/dddd/saga/CoordinationOffice.scala#L14). As we can see, the receptor reacts to the events, coming from the aggregated process journal, adds the `CorrelationID` meta-attribute to the event message and propagates the event message to the Coordination Office representative actor. The name of the aggregated process journal and the `CorrelationID` resolver function get retrieved from the [ProcessConfig](https://github.com/pawelkaczor/akka-ddd/blob/v1.3.1/akka-ddd-messaging/src/main/scala/pl/newicom/dddd/saga/ProcessConfig.scala) object — an implicit parameter of the `office` factory method. To summarize, the Coordination Office receptor gets automatically created by the Akka-DDD framework, based on the configuration of the business process. So, let's take a look at the [OrderProcessConfiguration](https://github.com/pawelkaczor/ddd-leaven-akka-v2/blob/20161103/headquarters/write-back/src/main/scala/ecommerce/headquarters/processes/OrderProcessManager.scala#L31): ```scala implicit object OrderProcessConfig extends ProcessConfig[OrderProcessManager]("order", department) { def correlationIdResolver = { case ReservationConfirmed(reservationId, _, _) => reservationId // orderId case OrderBilled(_, orderId, _, _) => orderId case OrderBillingFailed(_, orderId) => orderId case PaymentExpired(_, orderId) => orderId } } ``` The aggregated process journal is given the name: `order`. The `correlationIdResolver` function returns the `CorrelationID` from the `orderId` attribute of the event, for all events, except the `ReservationConfirmed`. For the `ReservationConfirmed` event, the `CorrelationID` / `order ID` must be generated, because the Ordering Process is not yet started, while the `ReservationConfirmed` event is being processed. #### Message flow - the complete picture After the initial event has been received and processed by the Process Manager, the business process instance gets started. The business process will continue, driven by the events. The events will be emitted as soon as the commands, issued by the Process Manager, get processed in the responsible Command Offices. The following diagram visualizes the flow of the commands and events within the system that occurs when the business process is running. ![](https://pawelkaczor.github.io/images/akka-ddd/MessageFlow.svg) #### Business process journal Before reacting to an event, the Process Manager writes the event to its journal. The journal of a Process Manager is de facto a journal of a business process instance - it keeps the events related to particular business process instance in order they were processed by the Process Manager. #### Ordering Process - an alternative implementation (Event Choreography) Instead of giving the responsibility for the business process execution to the single, external business entity (the Ordering Process is managed by a Process Manager, operating in the `Headquarters` subsystem), we could let the process emerge by allowing more direct communication between the offices. For example, to send the `CreateShipment` command to the `Shipping Office` in reaction to the `OrderBilled` event coming from the `Invoicing Office` we could register a simple Receptor in the `Shipping` subsystem. In the same way, we could implement other interactions required by the Ordering Process and thus make the `Headquarters` subsystem obsolete. The overall event flow could be modeled as presented on the following diagram: ![](https://raw.githubusercontent.com/pawelkaczor/ddd-leaven-akka-v2/master/project/diagrams/OrderingSystem.png) We can find this alternative approach to the implementation of the Ordering Process in the previous [version](https://github.com/pawelkaczor/ddd-leaven-akka-v2/tree/20160731) of the ddd-leaven-akka-v2 project. The `Headquarters` subsystem did not exist back then. In the `Shipping` subsystem, you can find the implementation of the [Payment Receptor](https://github.com/pawelkaczor/ddd-leaven-akka-v2/blob/20160731/shipping/write-back/src/main/scala/ecommerce/shipping/PaymentReceptor.scala), that I described above. #### Summary -Once we start modeling the interactions that shape our business domain, using the language of commands and events, we are on a good way towards a model of the system that is simple to understand by the business people and simple to express in the code. Although, we could implement the event-centric model on basis of the monolith architecture, we should not be scared of the distributed architecture, especially if we want the system to be scalable and fault-tolerant. As we saw, the coordination of activities between event-sourced business entities can efficiently and reliably be performed in the distributed environment. \ No newline at end of file +Once we start modeling the interactions that shape our business domain, using the language of the commands and the events, we are on a good way towards creating a model of a system that is simple to understand by the business people and also simple to express in the code. + +Although, we could implement the event-centric model on the basis of the monolith architecture, we should not be afraid of the distributed architecture, especially if we want the system to be scalable and fault-tolerant. + +As I demonstrated above, the coordination of the activities between the event-sourced business entities can be performed in the distributed environment efficiently and reliably. \ No newline at end of file
pawelkaczor/pawelkaczor.github.com
570fe36615bb6b28e4322aa6dcda769c6d7ac55f
add "Reactive business processes" post (#1)
diff --git a/_posts/reactive-ddd/reactive-business-processes.md b/_posts/reactive-ddd/reactive-business-processes.md new file mode 100644 index 0000000..b3acf05 --- /dev/null +++ b/_posts/reactive-ddd/reactive-business-processes.md @@ -0,0 +1,171 @@ +### Reactive DDD with Akka - Reactive business processes + + +#### Introduction + +In the previous [post](http://pkaczor.blogspot.com/2016/08/reactive-ddd-with-akka-putting-the-pieces-together.html) we learned how to implement a sample ordering service using the [Akka-DDD](https://github.com/pawelkaczor/akka-ddd) framework. The service exposed the `Reservation Office` responsible for preparing and confirming the reservation of products, that the client added to his/her shopping cart. We learned that an office is a command handling business entity whose sole responsibility is to validate and process the commands. If the command validation succeeds, an appropriate event is written to the office journal. The `Reservation Office` alone is obviously not able to execute the whole Ordering Process engaging activities like payment processing, invoicing and goods delivery. Therefore, to extend the functionality of the system we need to introduce two new subsystems / services: `Invoicing` and `Shipping`, that will be hosting `Invoicing Office` and `Shipping Office` respectively. The question arises, how to employ multiple offices to work on a business process and coordinate the workflow, so that the process is executed as defined by the business. To answer this question, we will first learn how to model a **business process** in a distributed system. Then we will review the implementation of a sample Ordering Process developed under the [ddd-leaven-akka-v2](https://github.com/pawelkaczor/ddd-leaven-akka-v2) project. Finally we will see how Akka-DDD facilitates the implementation of business processes in a distributed system. + +#### Business processes and SOA + +To deliver a business value, an enterprise needs to perform its activities in a coordinated manner. Regardless of whether it is a production line or a decision chain, activities needs to be performed in a specific order accordingly to the rules defined by the business. The business process thus defines precisely what activities, in which order and under which conditions need to be performed, so that the desired business goal gets achieved. The coordination of the activities implies the information exchange between the collaborators. In the past, business processes were driven by the paper documents flying back and forth between process actors. Nowadays, when more and more activities are performed by computers and machines, the business process execution is realized as a message flow between services. Unfortunately though, for a variety of reasons, the implementation of the **Service-Oriented Architecture (SOA)**, very often ended up with a **Big Ball of Mud** as well as scalability and reliability issues (just to name a few) in the runtime. + +The recent move towards the **SOA 2.0** / Event-driven SOA / "SOA done Right" / Microservices (choose your favorite buzzword) enables delivering more light-weight, reliable / fault-tolerant and scalable SOA implementations. When it comes to modeling and executing business processes, the key realization is that since **business processes are event-driven**, the same events that get written to the office journals could be used to trigger the start or the continuation of business processes. If so, any business process can be implemented as an **event-sourced actor** (called **Process Manager**) assuming it gets subscribed to a single stream of events (coming from an arbitrary number of offices) it is interested in. Once an event is received, the Process Manager executes an action, usually by sending a command to an office, and updates its state by writing the event to its journal. In this way, the Process Manager coordinates the work of the offices within the process. What is important is that **the logic of a business process is expressed in terms of incoming events, state transitions and outgoing commands**. This seems to be a quite powerful domain specific language for describing business processes. Let's take a look at the definition of an sample Ordering Process, that is written using the DSL offered by the Akka-DDD: + +#### Ordering Process - definition + +```scala + startWhen { + + case _: ReservationConfirmed => New + + } andThen { + + case New => { + + case ReservationConfirmed(reservationId, customerId, totalAmount) => + WaitingForPayment { + ⟶ (CreateInvoice(processManagerId, reservationId, customerId, totalAmount, now())) + ⟵ (PaymentExpired(processManagerId, reservationId)) in 3.minutes + } + } + + case WaitingForPayment => { + + case PaymentExpired(invoiceId, orderId) => + ⟶ (CancelInvoice(invoiceId, orderId)) + + case OrderBilled(_, orderId, _, _) => + DeliveryInProgress { + ⟶ (CloseReservation(orderId)) + ⟶ (CreateShipment(UUID(), orderId)) + } + + case OrderBillingFailed(_, orderId) => + Failed { + ⟶ (CancelReservation(orderId)) + } + } + + } +``` +Source: [OrderProcessManager.scala](https://github.com/pawelkaczor/ddd-leaven-akka-v2/blob/20161103/headquarters/write-back/src/main/scala/ecommerce/headquarters/processes/OrderProcessManager.scala) + +An order is represented as a process that is triggered by the `ReservationConfirmed` event published by the `Reservation Office`. As soon as the order is created, the `CreateInvoice` command is issued to the `Invoicing Office` and the status of the order is changed to `WaitingForPayment`. If the payment succeeds (the `OrderBilled` event is received from the `Invoicing` office within 3 minutes) the `CreateShipment` command is issued to the `Shipping Office` and the status of the order is changed to `DeliveryInProgress`. But, if the scheduled timeout message `PaymentExpired` is received while the order is still not billed, the `CancelInvoice`commands is issued to the `Invoicing Office` and eventually the process ends with a `Failed` status. + +I hope you agree, that the logic of the Ordering Process is easy to grasp by looking at the code above. We simply declare a set of state transitions with associated triggering events and resulting commands. Please note that ```⟵ (PaymentExpired(...)) in 3.minutes``` gets resolved to the following command: (```⟶ ScheduleEvent(PaymentExpired(...), now + 3.minutes)```) that will be issued to the specialized `Scheduling Office`. + +#### The Saga pattern + +As the business process participants are distributed and communicate asynchronously (just like the human actors in the real world!) the only way to deal with a failure is to incorporate it into the business process logic. If a failure happens (a command rejected by the office, a command not processed at all (office stopped), an event not received within the configured timeout), the counteraction, called compensation, must be executed. For example, the creation of an invoice is compensated by its cancellation (see the Ordering Process above). Following this rule, we break the long running conversation (the business process) into multiple smaller actions and counteractions that can be coordinated in the distributed environment without the global / distributed transaction. This pattern for reaching the distributed consensus without a distributed transaction is called the **Saga** pattern and was first introduced by the Hector Garcia-Molina in the 1987. A Saga pattern can be implemented with or without the central component (coordinator) (see: [Orchestration vs. Choreography](http://stackoverflow.com/a/29808740)). The implementation of the Ordering Process follows the Orchestration pattern - the Ordering Process is managed by an actor, that is external to all process participants. + +#### Process Managers and the Coordination Office + +The execution of the logic of a particular business process instance is handled by the **Process Manager** actor. The Process Manager is a stateful / event-sourced actor, just like the regular Aggregate Root actor, except it receives events instead of commands. Just like the Aggregate Root actors, Process Manager actors work in the offices. Both the **Command Office** (hosting Aggregate Roots) and the **Coordination Office** (hosting Process Managers) can be started using the `OfficeFactory#office` method: + +```scala + office[Scheduler] // start Scheduling Command Office + + office[OrderProcessManager] // start Ordering Coordination Office +``` +Source: [HeadquartersApp.scala](https://github.com/pawelkaczor/ddd-leaven-akka-v2/blob/20161103/headquarters/write-back/src/main/scala/ecommerce/headquarters/app/HeadquartersApp.scala) + +#### Let the events flow + +The Coordination Office is expected to correlate the received events with the business process instances using the `CorrelationID` meta-attribute of the event. Therefore to stream the events from the event store to a particular Coordination Office we need to create a `Source` (see: [Reading events from a journal](http://pkaczor.blogspot.com/2015/12/akka-ddd-integrating-eventstore.html#readingEvents)) emitting only these events that: + +1) belong to the domain of the particular business process, +2) were assigned the `CorrelationID` meta-attribute. + +One way to address the first requirement is to create a journal ([aggregated business process journal](http://pkaczor.blogspot.com/2015/12/akka-ddd-integrating-eventstore.html#business_process_journal)), that aggregates the events belonging to the domain of a particular business process. Some Akka Persistence journal providers may support the automatic creation of journals that group events by [tags](http://doc.akka.io/api/akka/2.4/?akka.persistence.journal.Tagged#akka.persistence.journal.Tagged). Unfortunately, this functionality is not [yet](https://github.com/EventStore/EventStore.Akka.Persistence/issues/26) supported by the Event Store plugin, that is used by the Akka-DDD. Luckily though, using the Event Store projection mechanism, we can create the journal of the Ordering Process by activating the following projection: + +```javascript +fromStreams(['$ce-Reservation', '$ce-Invoice', 'currentDeadlines-global']). + when({ + 'ecommerce.sales.ReservationConfirmed' : function(s,e) { + linkTo('order', e); + }, + 'ecommerce.invoicing.OrderBilled' : function(s,e) { + linkTo('order', e); + }, + 'ecommerce.invoicing.OrderBillingFailed' : function(s,e) { + linkTo('order', e); + }, + 'ecommerce.invoicing.PaymentExpired' : function(s,e) { + linkTo('order', e); + } + }); +``` + +Source: [order-process.js](https://github.com/pawelkaczor/ddd-leaven-akka-v2/blob/20161103/headquarters/write-back/src/main/resources/projections/order-process.js) + +Now, the events from the `order` journal need to be assigned the `CorrelationID` and directed to the responsible Coordination Office. What is important and challenging though, is to ensure that the events get delivered in a reliable manner. + +#### Reliable events propagation + +By reliable delivery I mean effectively-once delivery, which takes place when: + +- message is delivered **at least once**, +- message is processed (by the destination actor) **exactly-once**, +- messages get processed (by the destination actor) in the order they were stored in the source journal. + +Effectively-once delivery (a.k.a. The Business Handshake Pattern) can easily be accomplished if the sender keeps track of the "in delivery" messages and the receiver keeps track of the processed messages. The implementation of the pattern becomes straightforward if both the sender and the receiver are event-sourced actors. + +For more detailed explanation of how the reliable delivery gets achieved, please refer to the [Reliable Delivery](https://github.com/pawelkaczor/akka-ddd/wiki/Reliable-Delivery) Akka-DDD wiki page. + +In our scenario, we already have the event-sourced Process Manager on the receiving side (the Coordination Office is just a transparent proxy). The missing component is the event-sourced actor on the sending side. As it is an infrastructure level component, it will automatically be created by the Akka-DDD framework, just after the Coordination Office gets started. The overall behavior of the actor that needs to be created matches the concept of the [Receptor](https://en.wikipedia.org/wiki/Transduction_(physiology)) — a sensor that reacts to a signal (stimulus), transforms it and propagates (stimulus transduction). The Akka-DDD provides the implementation of the Receptor that supports *reliable* event propagation, including the [**back-pressure**](http://www.reactivemanifesto.org/glossary#Back-Pressure) mechanism. + +#### Receptor + +A Receptor gets created by the [factory method](https://github.com/pawelkaczor/akka-ddd/blob/v1.3.1/akka-ddd-core/src/main/scala/pl/newicom/dddd/process/ReceptorSupport.scala#L14) based on the provided [configuration object](https://github.com/pawelkaczor/akka-ddd/blob/v1.3.1/akka-ddd-messaging/src/main/scala/pl/newicom/dddd/coordination/ReceptorBuilder.scala#L17). The configuration can be built using the simple [Receptor DSL](https://github.com/pawelkaczor/akka-ddd/blob/v1.3.1/akka-ddd-messaging/src/main/scala/pl/newicom/dddd/coordination/ReceptorBuilder.scala#L26). + +A [Receptor](https://github.com/pawelkaczor/akka-ddd/blob/v1.3.1/akka-ddd-core/src/main/scala/pl/newicom/dddd/process/Receptor.scala#L21) actor is a **durable subscriber**. During the initialization, it is [subscribing](https://github.com/pawelkaczor/akka-ddd/blob/v1.3.1/akka-ddd-core/src/main/scala/pl/newicom/dddd/process/Receptor.scala#L45) (by itself) to the event journal of the business entity that was provided as the `stimuliSource` in the configuration object. After the event has been received and stored in the receptor journal, the transformation function gets called and the result gets sent to the configured receiver. If the receiver address is to be obtained from an event, that gets propagated, then the `receiverResolver` function should be provided in the configuration. + +One might question the fact that the same events get written twice into the event store (first time to the office journal, second time to the receptor journal). I would like to clarify, that in fact this does not happen. The receptor is by default configured to use an **in-memory journal** and the only messages that get persisted are the snapshots of the receptor state. The snapshots get written to the snapshot store on a regular basis (every `n` events, where `n` is configurable) and contain the messages awaiting the delivery receipt. + +#### Coordination Office Receptor + +Having learned how to build a receptor, it should be easy to understand the behavior of the Coordination Office receptor by examining its [configuration](https://github.com/pawelkaczor/akka-ddd/blob/v1.3.1/akka-ddd-messaging/src/main/scala/pl/newicom/dddd/saga/CoordinationOffice.scala#L14). As we can see, the receptor reacts to the events, coming from the aggregated process journal, adds the `CorrelationID` meta-attribute to the event message and propagates the event message to the Coordination Office representative actor. The name of the aggregated process journal and the `CorrelationID` resolver function get retrieved from the [ProcessConfig](https://github.com/pawelkaczor/akka-ddd/blob/v1.3.1/akka-ddd-messaging/src/main/scala/pl/newicom/dddd/saga/ProcessConfig.scala) object — an implicit parameter of the `office` factory method. + +To summarize, the Coordination Office receptor gets automatically created by the Akka-DDD framework, based on the configuration of the business process. + +So, let's take a look at the [OrderProcessConfiguration](https://github.com/pawelkaczor/ddd-leaven-akka-v2/blob/20161103/headquarters/write-back/src/main/scala/ecommerce/headquarters/processes/OrderProcessManager.scala#L31): + +```scala + implicit object OrderProcessConfig extends ProcessConfig[OrderProcessManager]("order", department) { + def correlationIdResolver = { + case ReservationConfirmed(reservationId, _, _) => reservationId // orderId + case OrderBilled(_, orderId, _, _) => orderId + case OrderBillingFailed(_, orderId) => orderId + case PaymentExpired(_, orderId) => orderId + } + } +``` + +The aggregated process journal is given the name: `order`. The `correlationIdResolver` function returns the `CorrelationID` from the `orderId` attribute of the event, for all events, except the `ReservationConfirmed`. For the `ReservationConfirmed` event, the `CorrelationID` / `order ID` must be generated, because the Ordering Process is not yet started, while the `ReservationConfirmed` event is being processed. + +#### Message flow - the complete picture + +After the initial event has been received and processed by the Process Manager, the business process instance gets started. The business process will continue, driven by the events. The events will be emitted as soon as the commands, issued by the Process Manager, get processed in the responsible Command Offices. + +The following diagram visualizes the flow of the commands and events within the system that occurs when the business process is running. + +![](https://pawelkaczor.github.io/images/akka-ddd/MessageFlow.svg) + +#### Business process journal + +Before reacting to an event, the Process Manager writes the event to its journal. The journal of a Process Manager is de facto a journal of a business process instance - it keeps the events related to particular business process instance in order they were processed by the Process Manager. + +#### Ordering Process - an alternative implementation (Event Choreography) + +Instead of giving the responsibility for the business process execution to the single, external business entity (the Ordering Process is managed by a Process Manager, operating in the `Headquarters` subsystem), we could let the process emerge by allowing more direct communication between the offices. For example, to send the `CreateShipment` command to the `Shipping Office` in reaction to the `OrderBilled` event coming from the `Invoicing Office` we could register a simple Receptor in the `Shipping` subsystem. In the same way, we could implement other interactions required by the Ordering Process and thus make the `Headquarters` subsystem obsolete. + +The overall event flow could be modeled as presented on the following diagram: + +![](https://raw.githubusercontent.com/pawelkaczor/ddd-leaven-akka-v2/master/project/diagrams/OrderingSystem.png) + +We can find this alternative approach to the implementation of the Ordering Process in the previous [version](https://github.com/pawelkaczor/ddd-leaven-akka-v2/tree/20160731) of the ddd-leaven-akka-v2 project. The `Headquarters` subsystem did not exist back then. In the `Shipping` subsystem, you can find the implementation of the [Payment Receptor](https://github.com/pawelkaczor/ddd-leaven-akka-v2/blob/20160731/shipping/write-back/src/main/scala/ecommerce/shipping/PaymentReceptor.scala), that I described above. + + +#### Summary + +Once we start modeling the interactions that shape our business domain, using the language of commands and events, we are on a good way towards a model of the system that is simple to understand by the business people and simple to express in the code. Although, we could implement the event-centric model on basis of the monolith architecture, we should not be scared of the distributed architecture, especially if we want the system to be scalable and fault-tolerant. As we saw, the coordination of activities between event-sourced business entities can efficiently and reliably be performed in the distributed environment. \ No newline at end of file
pawelkaczor/pawelkaczor.github.com
b93feee6da15ea110988368fbc88e10008afc9ad
add `Reactive business processes` post
diff --git a/_posts/2016-11-01-reactive-ddd-with-akka-reactive-business-processes.md b/_posts/2016-11-01-reactive-ddd-with-akka-reactive-business-processes.md new file mode 100644 index 0000000..e80e4f3 --- /dev/null +++ b/_posts/2016-11-01-reactive-ddd-with-akka-reactive-business-processes.md @@ -0,0 +1,151 @@ +### Reactive DDD with Akka - Reactive business processes + + +#### Introduction + +In the last episode we have learned how to implement a sample ordering service using the [Akka-DDD]() framework. The service exposed the `Reservation Office` responsible for preparing and confirming the reservation of products the client added to his/her shopping cart. We have learned that an office is a command handling business entity whose sole responsibility is to validate and process commands. If the command validation succeeds, an appropriate event is written to the office journal. The Reservation office alone is obviously not able to execute the whole ordering process engaging activities like payment processing, invoicing and goods delivery. Therefore, to extend functionality of the system we need to introduce two new subsystems / services: `invoicing` and `shipping`, hosting `Invoicing Office` and `Shipping Office` respectively. The question arises how to employ multiple offices to work on a business process and coordinate the workflow so that the process is executed as defined by the business. To answer this question we will first need to learn how to model a **business process** in a distributed system. Then we will see how Akka-DDD facilitates the implementation of business processes in a distributed system. Finally we will review the implementation of a sample ordering process developed under the [ddd-leaven-akka-v2]() project. + +#### Business processes and SOA + +To deliver a business value, an enterprise needs to perform its activities in a coordinated manner. Regardless if it is a production line or a decision chain, activities needs to be performed in a specific order accordingly to the rules defined by the business. Business process thus defines precisely what activities, in which order and under which conditions need to be performed so that the desired business goal is achieved. The coordination of the activities implies the information exchange between the collaborators. In the past, business processes were driven by the paper documents flying back and forth between process actors. Nowadays, when more and more activities are performed by computers and robots, the business process execution is realized as message flow between services. Unfortunately though, for different reasons, implementation of the **Service-Oriented Architecture (SOA)**, ended up very often with a **Big Ball of Mud** as well as scalability and reliability issues (just to name a few) in the runtime. + +The recent move towards the **SOA 2.0** / Event-driven SOA / "SOA done Right" / Microservices (choose your favorite buzzword) enables delivering more light-weight, reliable / fault-tolerant and scalable SOA implementations. When it comes to modeling and executing business processes, the key realization is that since **business processes are event-driven**, the same events that get written to the office journals could be used to trigger the start or the continuation of a business process. If so, any business process can be implemented as an **event-sourced actor** (called **Process Manager**) assuming it gets subscribed to a single stream of events (coming from an arbitrary number of offices) he is interested in. Once an event is received, the Process Manager executes an action, usually by sending a command to an office, and updates it's state by writing the event to its journal. In this way, the Process Manager coordinates the work of the offices within the process. What is important is that **the logic of a business process is expressed in terms of incoming events, state transitions and outgoing commands**. This seems to be a quite powerful domain specific language for describing business processes. Let's take a look at the definition of an sample [Ordering](https://raw.githubusercontent.com/pawelkaczor/ddd-leaven-akka-v2/master/project/diagrams/OrderingSystem.png) process, that is written using the DSL offered by the Akka-DDD: + +#### Ordering process - definition + +```scala + startWhen { + + case _: ReservationConfirmed => New + + } andThen { + + case New => { + + case ReservationConfirmed(reservationId, customerId, totalAmount) => + WaitingForPayment { + ⟶ (CreateInvoice(sagaId, reservationId, customerId, totalAmount, now())) + ⟵ (PaymentExpired(sagaId, reservationId)) in 3.minutes + } + } + + case WaitingForPayment => { + + case PaymentExpired(invoiceId, orderId) => + ⟶ (CancelInvoice(invoiceId, orderId)) + + case OrderBilled(_, orderId, _, _) => + DeliveryInProgress { + ⟶ (CloseReservation(orderId)) + ⟶ (CreateShipment(UUID(), orderId)) + } + + case OrderBillingFailed(_, orderId) => + Failed { + ⟶ (CancelReservation(orderId)) + } + } + + } +``` +Source: [OrderProcessManager.scala](https://github.com/pawelkaczor/ddd-leaven-akka-v2/blob/master/headquarters/write-back/src/main/scala/ecommerce/headquarters/processes/OrderProcessManager.scala) + +An order is represented as a process that is triggered by the `ReservationConfirmed` event published by the `Reservation Office`. As soon as the order is created, the `CreateInvoice` command is issued to the `Invoicing Office` and the status of the order is changed to `WaitingForPayment`. If the payment succeeds (the `OrderBilled` event is received from the `Invoicing` office within 3 minutes) the `CreateShipment` command is issued to the `Shipping Office` and the status of the order is changed to `DeliveryInProgress`. But, if the scheduled timeout message `PaymentExpired` is received while the order is still not billed, the `CancelInvoice`commands is issued to the `Invoicing Office` and eventually the process ends with a `Failed` status. + +I hope you agree that the logic of the Ordering process is easy to grasp by looking at the code above. We simply declare a set of state transitions with associated triggering events and resulting commands. Please note that ```⟵ (PaymentExpired(...)) in 3.minutes``` resolves to the following command: (```⟶ ScheduleEvent(PaymentExpired(...), now + 3.minutes)```) that will be issued to the specialized `Scheduling Office`. + +#### The Saga pattern + +As the business process participants are distributed and communicate asynchronously (just like the human actors in the real world!) the only way to deal with a failure is to incorporate it into the business process logic. If a failure happens (command rejected by the office, command not processed at all (office stopped), event not received within configured timeout), the counteraction, called compensation, must be executed. For example, the creation of an invoice is compensated by its cancellation (see the Ordering process above). Following this rule, we break the long running conversation (the business process) into multiple smaller actions and counteractions that can be coordinated in distributed environment without the global / distributed transaction. This pattern for reaching distributed consensus without distributed transaction is called **Saga** and was first introduced by the Hector Garcia-Molina in the 1987. Saga pattern can be implemented with or without the central component (coordinator) (see: [Orchestration vs. Choreography](http://stackoverflow.com/a/29808740)). Implementation of the Ordering process follows the Orchestration pattern - the Ordering process is managed by an actor, that is external to all process participants. + +#### Process Managers and the Coordination Office + +The execution of the logic of a particular business process instance is handled by the **Process Manager** actor. The Process Manager is a stateful / event-sourced actor, just like the regular Aggregate Root actor, except it receives the events instead of the commands. Just like the Aggregate Root actors, Process Manager actors work in the offices. Both the **Command Office** (hosting Aggregate Roots) and the **Coordination Office** (hosting Process Managers) can be started using the `OfficeFactory#office` method: + +```scala + office[Scheduler] // start Scheduling Command Office + + office[OrderProcessManager] // start Ordering Coordination Office +``` +Source: [HeadquartersApp.scala](https://github.com/pawelkaczor/ddd-leaven-akka-v2/blob/master/headquarters/write-back/src/main/scala/ecommerce/headquarters/app/HeadquartersApp.scala) + +#### Let the events flow + +Coordination Office is expected to correlate the received events with the business process instances using the `CorrelationID` meta-attribute of the event. Therefore to stream the events from the event store to a particular Coordination Office we need to create a `Source` (see: [Reading events from a journal](http://pkaczor.blogspot.com/2015/12/akka-ddd-integrating-eventstore.html#readingEvents)) emitting only these events that 1) belong to the domain of the particular business process and 2) were assigned the `CorrelationID` meta-attribute. One way to address the first requirement is to create a journal ([aggregated business process journal](http://pkaczor.blogspot.com/2015/12/akka-ddd-integrating-eventstore.html#business_process_journal)), that aggregates the events belonging to the domain of a particular business process. Some Akka Persistence journal providers may support the automatic creation of journals that group events by [tags](http://doc.akka.io/api/akka/2.4/?akka.persistence.journal.Tagged#akka.persistence.journal.Tagged). Unfortunately, this functionality is not [yet](https://github.com/EventStore/EventStore.Akka.Persistence/issues/26) supported by the Event Store plugin, that is used by the Akka-DDD. Luckily though, using the Event Store projection mechanism, we can create the journal of the Ordering process by activating the following projection: + +```javascript +fromStreams(['$ce-Reservation', '$ce-Invoice', 'currentDeadlines-global']). + when({ + 'ecommerce.sales.ReservationConfirmed' : function(s,e) { + linkTo('order', e); + }, + 'ecommerce.invoicing.OrderBilled' : function(s,e) { + linkTo('order', e); + }, + 'ecommerce.invoicing.OrderBillingFailed' : function(s,e) { + linkTo('order', e); + }, + 'ecommerce.invoicing.PaymentExpired' : function(s,e) { + linkTo('order', e); + } + }); +``` + +Source: [order-process.js](https://github.com/pawelkaczor/ddd-leaven-akka-v2/blob/master/headquarters/write-back/src/main/resources/projections/order-process.js) + +Now, the events from the `order` journal need to be assigned the `CorrelationID` and directed to the responsible Coordination Office. What is important and challenging though is to ensure that the events are delivered in a reliable manner. + +#### Reliable events propagation + +By reliable delivery I mean effectively-once delivery, which takes place when: + +- message is delivered **at least once** +- message is processed (by the destination actor) **exactly-once** +- messages are processed (by the destination actor) in the order they were stored in the source journal + +Effectively-once delivery (a.k.a. The Business Handshake Pattern) can easily be accomplished if the sender keeps track of the "in delivery" messages and the receiver keeps track of the processed messages. The implementation of the pattern becomes straightforward if both the sender and the receiver are event sourced actors (For the implementation details please refer to the Akka-DDD wiki: [Reliable Delivery](https://github.com/pawelkaczor/akka-ddd/wiki/Reliable-Delivery)). In our scenario, we already have the event-sourced Process Manager on the receiving side (Coordination Office is just a transparent proxy). The missing component is the event-sourced actor on the sending side. As it is an infrastructure level component, it will automatically be created by the Akka-DDD framework, just after the Coordination Office is started. The overall behavior of the actor that needs to be created matches the concept of the [Receptor](https://en.wikipedia.org/wiki/Transduction_(physiology)) - a sensor that reacts to a signal (stimulus), transforms it and propagates (stimulus transduction). The Akka-DDD provides implementation of the `Receptor` that supports *reliable* event propagation including the [**back-pressure**](http://www.reactivemanifesto.org/glossary#Back-Pressure) mechanism. + +#### Receptor + +The `Receptor` is created by the [factory method](https://github.com/pawelkaczor/akka-ddd/blob/master/akka-ddd-core/src/main/scala/pl/newicom/dddd/process/ReceptorSupport.scala#L14) based on the provided [configuration object](https://github.com/pawelkaczor/akka-ddd/blob/225d19205077e1cde7ebc0b24764b700888aea41/akka-ddd-messaging/src/main/scala/pl/newicom/dddd/coordination/ReceptorBuilder.scala#L17). The configuration can be build using the simple [Receptor DSL](https://github.com/pawelkaczor/akka-ddd/blob/225d19205077e1cde7ebc0b24764b700888aea41/akka-ddd-messaging/src/main/scala/pl/newicom/dddd/coordination/ReceptorBuilder.scala#L26). + +The `Receptor` actor is a **durable subscriber**. During the initialization, it subscribes itself to the event journal of the business entity that was provided as the `stimuliSource` in the configuration object. After the event has been received and stored in the receptor journal, the transormation function gets called and the result is sent to the configured receiver. The `receiverResolver` function can be provided in the configuration, if the receiver address should be obtained from the event being propagated. + +You might complain about the same events being stored twice in the event store (first time in the office journal, second time in the receptor journal). I have to clarify that this does not happen. The receptor is by default configured to use an **in-memory journal** and the only messages that get persisted are the snapshots of the receptor state. The snapshots get written to the snapshot store on a regular basis (every `n` events, where `n` is configurable) and contain the messages awaiting the delivery receipt. + +#### Coordination Office Receptor + +Having learned how to build a receptor, it should be easy to understand the behavior of the Coordination Office receptor by examining its [configuration](https://github.com/pawelkaczor/akka-ddd/blob/master/akka-ddd-messaging/src/main/scala/pl/newicom/dddd/saga/CoordinationOffice.scala#L14). As we can see, the receptor reacts to events from the aggregated process journal, adds the `CorrelationID` meta-attribute to the event message and propagates the event message to the Coordination Office representative actor. The name of the aggregated process journal and the `CorrelationID` resolver function are retrieved from the [ProcessConfig](https://github.com/pawelkaczor/akka-ddd/blob/225d19205077e1cde7ebc0b24764b700888aea41/akka-ddd-messaging/src/main/scala/pl/newicom/dddd/saga/ProcessConfig.scala) object - an implicit parameter of the `office` factory method. To conclude, the Coordination Office receptor will automatically be created by the Akka-DDD framework, based on the configuration of the business process. Let's see then the [OrderProcessConfiguration](https://github.com/pawelkaczor/ddd-leaven-akka-v2/blob/master/headquarters/write-back/src/main/scala/ecommerce/headquarters/processes/OrderProcessManager.scala#L31): + +```scala + implicit object OrderProcessConfig extends ProcessConfig[OrderProcessManager]("order", department) { + def correlationIdResolver = { + case ReservationConfirmed(reservationId, _, _) => reservationId // orderId + case OrderBilled(_, orderId, _, _) => orderId + case OrderBillingFailed(_, orderId) => orderId + case PaymentExpired(_, orderId) => orderId + } + } +``` + +The aggregated process journal is given the name: `order`. The `correlationIdResolver` function returns the `CorrelationID` from the `orderId` attribute of the event, for all events, except the `ReservationConfirmed`. For `ReservationConfirmed` event, the `CorrelationID` / `order ID` must be generated, because the Ordering process, at the time the `ReservationConfirmed` event is processed, is not yet started. + +#### Message flow - the complete picture + +After the initial, triggering event has been received and processed by the Process Manager, the business process instance is started. Process Manager will take care of continuing the process by sending the commands to Coordination Offices and reacting to the result events. + +The following diagram visualizes the flow of the commands and events within the system that occurs when the business process is running. + +![](https://pawelkaczor.github.io/images/akka-ddd/MessageFlow.svg) + +Please note that reliable delivery channel is arranged automatically by the Akka-DDD framework not only between Receptor actor and Saga Manager actors but also between Process Manager and Aggregate Root actors. + +#### Business process journal + +Before reacting upon an event, the Process Manager writes the event to its journal. The journal of a Process Manager is de facto a journal of a business process instance - it keeps the events related to particular business process instance in order they were processed by the Process Manager. + +#### Summary + +To be written... + +
pawelkaczor/pawelkaczor.github.com
14cfae045842357f29563890be0ae7920b08da1e
add MessageFlow
diff --git a/images/akka-ddd/MessageFlow.svg b/images/akka-ddd/MessageFlow.svg new file mode 100644 index 0000000..dbacf8c --- /dev/null +++ b/images/akka-ddd/MessageFlow.svg @@ -0,0 +1,2 @@ +<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> +<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="470px" height="336px" version="1.1" content="&lt;mxfile userAgent=&quot;Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36&quot; version=&quot;5.7.2.3&quot; editor=&quot;www.draw.io&quot; type=&quot;google&quot;&gt;&lt;diagram&gt;7VpLV9s4FP41WZJjSX7ES6Aws2jPcMpiOqseYSuOpo6VkRUS+PUj2fJDluMkxAFaygbr+lqP775vNEHXy+0fHK8WX1hM0gl04u0EfZpACBwYyn+K8lRSXD8oCQmnsWZqCPf0mVRfauqaxiQ3GAVjqaArkxixLCORMGiYc7Yx2eYs1avq+Vc4IQaHItxHOLWpf9NYLErqDPoN/U9Ck0W1MvD1gR9w9CPhbJ3p9SYQzYu/8vUSV3PpjeQLHLNNi4RuJuiaMybKp+X2mqQKW2oc4HbH23rfnGTikA+g3oZ4qo5OYomEHjIuFixhGU5vGupVcTyiJnDkaCGWqXwE8lGuyZ++tQf/KKapVw3vCKdLIgjX3+YCc3Gp5CUJGctIRbulaap5SBZXHFGK85xGJVGzqKX+JUI8aSXCa8Ekqdn5Z8ZWmi8XnP0g1yxlvDgrcoq/+k0lasU7Z5nQUwKoVtxSURxt6sBAj8vTubNQj7vHK7FVgBrSydmaR5rkauXGPCFaYJ4tQ1BrhrQ4wuQa/EmyaHNzg1n5iTY2EGrlwtoKkvoTPYsEFD+1GFaMZiJvLXKnCK0Vqhk7K9weyC+BbvPLh3IH1ah1qoZUaGq/1qJy9kecrjWON4+k2MC9YJxYOi2tbKUeYyxwXnCgq82CCnK/woUkNtKNmbqsVyBckO1kl23tkQsw5RLoGTaNR/E1TouWM/EHpNdCcBAg1wLIwkQdjUqP9xk/kPSO5VRQlslXD0wItjTBqHgvU5ooHqFMqmNO2nzn0iwNC7u6uVX2U4lguU1UyJji5zUn0//WZE2+JySTlhONhDqEU8/U1hmygPc8G3jgnQ68ZwH/lURkJXXOVkrD50AT8S5c85RtooX0jNPCP36HOzT4DGoLA+fV9NYfDEdaxXbGHyOcsBXJOuEEmOFET9fEEqft5w0fX0ewb3VU2hfd9vv+cATfj4Df62nbwnKmwPNteaHTxRX0uBk/lfNfPciHRD1ox1xS5Xz1C0vSUmOFKU9OcvqMHwoGBTrW7ieSUyqULb+0pHFcpCipcmpXdS7Wckg6GxuwFJ1T6nUnrZyxEYo/KJQLiTgKTMFc6Nk5SbGgj6ZW7AzUVmQFyJg1NL9n83kuVakrweOC6+yjCnWPpQUm9Ajsy7LeQnihJbxrxnhMM1yEd+j8NZ/TyM6Q5CyytnqdvAgi0zTqyNHyWbOeADMbIcBUQhvKjN5rYAaVdGvc3FcLzAD0KNZyiWWdq91ATB8rL1DpWO0fWu/2oA3GQbuo3vQazijQu52k0gss7IPQxj4IR8Ae9nlkvFQH1QibI9VV4HHh65Sf0y8Tg7VfGE1qBfa7grp30VTQB9bWrRpBJ2FSvDGVwuhWE60qXM0V43xRby/tVC5WBOmWNmXZsjfg1BXQGIrjmJWwLE8svZFY2YoDqsTuJM1BtqMfob3TkwD/JJ2cA7sydc+xlZqjoxMGB0zDwAeBH/rIdRAwFAE4+3K/Y5s0co3eFXY1afbwn9ykAX1NiDMmkhofye1dTbxPY6eW3YbgTudwUKqJBlVHFRAO7JThk1HqBzP1qmQ0ag4K7CbIb8Ef5jL8cMhlgIGS/Q3FPdy0+XhBplGSwSADeoLM8SoDHdTJTEM4cmABnW6+XmBXXBlmPz2s9DWdOvqnjHl1RjuFnnnEns6+B+2czhuQzMEpXV975qXFvF3p7gTNACfoR6d1fLfn+O4Yx7cbHJdf3w0AddJvel27vXEueOAB7Y2zg3Oq6ZwNHLuH8Ra6MwyPb8Ize0V47DbDHWcRyfOeFs8XnOFEplYv6fG8o44a6nTUqqb9K3TUen7EtrLkTottME8+U871q9zbqH7ba53sZTc2Km/eTtvA0ZrXMfMw2K1Q/VlWYE6AvI5KllvWHzVaeWzu19knDN32bPvY9bHGSv16rzX8boT+lI3QyvO2+6DwXH3Q6nf1sd3lNJT2YLhMFM5+Aad5gBvsubxQJRBHKEVoxt/69sJJwj5TP2LqekFb2BfO1AnQx5A2sqXtHits1+1cU0QD3cuDhd17BWUwJNAsSYkofgw/KiTYjci9F+A06fB2ZF+gMaKL4ff7f9k48fJXJ+B7dvEaBLabhscbrhw295zLbKC5TI5u/gc=&lt;/diagram&gt;&lt;/mxfile&gt;" style="background-color: rgb(255, 255, 255);"><defs/><g transform="translate(0.5,0.5)"><path d="M 449 166 L 460 166 L 460 276 L 454.37 276" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 449.12 276 L 456.12 272.5 L 454.37 276 L 456.12 279.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 388 55 C 388 44.33 448 44.33 448 55 L 448 99 C 448 109.67 388 109.67 388 99 Z" fill="#ffffff" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 388 55 C 388 63 448 63 448 55 M 388 59 C 388 67 448 67 448 59 M 388 63 C 388 71 448 71 448 63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(389.5,72.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="56" height="26" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 56px; white-space: normal; word-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Event Store</div></div></foreignObject><text x="28" y="19" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">Event Store</text></switch></g><path d="M 392.56 160.12 C 392.77 159.45 393.46 159 394.23 159.02 L 442.51 159.02 L 447.5 166.71 L 442.51 174 L 394.11 174 C 393.65 173.98 393.22 173.78 392.93 173.46 C 392.63 173.14 392.5 172.72 392.56 172.31 Z M 393.67 172.17 C 393.8 172.67 394.31 173.02 394.89 173.01 L 442.01 173.01 L 446.39 166.71 L 442.01 159.97 L 394.89 159.97 C 394.39 159.92 393.9 160.16 393.67 160.56 Z M 395.34 162.55 C 395.38 162.09 395.77 161.72 396.28 161.65 L 408.6 161.65 C 409.11 161.72 409.5 162.09 409.54 162.55 L 409.54 170.68 C 409.4 171.07 409.01 171.35 408.54 171.37 L 396.39 171.37 C 395.93 171.35 395.53 171.07 395.39 170.68 Z M 396.83 164.43 L 396.83 170.18 L 408.15 170.18 L 408.15 164.33 L 402.94 167.85 C 402.57 168.07 402.09 168.07 401.72 167.85 Z M 402.38 166.76 L 407.93 162.89 L 396.89 162.89 Z M 411.1 162.55 C 411.12 162.13 411.43 161.78 411.87 161.65 L 424.36 161.65 C 424.8 161.78 425.11 162.13 425.14 162.55 L 425.14 170.68 C 425.03 171.02 424.74 171.28 424.36 171.37 L 411.87 171.37 C 411.49 171.28 411.2 171.02 411.1 170.68 Z M 412.48 164.38 L 412.48 170.18 L 423.8 170.18 L 423.75 164.38 L 418.64 167.85 C 418.25 168.12 417.71 168.12 417.31 167.85 Z M 418.03 166.76 L 423.64 162.89 L 412.48 162.89 Z M 426.75 162.55 C 426.79 162.09 427.18 161.72 427.69 161.65 L 439.95 161.65 C 440.46 161.72 440.85 162.09 440.9 162.55 L 440.9 170.48 C 440.87 170.74 440.72 170.99 440.49 171.15 C 440.26 171.32 439.97 171.4 439.68 171.37 L 427.69 171.37 C 427.25 171.33 426.88 171.06 426.75 170.68 Z M 428.08 164.38 L 428.08 170.18 L 439.4 170.18 L 439.4 164.38 L 434.18 167.85 C 433.84 168.03 433.41 168.03 433.07 167.85 Z M 433.68 166.76 L 439.23 162.89 L 428.13 162.89 Z" fill="#00bef2" stroke="none" pointer-events="none"/><ellipse cx="418" cy="276" rx="30" ry="30" fill="#ffffff" stroke="#000000" stroke-width="2" pointer-events="none"/><g transform="translate(392.5,269.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="49" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 50px; white-space: nowrap; word-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Receptor</div></div></foreignObject><text x="25" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">Receptor</text></switch></g><path d="M 288.24 276 L 388 276" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 294.12 272.5 L 287.12 276 L 294.12 279.5" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(326.5,280.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="33" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;"><b>Event</b></div></div></foreignObject><text x="17" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">&lt;b&gt;Event&lt;/b&gt;</text></switch></g><ellipse cx="246" cy="276" rx="40" ry="40" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(207.5,262.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="76" height="26" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 76px; white-space: normal; word-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Coordination Office</div></div></foreignObject><text x="38" y="19" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">Coordination Office</text></switch></g><ellipse cx="129" cy="270" rx="30" ry="30" fill="#ffffff" stroke="#000000" stroke-width="2" pointer-events="none"/><ellipse cx="134" cy="73" rx="39.5" ry="39.5" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(105.5,59.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="56" height="26" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 56px; white-space: nowrap; word-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Command<div>Office</div></div></div></foreignObject><text x="28" y="19" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><rect x="70" y="218" width="230" height="116" rx="17.4" ry="17.4" fill="none" stroke="#000000" stroke-dasharray="3 3" pointer-events="none"/><g transform="translate(148.5,203.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="73" height="10" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 74px; white-space: nowrap; word-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">&lt;&lt; shardable &gt;&gt;</div></div></foreignObject><text x="37" y="10" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">&amp;lt;&amp;lt; shardable &amp;gt;&amp;gt;</text></switch></g><path d="M 271.98 77 L 310 77 L 381.63 77" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 386.88 77 L 379.88 80.5 L 381.63 77 L 379.88 73.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(323.5,83.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="33" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;"><b>Event</b></div></div></foreignObject><text x="17" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">&lt;b&gt;Event&lt;/b&gt;</text></switch></g><path d="M 173.5 68 L 213.63 68" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 218.88 68 L 211.88 71.5 L 213.63 68 L 211.88 64.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><ellipse cx="241" cy="68" rx="21" ry="21" fill="#ffffff" stroke="#000000" stroke-width="2" pointer-events="none"/><ellipse cx="251" cy="78" rx="21" ry="21" fill="#ffffff" stroke="#000000" stroke-width="2" pointer-events="none"/><g transform="translate(241.5,71.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="17" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 18px; white-space: nowrap; word-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">AR</div></div></foreignObject><text x="9" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">AR</text></switch></g><ellipse cx="139" cy="282" rx="30" ry="30" fill="#ffffff" stroke="#000000" stroke-width="2" pointer-events="none"/><g transform="translate(114.5,268.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="48" height="26" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 48px; white-space: nowrap; word-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Process<div>Manager</div></div></div></foreignObject><text x="24" y="19" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 99 270 L 30 270 L 30 73 L 88.63 73" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 93.88 73 L 86.88 76.5 L 88.63 73 L 86.88 69.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(0.5,166.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="59" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;"><b>Command</b></div></div></foreignObject><text x="30" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">&lt;b&gt;Command&lt;/b&gt;</text></switch></g><rect x="70" y="15" width="220" height="116" rx="17.4" ry="17.4" fill="none" stroke="#000000" stroke-dasharray="3 3" pointer-events="none"/><g transform="translate(143.5,0.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="73" height="10" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 74px; white-space: nowrap; word-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">&lt;&lt; shardable &gt;&gt;</div></div></foreignObject><text x="37" y="10" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">&amp;lt;&amp;lt; shardable &amp;gt;&amp;gt;</text></switch></g><path d="M 206 276 L 186 276 L 189 276 L 175.37 276" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 170.12 276 L 177.12 272.5 L 175.37 276 L 177.12 279.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 418 107 L 418 151.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 418 156.88 L 414.5 149.88 L 418 151.63 L 421.5 149.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(383.5,230.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="69" height="10" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 70px; white-space: nowrap; word-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">&lt;&lt; singleton &gt;&gt;</div></div></foreignObject><text x="35" y="10" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">&amp;lt;&amp;lt; singleton &amp;gt;&amp;gt;</text></switch></g></g></svg> \ No newline at end of file
pawelkaczor/pawelkaczor.github.com
8413ea703f1d047d3be00745e64c16e281890312
Saga2.svg
diff --git a/images/akka-ddd/Saga2.svg b/images/akka-ddd/Saga2.svg new file mode 100644 index 0000000..e6b75f1 --- /dev/null +++ b/images/akka-ddd/Saga2.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="790px" height="529px" version="1.1"><defs/><g transform="translate(0.5,0.5)"><path d="M 396 41 C 396 30.33 456 30.33 456 41 L 456 85 C 456 95.67 396 95.67 396 85 Z" fill="#ffffff" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 396 41 C 396 49 456 49 456 41 M 396 45 C 396 53 456 53 456 45 M 396 49 C 396 57 456 57 456 49" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(397.5,58.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="56" height="25" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 56px; white-space: normal; word-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Event Store</div></div></foreignObject><text x="28" y="19" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">Event Store</text></switch></g><path d="M 400.56 146.12 C 400.77 145.45 401.46 145 402.23 145.02 L 450.51 145.02 L 455.5 152.71 L 450.51 160 L 402.11 160 C 401.65 159.98 401.22 159.78 400.93 159.46 C 400.63 159.14 400.5 158.72 400.56 158.31 Z M 401.67 158.17 C 401.8 158.67 402.31 159.02 402.89 159.01 L 450.01 159.01 L 454.39 152.71 L 450.01 145.97 L 402.89 145.97 C 402.39 145.92 401.9 146.16 401.67 146.56 Z M 403.34 148.55 C 403.38 148.09 403.77 147.72 404.28 147.65 L 416.6 147.65 C 417.11 147.72 417.5 148.09 417.54 148.55 L 417.54 156.68 C 417.4 157.07 417.01 157.35 416.54 157.37 L 404.39 157.37 C 403.93 157.35 403.53 157.07 403.39 156.68 Z M 404.83 150.43 L 404.83 156.18 L 416.15 156.18 L 416.15 150.33 L 410.94 153.85 C 410.57 154.07 410.09 154.07 409.72 153.85 Z M 410.38 152.76 L 415.93 148.89 L 404.89 148.89 Z M 419.1 148.55 C 419.12 148.13 419.43 147.78 419.87 147.65 L 432.36 147.65 C 432.8 147.78 433.11 148.13 433.14 148.55 L 433.14 156.68 C 433.03 157.02 432.74 157.28 432.36 157.37 L 419.87 157.37 C 419.49 157.28 419.2 157.02 419.1 156.68 Z M 420.48 150.38 L 420.48 156.18 L 431.8 156.18 L 431.75 150.38 L 426.64 153.85 C 426.25 154.12 425.71 154.12 425.31 153.85 Z M 426.03 152.76 L 431.64 148.89 L 420.48 148.89 Z M 434.75 148.55 C 434.79 148.09 435.18 147.72 435.69 147.65 L 447.95 147.65 C 448.46 147.72 448.85 148.09 448.9 148.55 L 448.9 156.48 C 448.87 156.74 448.72 156.99 448.49 157.15 C 448.26 157.32 447.97 157.4 447.68 157.37 L 435.69 157.37 C 435.25 157.33 434.88 157.06 434.75 156.68 Z M 436.08 150.38 L 436.08 156.18 L 447.4 156.18 L 447.4 150.38 L 442.18 153.85 C 441.84 154.03 441.41 154.03 441.07 153.85 Z M 441.68 152.76 L 447.23 148.89 L 436.13 148.89 Z" fill="#00bef2" stroke="none" pointer-events="none"/><ellipse cx="426" cy="262" rx="30" ry="30" fill="#ffffff" stroke="#000000" stroke-width="2" pointer-events="none"/><g transform="translate(400.5,255.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="49" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 49px; white-space: nowrap; word-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Receptor</div></div></foreignObject><text x="25" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">Receptor</text></switch></g><path d="M 296.24 262 L 396 262" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 302.12 258.5 L 295.12 262 L 302.12 265.5" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(334.5,266.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="33" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;"><b>Event</b></div></div></foreignObject><text x="17" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">&lt;b&gt;Event&lt;/b&gt;</text></switch></g><ellipse cx="254" cy="262" rx="40" ry="40" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(215.5,249.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="76" height="25" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 76px; white-space: normal; word-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Coordination Office</div></div></foreignObject><text x="38" y="19" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">Coordination Office</text></switch></g><g transform="translate(5.5,341.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="577" height="181" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 185px; max-width: 577px; width: 577px; white-space: normal; word-wrap: normal;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><h1>Process Manager</h1><p>Process Manager executes concrete business process instance (e.g. User Registration Process for user X). </p><p>Process Manager is persistent, event-sourced actor. State transition of the process is communicated by Process Manager by an event (like UserEmailConfirmed). Transitions are triggered by external events that Process Manager receives. </p><p>Process Manager is created or activated automatically by Coordination Office whenever external event related (correlated) to this instance of business process is received.</p><p><span style="font-size: 10px ; line-height: 1.26">Sends commands to Command Offices (at-least-once delivery).</span></p><p><span style="font-size: 10px ; line-height: 1.26">Schedules timeout/deadline events. </span><br /></p></div></div></foreignObject><text x="289" y="96" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><ellipse cx="137" cy="256" rx="30" ry="30" fill="#ffffff" stroke="#000000" stroke-width="2" pointer-events="none"/><ellipse cx="142" cy="59" rx="39.5" ry="39.5" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(114.5,45.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="55" height="25" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 56px; white-space: nowrap; word-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Command<div>Office</div></div></div></foreignObject><text x="28" y="19" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><g transform="translate(482.5,187.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="291" height="161" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 180px; max-width: 291px; width: 291px; white-space: normal; word-wrap: normal;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><h1>Receptor</h1><p><span>Receives events from the configured event stream.</span><br /></p><p>Configurable.</p><p>When configured with Coordination Office as the receiver, uses correlationId resolver (function that maps an event to saga id (eg. UserCreated(userId: EntityId, ...) =&gt; userId) defined in the ProcessConfig to add CorrelationId meta-attribute to the event message.</p></div></div></foreignObject><text x="146" y="86" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><g transform="translate(492.5,15.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="290" height="105" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 116px; max-width: 290px; width: 290px; white-space: normal; word-wrap: normal;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><h1>Business Process Stream (BPS)</h1><p>Stream of events particular business process (eg. User Registration) <span style="line-height: 1.26">is interested in.</span></p></div></div></foreignObject><text x="145" y="58" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><rect x="78" y="204" width="230" height="116" rx="17.4" ry="17.4" fill="none" stroke="#000000" stroke-dasharray="3 3" pointer-events="none"/><path d="M 279.98 63 L 318 63 L 389.63 63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 394.88 63 L 387.88 66.5 L 389.63 63 L 387.88 59.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(331.5,69.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="33" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;"><b>Event</b></div></div></foreignObject><text x="17" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">&lt;b&gt;Event&lt;/b&gt;</text></switch></g><path d="M 181.5 54 L 221.63 54" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 226.88 54 L 219.88 57.5 L 221.63 54 L 219.88 50.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><ellipse cx="249" cy="54" rx="21" ry="21" fill="#ffffff" stroke="#000000" stroke-width="2" pointer-events="none"/><ellipse cx="259" cy="64" rx="21" ry="21" fill="#ffffff" stroke="#000000" stroke-width="2" pointer-events="none"/><g transform="translate(249.5,57.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="17" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 17px; white-space: nowrap; word-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">AR</div></div></foreignObject><text x="9" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">AR</text></switch></g><ellipse cx="147" cy="268" rx="30" ry="30" fill="#ffffff" stroke="#000000" stroke-width="2" pointer-events="none"/><g transform="translate(122.5,254.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="47" height="25" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 48px; white-space: nowrap; word-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Process<div>Manager</div></div></div></foreignObject><text x="24" y="19" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 107 256 L 38 256 L 38 59 L 96.63 59" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 101.88 59 L 94.88 62.5 L 96.63 59 L 94.88 55.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(8.5,152.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="58" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;"><b>Command</b></div></div></foreignObject><text x="29" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">&lt;b&gt;Command&lt;/b&gt;</text></switch></g><rect x="78" y="1" width="220" height="116" rx="17.4" ry="17.4" fill="none" stroke="#000000" stroke-dasharray="3 3" pointer-events="none"/><path d="M 214 262 L 194 262 L 197 262 L 183.37 262" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 178.12 262 L 185.12 258.5 L 183.37 262 L 185.12 265.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 426 93 L 426 137.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 426 142.88 L 422.5 135.88 L 426 137.63 L 429.5 135.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(370.5,145.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="24" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">BPS</div></div></foreignObject><text x="12" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">BPS</text></switch></g><path d="M 426 160 L 426 182 L 426 225.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 426 230.88 L 422.5 223.88 L 426 225.63 L 429.5 223.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/></g></svg> \ No newline at end of file
pawelkaczor/pawelkaczor.github.com
9aeaffde781938131daf8ea0427b9ba471596389
office diagram [akka-ddd]
diff --git a/images/akka-ddd/office.png b/images/akka-ddd/office.png new file mode 100644 index 0000000..3d3e2cf Binary files /dev/null and b/images/akka-ddd/office.png differ
pawelkaczor/pawelkaczor.github.com
fa2782637379831c590b2d6c0e2ef2d6a48301c7
switch to rouge highlighter
diff --git a/_config.yml b/_config.yml index 8a08f3a..443bd33 100644 --- a/_config.yml +++ b/_config.yml @@ -1,9 +1,9 @@ --- permalink: /:year/:month/:day/:title lsi: false markdown: kramdown -pygments: true +highlighter: rouge comments: true pretty_style: html_extension auto: true server_port: 4000
pawelkaczor/pawelkaczor.github.com
bbd65d56cf3465202b43c1631f9a25e34251bde0
switch to kramdown
diff --git a/_config.yml b/_config.yml index a6e134a..8a08f3a 100644 --- a/_config.yml +++ b/_config.yml @@ -1,9 +1,9 @@ --- permalink: /:year/:month/:day/:title lsi: false -markdown: rdiscount +markdown: kramdown pygments: true comments: true pretty_style: html_extension auto: true server_port: 4000
pawelkaczor/pawelkaczor.github.com
33c42188f287a731c57ad068d86e18e44c8e2fca
add other akka-ddd svg images
diff --git a/images/akka-ddd/Durable_Scheduler.svg b/images/akka-ddd/Durable_Scheduler.svg new file mode 100644 index 0000000..86cbe8b --- /dev/null +++ b/images/akka-ddd/Durable_Scheduler.svg @@ -0,0 +1,3 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> +<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="653px" height="470px" version="1.1" style="background-color: rgb(255, 255, 255);"><defs><linearGradient x1="0%" y1="0%" x2="0%" y2="100%" id="mx-gradient-f5f5f5-1-b3b3b3-1-s-0"><stop offset="0%" style="stop-color:#F5F5F5"/><stop offset="100%" style="stop-color:#B3B3B3"/></linearGradient></defs><g transform="translate(0.5,0.5)"><ellipse cx="596" cy="26" rx="25" ry="25" fill="#ffffff" stroke="#000000" pointer-events="none"/><ellipse cx="596" cy="26" rx="19.5" ry="19.5" fill="#ffffff" stroke="#000000" pointer-events="none"/><path d="M 596 6.5 L 596 9 M 605.69 9.05 L 604.29 11.5 M 612.77 16.14 L 610.32 17.63 M 615.5 26 L 612.92 26 M 612.77 35.79 L 610.32 34.29 M 605.69 42.87 L 604.29 40.43 M 596 42.92 L 596 45.5 M 586.23 42.87 L 587.63 40.43 M 579.15 35.79 L 581.6 34.29 M 576.5 26 L 579 26 M 579.15 16.14 L 581.6 17.63 M 586.23 9.05 L 587.63 11.5 M 596.96 9.25 L 596 26 L 606.94 26.46" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(580,59)"><switch><foreignObject pointer-events="all" width="32" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Clock</div></div></foreignObject><text x="16" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 471.06 20.12 C 471.24 19.45 471.87 19 472.57 19.02 L 516.46 19.02 L 521 26.71 L 516.46 34 L 472.47 34 C 472.05 33.98 471.65 33.78 471.39 33.46 C 471.12 33.14 471 32.72 471.06 32.31 Z M 472.06 32.17 C 472.18 32.67 472.65 33.02 473.17 33.01 L 516.01 33.01 L 519.99 26.71 L 516.01 19.97 L 473.17 19.97 C 472.71 19.92 472.27 20.16 472.06 20.56 Z M 473.58 22.55 C 473.62 22.09 473.97 21.72 474.44 21.65 L 485.64 21.65 C 486.1 21.72 486.45 22.09 486.49 22.55 L 486.49 30.68 C 486.37 31.07 486.01 31.35 485.58 31.37 L 474.54 31.37 C 474.12 31.35 473.75 31.07 473.63 30.68 Z M 474.94 24.43 L 474.94 30.18 L 485.23 30.18 L 485.23 24.33 L 480.49 27.85 C 480.15 28.07 479.72 28.07 479.38 27.85 Z M 479.98 26.76 L 485.03 22.89 L 474.99 22.89 Z M 487.91 22.55 C 487.93 22.13 488.21 21.78 488.61 21.65 L 499.96 21.65 C 500.36 21.78 500.65 22.13 500.67 22.55 L 500.67 30.68 C 500.57 31.02 500.31 31.28 499.96 31.37 L 488.61 31.37 C 488.27 31.28 488 31.02 487.91 30.68 Z M 489.17 24.38 L 489.17 30.18 L 499.46 30.18 L 499.41 24.38 L 494.77 27.85 C 494.41 28.12 493.91 28.12 493.56 27.85 Z M 494.21 26.76 L 499.31 22.89 L 489.17 22.89 Z M 502.13 22.55 C 502.17 22.09 502.53 21.72 502.99 21.65 L 514.14 21.65 C 514.6 21.72 514.95 22.09 515 22.55 L 515 30.48 C 514.97 30.74 514.84 30.99 514.63 31.15 C 514.42 31.32 514.15 31.4 513.89 31.37 L 502.99 31.37 C 502.59 31.33 502.25 31.06 502.13 30.68 Z M 503.34 24.38 L 503.34 30.18 L 513.63 30.18 L 513.63 24.38 L 508.89 27.85 C 508.58 28.03 508.2 28.03 507.88 27.85 Z M 508.44 26.76 L 513.48 22.89 L 503.39 22.89 Z" fill-opacity="0.6" fill="url(#mx-gradient-f5f5f5-1-b3b3b3-1-s-0)" stroke="#666666" stroke-opacity="0.6" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(483,4)"><switch><foreignObject pointer-events="all" width="25" height="14" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">clock</div></div></foreignObject><text x="13" y="12" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 571 26 L 523.24 26" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 529.12 22.5 L 522.12 26 L 529.12 29.5" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(545,24)"><switch><foreignObject pointer-events="all" width="14" height="11" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 8px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">tick</div></div></foreignObject><text x="7" y="10" fill="#000000" text-anchor="middle" font-size="8px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><ellipse cx="26" cy="26" rx="25" ry="25" fill="#ffffff" stroke="#000000" pointer-events="none"/><ellipse cx="26" cy="26" rx="21" ry="21" fill="none" stroke="#000000" pointer-events="none"/><g transform="translate(7,20)"><switch><foreignObject pointer-events="all" width="37" height="15" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 11px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 37px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Saga</div></div></foreignObject><text x="19" y="13" fill="#000000" text-anchor="middle" font-size="11px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 51 26 L 143.76 26" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 137.88 29.5 L 144.88 26 L 137.88 22.5" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(61,23)"><switch><foreignObject pointer-events="all" width="57" height="11" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 8px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">Schedule event</div></div></foreignObject><text x="29" y="10" fill="#000000" text-anchor="middle" font-size="8px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><ellipse cx="211" cy="243" rx="25" ry="25" fill="#ffffff" stroke="#575757" pointer-events="none"/><g transform="translate(187,235)"><switch><foreignObject pointer-events="all" width="47" height="20" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 8px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 47px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Deadlines<div>receptor</div></div></div></foreignObject><text x="24" y="14" fill="#000000" text-anchor="middle" font-size="8px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 356.06 169.12 C 356.24 168.45 356.87 168 357.57 168.02 L 401.46 168.02 L 406 175.71 L 401.46 183 L 357.47 183 C 357.05 182.98 356.65 182.78 356.39 182.46 C 356.12 182.14 356 181.72 356.06 181.31 Z M 357.06 181.17 C 357.18 181.67 357.65 182.02 358.17 182.01 L 401.01 182.01 L 404.99 175.71 L 401.01 168.97 L 358.17 168.97 C 357.71 168.92 357.27 169.16 357.06 169.56 Z M 358.58 171.55 C 358.62 171.09 358.97 170.72 359.44 170.65 L 370.64 170.65 C 371.1 170.72 371.45 171.09 371.49 171.55 L 371.49 179.68 C 371.37 180.07 371.01 180.35 370.58 180.37 L 359.54 180.37 C 359.12 180.35 358.75 180.07 358.63 179.68 Z M 359.94 173.43 L 359.94 179.18 L 370.23 179.18 L 370.23 173.33 L 365.49 176.85 C 365.15 177.07 364.72 177.07 364.38 176.85 Z M 364.98 175.76 L 370.03 171.89 L 359.99 171.89 Z M 372.91 171.55 C 372.93 171.13 373.21 170.78 373.61 170.65 L 384.96 170.65 C 385.36 170.78 385.65 171.13 385.67 171.55 L 385.67 179.68 C 385.57 180.02 385.31 180.28 384.96 180.37 L 373.61 180.37 C 373.27 180.28 373 180.02 372.91 179.68 Z M 374.17 173.38 L 374.17 179.18 L 384.46 179.18 L 384.41 173.38 L 379.77 176.85 C 379.41 177.12 378.91 177.12 378.56 176.85 Z M 379.21 175.76 L 384.31 171.89 L 374.17 171.89 Z M 387.13 171.55 C 387.17 171.09 387.53 170.72 387.99 170.65 L 399.14 170.65 C 399.6 170.72 399.95 171.09 400 171.55 L 400 179.48 C 399.97 179.74 399.84 179.99 399.63 180.15 C 399.42 180.32 399.15 180.4 398.89 180.37 L 387.99 180.37 C 387.59 180.33 387.25 180.06 387.13 179.68 Z M 388.34 173.38 L 388.34 179.18 L 398.63 179.18 L 398.63 173.38 L 393.89 176.85 C 393.58 177.03 393.2 177.03 392.88 176.85 Z M 393.44 175.76 L 398.48 171.89 L 388.39 171.89 Z" fill-opacity="0.6" fill="url(#mx-gradient-f5f5f5-1-b3b3b3-1-s-0)" stroke="#575757" stroke-opacity="0.6" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(335,153)"><switch><foreignObject pointer-events="all" width="91" height="14" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">upcoming deadlines</div></div></foreignObject><text x="46" y="12" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 296 244 L 238.24 243.04" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 244.18 239.64 L 237.12 243.02 L 244.06 246.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 471 26 L 439 26 L 439 178 L 408.24 178" fill="none" stroke="#000000" stroke-miterlimit="10" stroke-dasharray="3 3" pointer-events="none"/><path d="M 414.12 174.5 L 407.12 178 L 414.12 181.5" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 291 108 L 291 178 L 348.76 178" fill="none" stroke="#000000" stroke-miterlimit="10" stroke-dasharray="3 3" pointer-events="none"/><path d="M 342.88 181.5 L 349.88 178 L 342.88 174.5" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><ellipse cx="456" cy="243" rx="25" ry="25" fill="#ffffff" stroke="#575757" pointer-events="none"/><g transform="translate(431,230)"><switch><foreignObject pointer-events="all" width="49" height="29" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 8px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 47px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Upcoming deadlines manager</div></div></foreignObject><text x="25" y="19" fill="#000000" text-anchor="middle" font-size="8px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 438.32 225.32 L 402.58 189.58" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 409.22 191.27 L 401.79 188.79 L 404.27 196.22" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(409,209)"><switch><foreignObject pointer-events="all" width="36" height="11" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 8px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">maintains</div></div></foreignObject><text x="18" y="10" fill="#000000" text-anchor="middle" font-size="8px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 194.93 223.85 L 45.44 45.71" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 51.9 47.97 L 44.72 44.86 L 46.54 52.47" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(126,161)"><switch><foreignObject pointer-events="all" width="52" height="20" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 8px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">send deadline<div>payload</div></div></div></foreignObject><text x="26" y="14" fill="#000000" text-anchor="middle" font-size="8px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><g transform="translate(41,308)"><switch><foreignObject pointer-events="all" width="180" height="68" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 8px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 70px; max-width: 180px; width: 180px; white-space: normal;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><h1><font style="font-size: 12px">Deadline partition</font></h1><p>Projection (index) of deadlines in particular time period (partition) eg. July 2015, 01.05.2015.</p></div></div></foreignObject><text x="90" y="38" fill="#000000" text-anchor="middle" font-size="8px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><g transform="translate(226,308)"><switch><foreignObject pointer-events="all" width="180" height="148" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 8px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 160px; max-width: 180px; width: 180px; white-space: normal;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><h1><font style="font-size: 12px">Upcoming deadlines</font></h1><p>Projection (index) of deadlines in time period containing current time. Needs to be recreated by 'Upcoming deadlines manager' on regular basis (hourly, daily...etc depending on configured deadline partition key).</p><p>'Upcoming deadlines' projection keeps all its deadline messages in internal state (in memory) so it can detect which deadlines are overdue once tick is received. Overdue deadlines are linked to `current deadlines`.</p></div></div></foreignObject><text x="90" y="78" fill="#000000" text-anchor="middle" font-size="8px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><g transform="translate(466,308)"><switch><foreignObject pointer-events="all" width="180" height="112" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 8px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 150px; max-width: 180px; width: 180px; white-space: normal;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><h1><font style="font-size: 12px">Clock</font></h1><p>Time moves on if Clock is ticking (tick = currentEpoch message). Scheduling accuracy depends on frequency of ticks (eg 1 tick per minute -&gt; 1 minute accuracy).</p><p>Retention of `clock` event stream should be set to 1 event (no historical ticks).</p></div></div></foreignObject><text x="90" y="60" fill="#000000" text-anchor="middle" font-size="8px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 296.06 237.12 C 296.24 236.45 296.87 236 297.57 236.02 L 341.46 236.02 L 346 243.71 L 341.46 251 L 297.47 251 C 297.05 250.98 296.65 250.78 296.39 250.46 C 296.12 250.14 296 249.72 296.06 249.31 Z M 297.06 249.17 C 297.18 249.67 297.65 250.02 298.17 250.01 L 341.01 250.01 L 344.99 243.71 L 341.01 236.97 L 298.17 236.97 C 297.71 236.92 297.27 237.16 297.06 237.56 Z M 298.58 239.55 C 298.62 239.09 298.97 238.72 299.44 238.65 L 310.64 238.65 C 311.1 238.72 311.45 239.09 311.49 239.55 L 311.49 247.68 C 311.37 248.07 311.01 248.35 310.58 248.37 L 299.54 248.37 C 299.12 248.35 298.75 248.07 298.63 247.68 Z M 299.94 241.43 L 299.94 247.18 L 310.23 247.18 L 310.23 241.33 L 305.49 244.85 C 305.15 245.07 304.72 245.07 304.38 244.85 Z M 304.98 243.76 L 310.03 239.89 L 299.99 239.89 Z M 312.91 239.55 C 312.93 239.13 313.21 238.78 313.61 238.65 L 324.96 238.65 C 325.36 238.78 325.65 239.13 325.67 239.55 L 325.67 247.68 C 325.57 248.02 325.31 248.28 324.96 248.37 L 313.61 248.37 C 313.27 248.28 313 248.02 312.91 247.68 Z M 314.17 241.38 L 314.17 247.18 L 324.46 247.18 L 324.41 241.38 L 319.77 244.85 C 319.41 245.12 318.91 245.12 318.56 244.85 Z M 319.21 243.76 L 324.31 239.89 L 314.17 239.89 Z M 327.13 239.55 C 327.17 239.09 327.53 238.72 327.99 238.65 L 339.14 238.65 C 339.6 238.72 339.95 239.09 340 239.55 L 340 247.48 C 339.97 247.74 339.84 247.99 339.63 248.15 C 339.42 248.32 339.15 248.4 338.89 248.37 L 327.99 248.37 C 327.59 248.33 327.25 248.06 327.13 247.68 Z M 328.34 241.38 L 328.34 247.18 L 338.63 247.18 L 338.63 241.38 L 333.89 244.85 C 333.58 245.03 333.2 245.03 332.88 244.85 Z M 333.44 243.76 L 338.48 239.89 L 328.39 239.89 Z" fill-opacity="0.6" fill="url(#mx-gradient-f5f5f5-1-b3b3b3-1-s-0)" stroke="#575757" stroke-opacity="0.6" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(281,259)"><switch><foreignObject pointer-events="all" width="79" height="14" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">current deadlines</div></div></foreignObject><text x="40" y="12" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 376.99 183 L 347.05 239.03" fill="none" stroke="#000000" stroke-miterlimit="10" stroke-dasharray="3 3" pointer-events="none"/><path d="M 346.74 232.19 L 346.53 240.01 L 352.91 235.49" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(348,209)"><switch><foreignObject pointer-events="all" width="30" height="11" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 8px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">updates</div></div></foreignObject><text x="15" y="10" fill="#000000" text-anchor="middle" font-size="8px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 36 124 L 96 124 L 96 164 L 36 164 Z" fill="#ffffff" stroke="#575757" stroke-miterlimit="10" pointer-events="none"/><path d="M 36 124 L 66 144 L 96 124" fill="none" stroke="#575757" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(42,111)"><switch><foreignObject pointer-events="all" width="47" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 9px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 47px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Deadline</div></div></foreignObject><text x="24" y="11" fill="#000000" text-anchor="middle" font-size="9px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><g transform="translate(38,140)"><switch><foreignObject pointer-events="all" width="45" height="23" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 6px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 26px; max-width: 46px; width: 45px; white-space: normal;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">- target<div>- deadlineEpoch</div><div>- payload</div></div></div></foreignObject><text x="23" y="15" fill="#000000" text-anchor="middle" font-size="6px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 211.04 59.12 C 211.19 58.45 211.69 58 212.26 58.02 L 247.37 58.02 L 251 65.71 L 247.37 73 L 212.17 73 C 211.84 72.98 211.52 72.78 211.31 72.46 C 211.09 72.14 211 71.72 211.04 71.31 Z M 211.85 71.17 C 211.95 71.67 212.32 72.02 212.74 72.01 L 247 72.01 L 250.19 65.71 L 247 58.97 L 212.74 58.97 C 212.37 58.92 212.02 59.16 211.85 59.56 Z M 213.06 61.55 C 213.1 61.09 213.38 60.72 213.75 60.65 L 222.71 60.65 C 223.08 60.72 223.36 61.09 223.39 61.55 L 223.39 69.68 C 223.29 70.07 223 70.35 222.67 70.37 L 213.83 70.37 C 213.49 70.35 213.2 70.07 213.1 69.68 Z M 214.15 63.43 L 214.15 69.18 L 222.39 69.18 L 222.39 63.33 L 218.59 66.85 C 218.32 67.07 217.97 67.07 217.7 66.85 Z M 218.19 65.76 L 222.22 61.89 L 214.19 61.89 Z M 224.52 61.55 C 224.54 61.13 224.77 60.78 225.09 60.65 L 234.17 60.65 C 234.49 60.78 234.72 61.13 234.74 61.55 L 234.74 69.68 C 234.66 70.02 234.45 70.28 234.17 70.37 L 225.09 70.37 C 224.81 70.28 224.6 70.02 224.52 69.68 Z M 225.53 63.38 L 225.53 69.18 L 233.77 69.18 L 233.73 63.38 L 230.01 66.85 C 229.73 67.12 229.33 67.12 229.04 66.85 Z M 229.57 65.76 L 233.65 61.89 L 225.53 61.89 Z M 235.91 61.55 C 235.94 61.09 236.22 60.72 236.59 60.65 L 245.51 60.65 C 245.88 60.72 246.16 61.09 246.2 61.55 L 246.2 69.48 C 246.18 69.74 246.07 69.99 245.9 70.15 C 245.74 70.32 245.52 70.4 245.31 70.37 L 236.59 70.37 C 236.27 70.33 236 70.06 235.91 69.68 Z M 236.87 63.38 L 236.87 69.18 L 245.11 69.18 L 245.11 63.38 L 241.31 66.85 C 241.06 67.03 240.76 67.03 240.51 66.85 Z M 240.95 65.76 L 244.99 61.89 L 236.91 61.89 Z" fill-opacity="0.6" fill="url(#mx-gradient-f5f5f5-1-b3b3b3-1-s-0)" stroke="#575757" stroke-opacity="0.6" stroke-miterlimit="10" pointer-events="none"/><path d="M 271.04 59.12 C 271.19 58.45 271.69 58 272.26 58.02 L 307.37 58.02 L 311 65.71 L 307.37 73 L 272.17 73 C 271.84 72.98 271.52 72.78 271.31 72.46 C 271.09 72.14 271 71.72 271.04 71.31 Z M 271.85 71.17 C 271.95 71.67 272.32 72.02 272.74 72.01 L 307 72.01 L 310.19 65.71 L 307 58.97 L 272.74 58.97 C 272.37 58.92 272.02 59.16 271.85 59.56 Z M 273.06 61.55 C 273.1 61.09 273.38 60.72 273.75 60.65 L 282.71 60.65 C 283.08 60.72 283.36 61.09 283.39 61.55 L 283.39 69.68 C 283.29 70.07 283 70.35 282.67 70.37 L 273.83 70.37 C 273.49 70.35 273.2 70.07 273.1 69.68 Z M 274.15 63.43 L 274.15 69.18 L 282.39 69.18 L 282.39 63.33 L 278.59 66.85 C 278.32 67.07 277.97 67.07 277.7 66.85 Z M 278.19 65.76 L 282.22 61.89 L 274.19 61.89 Z M 284.52 61.55 C 284.54 61.13 284.77 60.78 285.09 60.65 L 294.17 60.65 C 294.49 60.78 294.72 61.13 294.74 61.55 L 294.74 69.68 C 294.66 70.02 294.45 70.28 294.17 70.37 L 285.09 70.37 C 284.81 70.28 284.6 70.02 284.52 69.68 Z M 285.53 63.38 L 285.53 69.18 L 293.77 69.18 L 293.73 63.38 L 290.01 66.85 C 289.73 67.12 289.33 67.12 289.04 66.85 Z M 289.57 65.76 L 293.65 61.89 L 285.53 61.89 Z M 295.91 61.55 C 295.94 61.09 296.22 60.72 296.59 60.65 L 305.51 60.65 C 305.88 60.72 306.16 61.09 306.2 61.55 L 306.2 69.48 C 306.18 69.74 306.07 69.99 305.9 70.15 C 305.74 70.32 305.52 70.4 305.31 70.37 L 296.59 70.37 C 296.27 70.33 296 70.06 295.91 69.68 Z M 296.87 63.38 L 296.87 69.18 L 305.11 69.18 L 305.11 63.38 L 301.31 66.85 C 301.06 67.03 300.76 67.03 300.51 66.85 Z M 300.95 65.76 L 304.99 61.89 L 296.91 61.89 Z" fill-opacity="0.6" fill="url(#mx-gradient-f5f5f5-1-b3b3b3-1-s-0)" stroke="#575757" stroke-opacity="0.6" stroke-miterlimit="10" pointer-events="none"/><path d="M 236.07 19.12 C 236.31 18.45 237.13 18 238.04 18.02 L 295.1 18.02 L 301 25.71 L 295.1 33 L 237.91 33 C 237.36 32.98 236.85 32.78 236.5 32.46 C 236.15 32.14 236 31.72 236.07 31.31 Z M 237.38 31.17 C 237.54 31.67 238.14 32.02 238.83 32.01 L 294.51 32.01 L 299.69 25.71 L 294.51 18.97 L 238.83 18.97 C 238.23 18.92 237.65 19.16 237.38 19.56 Z M 239.35 21.55 C 239.41 21.09 239.87 20.72 240.47 20.65 L 255.03 20.65 C 255.63 20.72 256.09 21.09 256.14 21.55 L 256.14 29.68 C 255.98 30.07 255.51 30.35 254.96 30.37 L 240.6 30.37 C 240.05 30.35 239.58 30.07 239.42 29.68 Z M 241.12 23.43 L 241.12 29.18 L 254.5 29.18 L 254.5 23.33 L 248.34 26.85 C 247.9 27.07 247.33 27.07 246.89 26.85 Z M 247.68 25.76 L 254.24 21.89 L 241.19 21.89 Z M 257.98 21.55 C 258.01 21.13 258.37 20.78 258.9 20.65 L 273.65 20.65 C 274.17 20.78 274.54 21.13 274.57 21.55 L 274.57 29.68 C 274.45 30.02 274.1 30.28 273.65 30.37 L 258.9 30.37 C 258.45 30.28 258.1 30.02 257.98 29.68 Z M 259.62 23.38 L 259.62 29.18 L 273 29.18 L 272.93 23.38 L 266.9 26.85 C 266.43 27.12 265.79 27.12 265.32 26.85 Z M 266.18 25.76 L 272.8 21.89 L 259.62 21.89 Z M 276.47 21.55 C 276.53 21.09 276.99 20.72 277.59 20.65 L 292.08 20.65 C 292.68 20.72 293.14 21.09 293.2 21.55 L 293.2 29.48 C 293.16 29.74 292.99 29.99 292.72 30.15 C 292.45 30.32 292.1 30.4 291.75 30.37 L 277.59 30.37 C 277.06 30.33 276.63 30.06 276.47 29.68 Z M 278.05 23.38 L 278.05 29.18 L 291.42 29.18 L 291.42 23.38 L 285.26 26.85 C 284.85 27.03 284.35 27.03 283.95 26.85 Z M 284.67 25.76 L 291.23 21.89 L 278.11 21.89 Z" fill-opacity="0.6" fill="url(#mx-gradient-f5f5f5-1-b3b3b3-1-s-0)" stroke="#575757" stroke-opacity="0.6" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(248,5)"><switch><foreignObject pointer-events="all" width="41" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 9px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">deadlines</div></div></foreignObject><text x="21" y="11" fill="#000000" text-anchor="middle" font-size="9px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 211.04 89.12 C 211.19 88.45 211.69 88 212.26 88.02 L 247.37 88.02 L 251 95.71 L 247.37 103 L 212.17 103 C 211.84 102.98 211.52 102.78 211.31 102.46 C 211.09 102.14 211 101.72 211.04 101.31 Z M 211.85 101.17 C 211.95 101.67 212.32 102.02 212.74 102.01 L 247 102.01 L 250.19 95.71 L 247 88.97 L 212.74 88.97 C 212.37 88.92 212.02 89.16 211.85 89.56 Z M 213.06 91.55 C 213.1 91.09 213.38 90.72 213.75 90.65 L 222.71 90.65 C 223.08 90.72 223.36 91.09 223.39 91.55 L 223.39 99.68 C 223.29 100.07 223 100.35 222.67 100.37 L 213.83 100.37 C 213.49 100.35 213.2 100.07 213.1 99.68 Z M 214.15 93.43 L 214.15 99.18 L 222.39 99.18 L 222.39 93.33 L 218.59 96.85 C 218.32 97.07 217.97 97.07 217.7 96.85 Z M 218.19 95.76 L 222.22 91.89 L 214.19 91.89 Z M 224.52 91.55 C 224.54 91.13 224.77 90.78 225.09 90.65 L 234.17 90.65 C 234.49 90.78 234.72 91.13 234.74 91.55 L 234.74 99.68 C 234.66 100.02 234.45 100.28 234.17 100.37 L 225.09 100.37 C 224.81 100.28 224.6 100.02 224.52 99.68 Z M 225.53 93.38 L 225.53 99.18 L 233.77 99.18 L 233.73 93.38 L 230.01 96.85 C 229.73 97.12 229.33 97.12 229.04 96.85 Z M 229.57 95.76 L 233.65 91.89 L 225.53 91.89 Z M 235.91 91.55 C 235.94 91.09 236.22 90.72 236.59 90.65 L 245.51 90.65 C 245.88 90.72 246.16 91.09 246.2 91.55 L 246.2 99.48 C 246.18 99.74 246.07 99.99 245.9 100.15 C 245.74 100.32 245.52 100.4 245.31 100.37 L 236.59 100.37 C 236.27 100.33 236 100.06 235.91 99.68 Z M 236.87 93.38 L 236.87 99.18 L 245.11 99.18 L 245.11 93.38 L 241.31 96.85 C 241.06 97.03 240.76 97.03 240.51 96.85 Z M 240.95 95.76 L 244.99 91.89 L 236.91 91.89 Z" fill-opacity="0.6" fill="url(#mx-gradient-f5f5f5-1-b3b3b3-1-s-0)" stroke="#575757" stroke-opacity="0.6" stroke-miterlimit="10" pointer-events="none"/><path d="M 271.04 89.12 C 271.19 88.45 271.69 88 272.26 88.02 L 307.37 88.02 L 311 95.71 L 307.37 103 L 272.17 103 C 271.84 102.98 271.52 102.78 271.31 102.46 C 271.09 102.14 271 101.72 271.04 101.31 Z M 271.85 101.17 C 271.95 101.67 272.32 102.02 272.74 102.01 L 307 102.01 L 310.19 95.71 L 307 88.97 L 272.74 88.97 C 272.37 88.92 272.02 89.16 271.85 89.56 Z M 273.06 91.55 C 273.1 91.09 273.38 90.72 273.75 90.65 L 282.71 90.65 C 283.08 90.72 283.36 91.09 283.39 91.55 L 283.39 99.68 C 283.29 100.07 283 100.35 282.67 100.37 L 273.83 100.37 C 273.49 100.35 273.2 100.07 273.1 99.68 Z M 274.15 93.43 L 274.15 99.18 L 282.39 99.18 L 282.39 93.33 L 278.59 96.85 C 278.32 97.07 277.97 97.07 277.7 96.85 Z M 278.19 95.76 L 282.22 91.89 L 274.19 91.89 Z M 284.52 91.55 C 284.54 91.13 284.77 90.78 285.09 90.65 L 294.17 90.65 C 294.49 90.78 294.72 91.13 294.74 91.55 L 294.74 99.68 C 294.66 100.02 294.45 100.28 294.17 100.37 L 285.09 100.37 C 284.81 100.28 284.6 100.02 284.52 99.68 Z M 285.53 93.38 L 285.53 99.18 L 293.77 99.18 L 293.73 93.38 L 290.01 96.85 C 289.73 97.12 289.33 97.12 289.04 96.85 Z M 289.57 95.76 L 293.65 91.89 L 285.53 91.89 Z M 295.91 91.55 C 295.94 91.09 296.22 90.72 296.59 90.65 L 305.51 90.65 C 305.88 90.72 306.16 91.09 306.2 91.55 L 306.2 99.48 C 306.18 99.74 306.07 99.99 305.9 100.15 C 305.74 100.32 305.52 100.4 305.31 100.37 L 296.59 100.37 C 296.27 100.33 296 100.06 295.91 99.68 Z M 296.87 93.38 L 296.87 99.18 L 305.11 99.18 L 305.11 93.38 L 301.31 96.85 C 301.06 97.03 300.76 97.03 300.51 96.85 Z M 300.95 95.76 L 304.99 91.89 L 296.91 91.89 Z" fill-opacity="0.6" fill="url(#mx-gradient-f5f5f5-1-b3b3b3-1-s-0)" stroke="#575757" stroke-opacity="0.6" stroke-miterlimit="10" pointer-events="none"/><g opacity="0.6" transform="translate(322,23)"><switch><foreignObject pointer-events="all" width="10" height="11" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 8px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 16px; max-width: 36px; width: 10px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">all</div></div></foreignObject><text x="5" y="10" fill="#000000" text-anchor="middle" font-size="8px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><g opacity="0.6" transform="translate(321,63)"><switch><foreignObject pointer-events="all" width="30" height="11" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 8px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 16px; max-width: 36px; width: 30px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">monthly</div></div></foreignObject><text x="15" y="10" fill="#000000" text-anchor="middle" font-size="8px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><g opacity="0.6" transform="translate(322,93)"><switch><foreignObject pointer-events="all" width="18" height="11" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 8px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 16px; max-width: 36px; width: 18px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">daily</div></div></foreignObject><text x="9" y="10" fill="#000000" text-anchor="middle" font-size="8px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 231 82 L 291 82" fill="none" stroke="#000000" stroke-opacity="0.6" stroke-miterlimit="10" stroke-dasharray="3 3" transform="rotate(90,261,82)" pointer-events="none"/><g transform="translate(229,40)"><switch><foreignObject pointer-events="all" width="76" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 9px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 16px; max-width: 76px; width: 76px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">deadline partitions</div></div></foreignObject><text x="38" y="11" fill="#000000" text-anchor="middle" font-size="9px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><ellipse cx="171" cy="26" rx="25" ry="25" fill="#ffffff" stroke="#575757" pointer-events="none"/><g transform="translate(145,18)"><switch><foreignObject pointer-events="all" width="51" height="20" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 8px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 51px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Scheduling<div>Office</div></div></div></foreignObject><text x="26" y="14" fill="#000000" text-anchor="middle" font-size="8px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 196 26 L 228.76 26" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 222.88 29.5 L 229.88 26 L 222.88 22.5" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/></g></svg> \ No newline at end of file diff --git a/images/akka-ddd/Ordering_System.svg b/images/akka-ddd/Ordering_System.svg new file mode 100644 index 0000000..a951984 --- /dev/null +++ b/images/akka-ddd/Ordering_System.svg @@ -0,0 +1,3 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> +<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="574px" height="184px" version="1.1" style="background-color: rgb(255, 255, 255);"><defs/><g transform="translate(0.5,0.5)"><rect x="253" y="2" width="43" height="180" rx="6.45" ry="6.45" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(254,47)"><switch><foreignObject pointer-events="all" width="40" height="93" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 11px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 40px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><div><br /></div><div><br /></div><div><br /></div><div><br /></div><div><br /></div>Event<div>Store</div></div></div></foreignObject><text x="20" y="52" fill="#000000" text-anchor="middle" font-size="11px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 298 22 L 402.93 22 L 420 27.5 L 402.93 33 L 298 33 L 314.44 27.5 Z" fill="#a9c4eb" stroke="none" pointer-events="none"/><g transform="translate(312,24)"><switch><foreignObject pointer-events="all" width="94" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 9px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Reservation Confirmed</div></div></foreignObject><text x="47" y="11" fill="#000000" text-anchor="middle" font-size="9px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><ellipse cx="452" cy="37" rx="30" ry="30" fill="#ffe599" stroke="#000000" pointer-events="none"/><g transform="translate(426,32)"><switch><foreignObject pointer-events="all" width="51" height="14" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 51px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Invoicing</div></div></foreignObject><text x="26" y="12" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 298 42 L 402.93 42 L 420 47.5 L 402.93 53 L 298 53 L 314.44 47.5 Z" fill="#ffe599" stroke="none" pointer-events="none"/><g transform="translate(324,44)"><switch><foreignObject pointer-events="all" width="71" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 9px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Payment Expired</div></div></foreignObject><text x="36" y="11" fill="#000000" text-anchor="middle" font-size="9px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><ellipse cx="112" cy="100" rx="30" ry="30" fill="#a9c4eb" stroke="#000000" pointer-events="none"/><g transform="translate(93,95)"><switch><foreignObject pointer-events="all" width="37" height="14" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 37px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><div>Sales</div></div></div></foreignObject><text x="19" y="12" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 143 78 L 236.75 78 L 252 83.5 L 236.75 89 L 143 89 L 157.68 83.5 Z" fill="#ffe599" stroke="none" transform="rotate(180,197.5,83.5)" pointer-events="none"/><g transform="translate(171,80)"><switch><foreignObject pointer-events="all" width="53" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 9px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Billing Failed</div></div></foreignObject><text x="27" y="11" fill="#000000" text-anchor="middle" font-size="9px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><ellipse cx="452" cy="143" rx="30" ry="30" fill="#b9e0a5" stroke="#000000" pointer-events="none"/><g transform="translate(426,138)"><switch><foreignObject pointer-events="all" width="51" height="14" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 51px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Shipping</div></div></foreignObject><text x="26" y="12" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 143 108 L 236.75 108 L 252 113.5 L 236.75 119 L 143 119 L 157.68 113.5 Z" fill="#b9e0a5" stroke="none" transform="rotate(180,197.5,113.5)" pointer-events="none"/><g transform="translate(163,110)"><switch><foreignObject pointer-events="all" width="69" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 9px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Goods Delivered</div></div></foreignObject><text x="35" y="11" fill="#000000" text-anchor="middle" font-size="9px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 298 138 L 402.93 138 L 420 143.5 L 402.93 149 L 298 149 L 314.44 143.5 Z" fill="#ffe599" stroke="none" pointer-events="none"/><g transform="translate(334,140)"><switch><foreignObject pointer-events="all" width="50" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 9px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Order Billed</div></div></foreignObject><text x="25" y="11" fill="#000000" text-anchor="middle" font-size="9px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M -8 37 L 88.33 37 L 104 42.5 L 88.33 48 L -8 48 L 7.09 42.5 Z" fill="none" stroke="#b3b3b3" stroke-miterlimit="10" transform="rotate(40,48,42.5)" pointer-events="none"/><g transform="translate(6,38)rotate(40,42,4)"><switch><foreignObject pointer-events="all" width="84" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 9px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Confirm Reservation</div></div></foreignObject><text x="42" y="11" fill="#000000" text-anchor="middle" font-size="9px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 359 53 L 369 63 L 359 73 L 349 63 Z" fill-opacity="0.5" fill="#ffffff" stroke="#000000" stroke-opacity="0.5" stroke-miterlimit="10" transform="rotate(45,359,63)" pointer-events="none"/><ellipse cx="359" cy="63" rx="5" ry="5" fill-opacity="0.5" fill="#ffffff" stroke="#000000" stroke-opacity="0.5" transform="rotate(45,359,63)" pointer-events="none"/><ellipse cx="359" cy="63" rx="3.9000000000000004" ry="3.9000000000000004" fill-opacity="0.5" fill="#ffffff" stroke="#000000" stroke-opacity="0.5" transform="rotate(45,359,63)" pointer-events="none"/><path d="M 359 59.1 L 359 59.6 M 360.94 59.61 L 360.66 60.1 M 362.35 61.03 L 361.86 61.33 M 362.9 63 L 362.38 63 M 362.35 64.96 L 361.86 64.66 M 360.94 66.37 L 360.66 65.89 M 359 66.38 L 359 66.9 M 357.05 66.37 L 357.33 65.89 M 355.63 64.96 L 356.12 64.66 M 355.1 63 L 355.6 63 M 355.63 61.03 L 356.12 61.33 M 357.05 59.61 L 357.33 60.1 M 359.19 59.65 L 359 63 L 361.19 63.09" fill="none" stroke="#000000" stroke-opacity="0.5" stroke-miterlimit="10" transform="rotate(45,359,63)" pointer-events="none"/><path d="M 2 61 L 2 52.46 C 3.17 49.58 4.96 47.33 7.11 46.06 C 7.73 45.79 8.38 45.68 9.02 45.75 C 9.01 48.39 10.38 50.63 12.21 50.94 C 13.21 51.02 14.18 50.51 14.91 49.53 C 15.63 48.55 16.04 47.18 16.04 45.75 C 16.81 45.61 17.6 45.71 18.34 46.06 C 20.11 47.4 21.43 49.71 22 52.46 L 22 61 Z M 16.04 45.75 C 16.04 47.18 15.63 48.55 14.91 49.53 C 14.18 50.51 13.21 51.02 12.21 50.94 C 10.38 50.63 9.01 48.39 9.02 45.75 C 9.38 45.7 9.74 45.6 10.09 45.45 L 10.3 44.23 C 9.62 44 9.07 43.32 8.81 42.4 C 8.26 40.88 8.8 39.2 10.15 38.25 C 11.5 37.3 13.35 37.3 14.7 38.25 C 16.05 39.2 16.59 40.88 16.04 42.4 C 15.69 43.33 15.07 44 14.34 44.23 L 14.55 45.45 Z" fill="#ffffff" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 5.4 56.12 L 5.4 60.7 M 17.96 56.12 L 17.96 60.7" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 8.81 42.4 C 7.85 41.03 7.6 38.96 8.17 37.21 C 8.89 34.9 10.45 33.37 12.21 33.25 C 14.2 33 16.08 34.59 16.89 37.21 C 17.41 39.02 17.07 41.11 16.04 42.4 C 16.11 41.44 15.96 40.48 15.62 39.65 C 14.72 38.85 13.61 38.74 12.64 39.35 C 11.61 38.62 10.4 38.74 9.45 39.65 C 9.03 40.44 8.81 41.41 8.81 42.4 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 470 72 L 563.75 72 L 579 77.5 L 563.75 83 L 470 83 L 484.68 77.5 Z" fill="none" stroke="#b3b3b3" stroke-miterlimit="10" transform="rotate(220,524.5,77.5)" pointer-events="none"/><g transform="translate(488,73)rotate(40,36.5,4)"><switch><foreignObject pointer-events="all" width="73" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 9px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Receive Payment</div></div></foreignObject><text x="37" y="11" fill="#000000" text-anchor="middle" font-size="9px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 523 63 L 523 54.46 C 524.17 51.58 525.96 49.33 528.11 48.06 C 528.73 47.79 529.38 47.68 530.02 47.75 C 530.01 50.39 531.38 52.63 533.21 52.94 C 534.21 53.02 535.18 52.51 535.91 51.53 C 536.63 50.55 537.04 49.18 537.04 47.75 C 537.81 47.61 538.6 47.71 539.34 48.06 C 541.11 49.4 542.43 51.71 543 54.46 L 543 63 Z M 537.04 47.75 C 537.04 49.18 536.63 50.55 535.91 51.53 C 535.18 52.51 534.21 53.02 533.21 52.94 C 531.38 52.63 530.01 50.39 530.02 47.75 C 530.38 47.7 530.74 47.6 531.09 47.45 L 531.3 46.23 C 530.62 46 530.07 45.32 529.81 44.4 C 529.26 42.88 529.8 41.2 531.15 40.25 C 532.5 39.3 534.35 39.3 535.7 40.25 C 537.05 41.2 537.59 42.88 537.04 44.4 C 536.69 45.33 536.07 46 535.34 46.23 L 535.55 47.45 Z" fill="#ffffff" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 526.4 58.12 L 526.4 62.7 M 538.96 58.12 L 538.96 62.7" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 529.81 44.4 C 528.85 43.03 528.6 40.96 529.17 39.21 C 529.89 36.9 531.45 35.37 533.21 35.25 C 535.2 35 537.08 36.59 537.89 39.21 C 538.41 41.02 538.07 43.11 537.04 44.4 C 537.11 43.44 536.96 42.48 536.62 41.65 C 535.72 40.85 534.61 40.74 533.64 41.35 C 532.61 40.62 531.4 40.74 530.45 41.65 C 530.03 42.44 529.81 43.41 529.81 44.4 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><image x="252" y="69" width="44" height="40" xlink:href="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNDAgMjQwIiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCAyNDAgMjQwIj48cGF0aCBmaWxsPSIjZmZmIiBkPSJNMTE5LjUgMjBDNzcuMzUgMjAgMzIgMzIuNzA2IDMyIDYwLjYyNXYxMTguNzVDMzIgMjA3LjI4IDc3LjM1IDIyMCAxMTkuNSAyMjBjNDIuMTQ0IDAgODcuNS0xMi43MiA4Ny41LTQwLjYyNVY2MC42MjVDMjA3IDMyLjcwNSAxNjEuNjM4IDIwIDExOS41IDIwek0xOTUgMTc5LjM3NWMwIDE1LjUyNS0zMy41OCAyOC4xMjUtNzUgMjguMTI1LTQxLjQyNSAwLTc1LTEyLjYtNzUtMjguMTI1di0yMy4zNWMxMi45MTIgMTMuMzA2IDQ0LjA2MiAyMC4yMjUgNzUgMjAuMjI1czYyLjA4OC02LjkyIDc1LTIwLjIyNXYyMy4zNXpNMTk1IDE0MmgtLjAyNXMuMDI1LjA3LjAyNS4xM2MwIDE1LjQzMi0zMy41OCAyNy45LTc1IDI3LjlzLTc1LTEyLjQ1Mi03NS0yNy44ODNjMC0uMDYyLjAyNS0uMTQ3LjAyNS0uMTQ3SDQ1di0yMy40NzVjMTIuOTEyIDEzLjMwNiA0NC4wNjIgMjAuMjI1IDc1IDIwLjIyNXM2Mi4wODgtNi45MiA3NS0yMC4yMjVWMTQyem0wLTM4aC0uMDI1cy4wMjUuMzIuMDI1LjM4YzAgMTUuNDMyLTMzLjU4IDI4LjAyNi03NSAyOC4wMjZzLTc1LTEyLjY0LTc1LTI4LjA3MmMwLS4wNjIuMDI1LS4zMzQuMDI1LS4zMzRINDVWODIuOWMxNi4zOCAxMi40OCA0Ni40MDYgMTguMzUgNzUgMTguMzVzNTguNjItNS44NyA3NS0xOC4zNVYxMDR6bS03NS0xNS4yNWMtNDEuNDI1IDAtNzUtMTIuNi03NS0yOC4xMjVDNDUgNDUuMDg3IDc4LjU3NSAzMi41IDEyMCAzMi41YzQxLjQyIDAgNzUgMTIuNTg3IDc1IDI4LjEyNSAwIDE1LjUyNS0zMy41OCAyOC4xMjUtNzUgMjguMTI1eiIvPjwvc3ZnPg==" pointer-events="none"/></g></svg> \ No newline at end of file diff --git a/images/akka-ddd/View_Update_Service.svg b/images/akka-ddd/View_Update_Service.svg new file mode 100644 index 0000000..0fc1616 --- /dev/null +++ b/images/akka-ddd/View_Update_Service.svg @@ -0,0 +1,3 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> +<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="654px" height="637px" version="1.1" style="background-color: rgb(255, 255, 255);"><defs><linearGradient x1="0%" y1="100%" x2="0%" y2="0%" id="mx-gradient-7ea6e0-1-dae8fc-1-s-0"><stop offset="0%" style="stop-color:#DAE8FC"/><stop offset="100%" style="stop-color:#7EA6E0"/></linearGradient></defs><g transform="translate(0.5,0.5)"><path d="M 531 155 C 531 143 591 143 591 155 L 591 207 C 591 219 531 219 531 207 Z" fill="#ffffff" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 531 155 C 531 164 591 164 591 155 M 531 159.5 C 531 168.5 591 168.5 591 159.5 M 531 164 C 531 173 591 173 591 164" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(531,178)"><switch><foreignObject pointer-events="all" width="59" height="30" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 57px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Event Store</div></div></foreignObject><text x="30" y="21" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><g transform="translate(327,468)"><switch><foreignObject pointer-events="all" width="86" height="38" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 43px; max-width: 86px; width: 86px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">updates ViewMetadata (lastEventNr)</div></div></foreignObject><text x="43" y="24" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 342.33 428.83 L 458.05 516.65" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 451.25 515.88 L 458.94 517.32 L 455.48 510.3" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><ellipse cx="342" cy="186" rx="40" ry="40" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(301,173)"><switch><foreignObject pointer-events="all" width="81" height="30" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 81px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">View Update<div>Service</div></div></div></foreignObject><text x="41" y="21" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 342.07 233.71 L 342.33 264.67 L 340.67 264.67 L 340.95 297.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 342.01 226.71 L 345.54 230.18 L 342.07 233.71 L 338.54 230.24 Z" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 340.99 302.88 L 337.43 295.91 L 340.95 297.63 L 344.43 295.85 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(283,246)"><switch><foreignObject pointer-events="all" width="124" height="30" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">runs VU event streams<br />(one per VUC)</div></div></foreignObject><text x="62" y="21" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><g transform="translate(12,504)"><switch><foreignObject pointer-events="all" width="205" height="130" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 130px; max-width: 205px; width: 205px; white-space: normal;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><h1>Resilience</h1><p>* VU Service is restarted whenever any VU event stream completes with error</p><p>* VU Service takes care of postponing start of VU event streams until ES and VS are available</p></div></div></foreignObject><text x="103" y="70" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 342 71 L 342 139.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 342 144.88 L 338.5 137.88 L 342 139.63 L 345.5 137.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(299,107)"><switch><foreignObject pointer-events="all" width="85" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">creates &amp; starts</div></div></foreignObject><text x="43" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><rect x="272" y="1" width="120" height="60" rx="9" ry="9" fill="#ffffff" stroke="#000000" pointer-events="none"/><rect x="282" y="11" width="120" height="60" rx="9" ry="9" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(306,28)"><switch><foreignObject pointer-events="all" width="71" height="30" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 71px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Read-Back<div>application</div></div></div></foreignObject><text x="36" y="21" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 420 528 C 420 514.67 499 514.67 499 528 L 499 588 C 499 601.33 420 601.33 420 588 Z" fill="#ffffff" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 420 528 C 420 538 499 538 499 528 M 420 533 C 420 543 499 543 499 533 M 420 538 C 420 548 499 548 499 538" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(439,557)"><switch><foreignObject pointer-events="all" width="40" height="30" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 40px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">View<div>Store</div></div></div></foreignObject><text x="20" y="21" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><rect x="289" y="399" width="106" height="30" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(301,408)"><switch><foreignObject pointer-events="all" width="81" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 81px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">ViewHandler</div></div></foreignObject><text x="41" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 340.84 331.54 L 342.19 392.47" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 340.68 324.54 L 344.26 327.96 L 340.84 331.54 L 337.26 328.12 Z" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 342.31 397.72 L 338.65 390.8 L 342.19 392.47 L 345.65 390.64 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(294,361)"><switch><foreignObject pointer-events="all" width="100" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">&lt;processing step&gt;</div></div></foreignObject><text x="50" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><rect x="536" y="399" width="106" height="30" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(556,408)"><switch><foreignObject pointer-events="all" width="65" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 65px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Projection</div></div></foreignObject><text x="33" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 395 414 L 529.63 414" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 534.88 414 L 527.88 417.5 L 529.63 414 L 527.88 410.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(414,407)"><switch><foreignObject pointer-events="all" width="105" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">executes 1 or more</div></div></foreignObject><text x="53" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 572.33 438.83 L 465.04 514.34" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 460.75 517.36 L 464.46 510.47 L 465.04 514.34 L 468.49 516.19 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(485,471)"><switch><foreignObject pointer-events="all" width="74" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">updates View</div></div></foreignObject><text x="37" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><rect x="1" y="146" width="170" height="80" fill="#ffffff" stroke="#000000" pointer-events="none"/><path d="M 1 172 L 1 146 L 171 146 L 171 172 Z" fill="#ffffff" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(41,154)"><switch><foreignObject pointer-events="all" width="90" height="14" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; font-weight: bold; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">ViewUpdateConfig</div></div></foreignObject><text x="45" y="12" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica" font-weight="bold">[Not supported by viewer]</text></switch></g><g transform="translate(7,179)"><switch><foreignObject pointer-events="all" width="132" height="38" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 40px; max-width: 158px; width: 132px; white-space: normal;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">+ viewName: String<div>+ officeInfo: OfficeInfo</div><div>+ projections: Seq[Projection]</div></div></div></foreignObject><text x="66" y="24" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 1 220 L 171 220" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 302 185.41 L 177.03 183.12" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 171.78 183.02 L 178.85 179.65 L 177.03 183.12 L 178.72 186.65 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(193,178)"><switch><foreignObject pointer-events="all" width="95" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">1 or more configs</div></div></foreignObject><text x="48" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><rect x="546" y="409" width="106" height="30" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(566,418)"><switch><foreignObject pointer-events="all" width="65" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 65px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Projection</div></div></foreignObject><text x="33" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 403.37 313.99 L 560.67 313.83 L 560.67 216.33" fill="none" stroke="#000000" stroke-miterlimit="10" stroke-dasharray="3 3" pointer-events="none"/><path d="M 398.12 314 L 405.11 310.49 L 403.37 313.99 L 405.12 317.49 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(544,293)"><switch><foreignObject pointer-events="all" width="40" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">Source</div></div></foreignObject><text x="20" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 274.83 313.83 L 227.33 313.83 L 227.33 214.67 L 307.63 214.67" fill="none" stroke="#000000" stroke-miterlimit="10" stroke-dasharray="3 3" pointer-events="none"/><path d="M 312.88 214.67 L 305.88 218.17 L 307.63 214.67 L 305.88 211.17 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(207,265)"><switch><foreignObject pointer-events="all" width="39" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">Failure</div></div></foreignObject><text x="20" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 275.14 305.49 C 275.6 304.6 277.14 304 278.86 304.03 L 386.83 304.03 L 398 314.28 L 386.83 324 L 278.61 324 C 277.58 323.97 276.61 323.71 275.95 323.28 C 275.29 322.85 275 322.3 275.14 321.75 Z M 277.62 321.55 C 277.91 322.23 279.05 322.7 280.35 322.68 L 385.71 322.68 L 395.52 314.28 L 385.71 305.29 L 280.35 305.29 C 279.22 305.22 278.13 305.54 277.62 306.08 Z M 281.34 308.73 C 281.44 308.12 282.32 307.63 283.45 307.54 L 311 307.54 C 312.14 307.63 313.01 308.12 313.11 308.73 L 313.11 319.57 C 312.8 320.1 311.91 320.47 310.88 320.5 L 283.7 320.5 C 282.67 320.47 281.78 320.1 281.47 319.57 Z M 284.69 311.24 L 284.69 318.91 L 310.01 318.91 L 310.01 311.11 L 298.34 315.8 C 297.52 316.09 296.44 316.09 295.61 315.8 Z M 297.1 314.35 L 309.51 309.19 L 284.82 309.19 Z M 316.59 308.73 C 316.64 308.18 317.34 307.7 318.32 307.54 L 346.25 307.54 C 347.24 307.7 347.93 308.18 347.99 308.73 L 347.99 319.57 C 347.75 320.02 347.09 320.37 346.25 320.5 L 318.32 320.5 C 317.48 320.37 316.82 320.02 316.59 319.57 Z M 319.69 311.17 L 319.69 318.91 L 345.01 318.91 L 344.88 311.17 L 333.47 315.8 C 332.58 316.15 331.37 316.15 330.49 315.8 Z M 332.1 314.35 L 344.64 309.19 L 319.69 309.19 Z M 351.58 308.73 C 351.69 308.12 352.56 307.63 353.69 307.54 L 381.12 307.54 C 382.26 307.63 383.13 308.12 383.23 308.73 L 383.23 319.31 C 383.17 319.66 382.85 319.98 382.33 320.2 C 381.82 320.43 381.16 320.53 380.5 320.5 L 353.69 320.5 C 352.71 320.44 351.88 320.08 351.58 319.57 Z M 354.56 311.17 L 354.56 318.91 L 379.88 318.91 L 379.88 311.17 L 368.21 315.8 C 367.45 316.04 366.5 316.04 365.73 315.8 Z M 367.1 314.35 L 379.51 309.19 L 354.69 309.19 Z" fill="url(#mx-gradient-7ea6e0-1-dae8fc-1-s-0)" stroke="#6c8ebf" stroke-miterlimit="10" transform="translate(336.5,0)scale(-1,1)translate(-336.5,0)" pointer-events="none"/></g></svg> \ No newline at end of file
pawelkaczor/pawelkaczor.github.com
0e4887558b2ef331b0652bac84405f9caf599b91
add Saga.svg
diff --git a/images/akka-ddd/Saga.svg b/images/akka-ddd/Saga.svg new file mode 100644 index 0000000..09d821d --- /dev/null +++ b/images/akka-ddd/Saga.svg @@ -0,0 +1,3 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> +<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="798px" height="619px" version="1.1" style="background-color: rgb(255, 255, 255);"><defs/><g transform="translate(0.5,0.5)"><ellipse cx="140" cy="340" rx="40" ry="39.5" fill="#ffffff" stroke="#000000" stroke-width="2" pointer-events="none"/><path d="M 408 20 C 408 9.33 468 9.33 468 20 L 468 64 C 468 74.67 408 74.67 408 64 Z" fill="#ffffff" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 408 20 C 408 28 468 28 468 20 M 408 24 C 408 32 468 32 468 24 M 408 28 C 408 36 468 36 468 28" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(408,38)"><switch><foreignObject pointer-events="all" width="59" height="30" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 57px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Event Store</div></div></foreignObject><text x="30" y="21" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 407.56 106.12 C 407.77 105.45 408.46 105 409.23 105.02 L 457.51 105.02 L 462.5 112.71 L 457.51 120 L 409.11 120 C 408.65 119.98 408.22 119.78 407.93 119.46 C 407.63 119.14 407.5 118.72 407.56 118.31 Z M 408.67 118.17 C 408.8 118.67 409.31 119.02 409.89 119.01 L 457.01 119.01 L 461.39 112.71 L 457.01 105.97 L 409.89 105.97 C 409.39 105.92 408.9 106.16 408.67 106.56 Z M 410.34 108.55 C 410.38 108.09 410.77 107.72 411.28 107.65 L 423.6 107.65 C 424.11 107.72 424.5 108.09 424.54 108.55 L 424.54 116.68 C 424.4 117.07 424.01 117.35 423.54 117.37 L 411.39 117.37 C 410.93 117.35 410.53 117.07 410.39 116.68 Z M 411.83 110.43 L 411.83 116.18 L 423.15 116.18 L 423.15 110.33 L 417.94 113.85 C 417.57 114.07 417.09 114.07 416.72 113.85 Z M 417.38 112.76 L 422.93 108.89 L 411.89 108.89 Z M 426.1 108.55 C 426.12 108.13 426.43 107.78 426.87 107.65 L 439.36 107.65 C 439.8 107.78 440.11 108.13 440.14 108.55 L 440.14 116.68 C 440.03 117.02 439.74 117.28 439.36 117.37 L 426.87 117.37 C 426.49 117.28 426.2 117.02 426.1 116.68 Z M 427.48 110.38 L 427.48 116.18 L 438.8 116.18 L 438.75 110.38 L 433.64 113.85 C 433.25 114.12 432.71 114.12 432.31 113.85 Z M 433.03 112.76 L 438.64 108.89 L 427.48 108.89 Z M 441.75 108.55 C 441.79 108.09 442.18 107.72 442.69 107.65 L 454.95 107.65 C 455.46 107.72 455.85 108.09 455.9 108.55 L 455.9 116.48 C 455.87 116.74 455.72 116.99 455.49 117.15 C 455.26 117.32 454.97 117.4 454.68 117.37 L 442.69 117.37 C 442.25 117.33 441.88 117.06 441.75 116.68 Z M 443.08 110.38 L 443.08 116.18 L 454.4 116.18 L 454.4 110.38 L 449.18 113.85 C 448.84 114.03 448.41 114.03 448.07 113.85 Z M 448.68 112.76 L 454.23 108.89 L 443.13 108.89 Z" fill="#00bef2" stroke="none" pointer-events="none"/><g transform="translate(406,127)"><switch><foreignObject pointer-events="all" width="58" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><div>BP stream</div></div></div></foreignObject><text x="29" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 437.52 72 L 437.1 97.8" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 437.02 103.05 L 433.63 95.99 L 437.1 97.8 L 440.63 96.11 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><ellipse cx="435" cy="216" rx="39.5" ry="39.5" fill="#ffffff" stroke="#000000" stroke-width="2" pointer-events="none"/><g transform="translate(396,195)"><switch><foreignObject pointer-events="all" width="77" height="44" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 75px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Saga Manager<div>[Receptor]</div></div></div></foreignObject><text x="39" y="28" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 435.33 169.47 L 435.33 120" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 435.33 174.72 L 431.83 167.72 L 435.33 169.47 L 438.83 167.72 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 193.4 215.83 L 395.33 215.83" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 199.28 212.33 L 192.28 215.83 L 199.28 219.33" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(282,210)"><switch><foreignObject pointer-events="all" width="33" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">Event</div></div></foreignObject><text x="17" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><ellipse cx="151" cy="216" rx="40" ry="40" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(113,210)"><switch><foreignObject pointer-events="all" width="75" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 75px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Saga Office</div></div></foreignObject><text x="38" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 151 256 L 151.17 284.17 L 151.17 305.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 151.17 310.88 L 147.67 303.88 L 151.17 305.63 L 154.67 303.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(135,270)"><switch><foreignObject pointer-events="all" width="33" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">Event</div></div></foreignObject><text x="17" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><g transform="translate(213,381)"><switch><foreignObject pointer-events="all" width="577" height="187" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 235px; max-width: 577px; width: 577px; white-space: normal;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><h1>Saga</h1><p>Saga instance (Saga) represents particular business process instance (e.g. User Registration Process for user X). </p><p>Saga is persistent, event-sourced actor. State transition of the process is communicated by Saga by an event (like UserEmailConfirmed). Transitions are triggered by external events that Saga receives. </p><p>Saga is created or activated automatically by Saga Office whenever external event related (correlated) to this instance of business process is received by Saga Office.</p><p><span style="font-size: 10px ; line-height: 1.26">Sends commands to offices (at-least-once delivery).</span></p><p><span style="font-size: 10px ; line-height: 1.26">Schedules timeout/deadline events. </span><br /></p></div></div></foreignObject><text x="289" y="99" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><ellipse cx="151" cy="352" rx="39.5" ry="39.5" fill="#ffffff" stroke="#000000" stroke-width="2" pointer-events="none"/><g transform="translate(122,338)"><switch><foreignObject pointer-events="all" width="57" height="30" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 57px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Saga<div>Instance</div></div></div></foreignObject><text x="29" y="21" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><ellipse cx="151" cy="43" rx="39.5" ry="39.5" fill="#ffffff" stroke="#000000" stroke-width="2" pointer-events="none"/><g transform="translate(129,36)"><switch><foreignObject pointer-events="all" width="43" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 43px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Office</div></div></foreignObject><text x="22" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><g transform="translate(499,126)"><switch><foreignObject pointer-events="all" width="291" height="199" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 290px; max-width: 291px; width: 291px; white-space: normal;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><h1>Saga Manager</h1><p>Responsible for reliable delivery of events to Saga Office.</p><p>Receives events from defined BPS.</p><p>Obtains correlationId resolver - function that maps an event to saga id (eg. UserCreated(userId: EntityId, ...) =&gt; userId) from SagaConfig.</p><p><span style="font-size: 10px ; line-height: 1.26">Forwards incoming events to Saga Office.</span></p><p>Is cluster-wide singleton automatically created when Saga class is registered (see: SagaSupport)</p></div></div></foreignObject><text x="146" y="105" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><g transform="translate(213,274)"><switch><foreignObject pointer-events="all" width="207" height="87" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 100px; max-width: 207px; width: 207px; white-space: normal;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><h1>Saga Office</h1><p>Standard Office that is automatically created for Saga class (See: SagaSupport)</p></div></div></foreignObject><text x="104" y="49" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><g transform="translate(500,0)"><switch><foreignObject pointer-events="all" width="290" height="123" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 10px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 134px; max-width: 290px; width: 290px; white-space: normal;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><h1>Business Process Stream (BPS)</h1><p>Stream of events particular business process (eg. User Registration) <span style="line-height: 1.26">is interested in. The stream is fed by projections that listen to events coming from one or more business offices.</span></p></div></div></foreignObject><text x="145" y="67" fill="#000000" text-anchor="middle" font-size="10px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 172 134.17 L 290.33 134.17 L 290.33 41.67 L 401.47 41.67" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 406.72 41.67 L 399.72 45.17 L 401.47 41.67 L 399.72 38.17 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(274,99)"><switch><foreignObject pointer-events="all" width="33" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">Event</div></div></foreignObject><text x="17" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 111.17 351.67 L 25.33 351.67 L 25.33 42.5 L 104.8 42.5" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 110.05 42.5 L 103.05 46 L 104.8 42.5 L 103.05 39 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(0,179)"><switch><foreignObject pointer-events="all" width="57" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">Command</div></div></foreignObject><text x="29" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><ellipse cx="141" cy="124" rx="21" ry="21" fill="#ffffff" stroke="#000000" pointer-events="none"/><ellipse cx="151" cy="134" rx="21" ry="21" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(136,128)"><switch><foreignObject pointer-events="all" width="29" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 29px; white-space: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">AR</div></div></foreignObject><text x="15" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 151.17 81.67 L 151.17 106.97" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 151.17 112.22 L 147.67 105.22 L 151.17 106.97 L 154.67 105.22 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(122,88)"><switch><foreignObject pointer-events="all" width="57" height="16" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">Command</div></div></foreignObject><text x="29" y="14" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g></g></svg> \ No newline at end of file
pawelkaczor/pawelkaczor.github.com
ff1fc4b7777a6a734650b4a42d1139b58496db70
switch to newicom.pl
diff --git a/about.markdown b/about.markdown index 426d7e3..2fc44c4 100644 --- a/about.markdown +++ b/about.markdown @@ -1,25 +1,25 @@ --- layout: post title: O mnie hide_meta: true --- <p> <br /> <img src="/images/pawel_kaczor.png" alt="foto" class="foto"/> </p> Od wielu lat pracuję jako programista, projektant, konsultant IT. Pasjonuję się poznawaniem nowoczesnych technologii tworzenia oprogramowania. Obecnie jestem właścicielem firmy **NEWICOM**, sciśle współpracując z firmą <a href="http://www.consileon.pl">Consileon Polska</a>. W swojej pracy wykorzystuję doświadczenie zebrane w ciągu lat pracy na komercyjnych projektach w technologiach **Jave EE, Scala** <h2 style="padding-top:2em;" class="green">Kontakt:</h2> <p> <br /> tel: <strong>+48v505v172v876</strong>, email: <a href="mailto:[email protected]"><strong>[email protected]</strong></a> </p> -<h2 style="padding-top:2em;" class="green">O pawelkaczor.com</h2> +<h2 style="padding-top:2em;" class="green">O newicom.pl</h2> Ta strona została zbudowana z użyciem [jekyll](http://github.com/mojombo/jekyll/tree/master), 'blog-aware, static site generator', w pełni wykorzystując możliwości [![GitHub Pages](images/logo_pages.png)](http://pages.github.com/)
pawelkaczor/pawelkaczor.github.com
2d32853bee9fba021e863bd6fc4922984c6f1c24
switch to newicom.pl
diff --git a/_includes/post-div.html b/_includes/post-div.html index b1a8f02..875c563 100644 --- a/_includes/post-div.html +++ b/_includes/post-div.html @@ -1,12 +1,12 @@ {% if page.post-type %}<div class="{{ page.post-type }}">{% else %}<div class="post">{% endif %} <div class="content"> <h2 class="title"><a href="{{ page.url }}">{{ page.title }}</a></h2> {{ body }} </div>{% unless page.hide_meta %} <div class="meta"> - <span class="author"><a href="http://pawelkaczor.com">Pawel Kaczor</a></span> &middot; + <span class="author"><a href="http://newicom.pl">Pawel Kaczor</a></span> &middot; <span class="date"><a href="/{{ page.date | date: "%Y" }}/{{ page.date | date: "%m" }}">{{ page.date | date: "%e" | ordinalize }} {{ page.date | date: "%B"}} {{ page.date | date: "%Y"}}</a></span> <span class="tags">{% for tag in page.categories %} &middot; <a href="/{{tag}}.html" rel="tag">{{tag}}</a>{% endfor %}</span> <span class="tags">&middot; <a href="{{ page.url }}/#disqus_thread" rel="tag">Komentuj</a></span> </div>{% endunless %} </div>
pawelkaczor/pawelkaczor.github.com
36608413fed6223ce6d79c701d36af7491431403
switch to newicom.pl
diff --git a/_layouts/default.html b/_layouts/default.html index d190da3..7c5c55d 100644 --- a/_layouts/default.html +++ b/_layouts/default.html @@ -1,49 +1,49 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> - <title>{{ page.title }} &middot; pawelkaczor.com</title>{% if page.description %} + <title>{{ page.title }} &middot; newicom.pl</title>{% if page.description %} <meta name="description" content="{{ page.description }}"/>{% endif %}{% if page.robots %} <meta name="robots" content="{{ page.robots }}"/>{% endif %} <meta name="verify-v1" content="" /> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="chrome=1" /> <link rel="stylesheet" href="/css/style.css" type="text/css" /> <link rel="stylesheet" href="/css/syntax.css" type="text/css" /> - <link rel="alternate" type="application/atom+xml" href="http://pawelkaczor.com/atom.xml" /> - <link rel="canonical" href="http://pawelkaczor.com{{ page.url }}"/> + <link rel="alternate" type="application/atom+xml" href="http://newicom.pl/atom.xml" /> + <link rel="canonical" href="http://newicom.pl{{ page.url }}"/> <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> <meta name="viewport" content="width=850" /> <meta name="description" content="Paweł Kaczor - Blog o programowaniu." /> <meta name="keywords" content="Paweł Kaczor, Pawel Kaczor, Scala, Programowanie, DevBlog, Consulting" /> <script src="/js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> <script src="/js/loopedslider.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div id="container"> <div id="header" class="menubar"> {% include menubar.html %} </div> <div id="main"> {{ content }} </div> </div> {% unless page.hide_analytics %}{% include google-analytics.html %}{% endunless %} <script type="text/javascript"> //<![CDATA[ (function() { var links = document.getElementsByTagName('a'); var query = '?'; for(var i = 0; i < links.length; i++) { if(links[i].href.indexOf('#disqus_thread') >= 0) { query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&'; } } document.write('<script charset="utf-8" type="text/javascript" src="http://disqus.com/forums/Newion/get_num_replies.js' + query + '"></' + 'script>'); })(); //]]> </script> </body> </html>
pawelkaczor/pawelkaczor.github.com
607b61dbc34a23de0cff015a9124442ceaf687f5
cleanup done, ready to go
diff --git a/_includes/google-analytics.html b/_includes/google-analytics.html new file mode 100644 index 0000000..7dde4bf --- /dev/null +++ b/_includes/google-analytics.html @@ -0,0 +1,13 @@ +<script type="text/javascript"> + + var _gaq = _gaq || []; + _gaq.push(['_setAccount', 'UA-19004267-1']); + _gaq.push(['_trackPageview']); + + (function() { + var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; + ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; + var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); + })(); + +</script> diff --git a/_includes/menubar.html b/_includes/menubar.html new file mode 100644 index 0000000..ddca0a6 --- /dev/null +++ b/_includes/menubar.html @@ -0,0 +1,11 @@ +<a href="/">home</a> +&middot; <a href="/about.html">o mnie</a> +&middot; <a href="/portfolio.html">portfolio</a> +&middot; <a href="http://github.com/pawelkaczor">na github</a> +&middot; <a href="http://pl.linkedin.com/in/Newicom">na linkedin</a> +&middot; <a href="http://twitter.com/Newion">na twitter</a> +<br /><br /> +<a class="name" href="/"><span>Newion</span></a> +<br /> +Jeśli jeszcze nie zwariowałeś to znaczy, że jesteś niedoinformowany! + diff --git a/_posts/2010-09-07-dostrajanie-orm.markdown b/_posts/2010-09-07-dostrajanie-orm.markdown deleted file mode 100644 index 36e37b2..0000000 --- a/_posts/2010-09-07-dostrajanie-orm.markdown +++ /dev/null @@ -1,204 +0,0 @@ ---- -layout: post -title: Dostrajanie warstwy ORM w projekcie wielomodułowym -categories: [orm] ---- -Częstym jak sądzę przypadkiem w średnich i większych projektach informatycznych jest współdzielenie modelu domeny przez kilka niezależnych aplikacji. -Takimi aplikacjami mogą być np.: web portal dla klientów, wewnętrzna aplikacja administracyjna, moduł raportujący. - -Wspólne dane, z których korzystają aplikacje, nie są wcale powodem do tworzenia wspólnego modelu domeny. Polecam na ten temat prezentację [DDD - putting model to work](http://www.infoq.com/presentations/model-to-work-evans), której którkie podsumowanie można znaleźć tutaj: [IT-Researches Blog](http://it-researches.blogspot.com/2009/03/eric-evans-ddd-putting-model-to-work.html). - -Zakładając jednak, że mamy jeden model (co jest częstą praktyką) pojawia się kwestia współdzielenia modelu ORM zdefiniowanego -jako mapowania obiektów do tabel w bazie relacyjnej. -Jak się bowiem często okazuje wymagania poszczególnych aplikacji w tym zakresie są różne. -Dotyczyć to może takich kwestii jak sposób inicjalizacji pól encji (lazy vs egear fetching). - -Zagadnienie, jakie dokładnie ustawienia ORM warto dostrajać i kiedy, odłożę na później. -W tym wpisie chciałbym przedstawić w jaki sposób skonfigurować projekt aby umożliwić poszczególnym aplikacjom dostosowanie warstwy ORM do ich potrzeb oraz jakie problemy -przy tworzeniu takiej konfiguracji napotkałem. - -## Konfiguracja projektu -Wykorzystywane technologie: - - - Maven - - Spring - - Hibernate - -Mamy zatem projekt wielomodułowy, w skład którego wchodzą poszczególne aplikacje oraz następujące moduły współdzielone: - - - model domeny - (encje/domain objects) - - dao - konfiguracja dostępu do bazy danych, klasy dao - - -### Moduł - model domeny - -Model domeny stanowią encje (obiekty POJO) opisane adnotacjami Hiberanate Annotations. -Adnotacje są dobrym sposobem na zdefiniowanie domyślnych mapowań ORM. Poszczególne aplikacje mają bowiem możliwość nadpisania domyślnych mapowań przy użyciu plików konfiguracyjnych xml (hbm.xml). Zwracam uwagę na to, że Hibernate Annotations bazują na specyfikacji **JPA** jednak nie wymagają użycia modułu JPA (dostarczającego interfejs javax.persistence.EntityManager). - -### Moduł - dao - -Konfigurację SessionFactory tworzymy wykorzystując Spring-ową fabrykę wspierającą Hibernate Annotations. -{% highlight xml %} - <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" - p:dataSource-ref="dataSource"> - <property name="annotatedClasses"> - <list> - <value>com.example.domain.FeedCategory</value> - [...] - </list> - </property> - <property name="mappingDirectoryLocations"> - <list> - <value>classpath:orm/custom-mappings/</value> - </list> - </property> - [...] - </bean> -{% endhighlight %} -W parametrze ``annotatedClasses`` podajemy listę naszych encji. Co warte uwagi Spring umożliwia wskazanie pakietu który będzie automatycznie skanowany w poszukiwaniu encji (parametr ``packagesToScan``). - -Nas jednak bardziej interesuje parametr ``mappingDirectoryLocations``. Wskażemy w nim katalog, z którego załadowane zostaną pliki ``hbm.xml``. -W ten sposób umożliwiamy aplikacjom dostarczenie własnych mapowań ORM. - -## Przykład -Uporawszy się z konfiguracją, przetestujmy jak działa nadpisywanie mapowań na konkretnym przykładzie. - -Mamy zatem klasę **FeedCategory**, która dziedziczy po **BaseEntity** i zawiera listę podkategorii (pole ``subCategories``). - -{% highlight java %} - -@MappedSuperclass -public abstract class BaseEntity { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "ID") - private Long id; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "CREATED_DATE") - private Date createdDate; - - [...] -} - -@Entity -public class FeedCategory extends BaseEntity { - [...] - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "PARENT_ID") - private FeedCategory parent; - - @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.ALL) - private List<FeedCategory> subCategories = new ArrayList<FeedCategory>(); - [...] -} - -{% endhighlight %} - -Jak widzimy, domyślnie Hibernate załaduje listę podkategorii leniwie (w momencie użycia) co zostało zdefiniowane ustawieniem ``fetch = FetchType.LAZY``. -Załóżmy jednak, że chcemy aby w naszej aplikacji podkategorie były ładowane "chciwie" (ang. eagerly) a więc zaraz po załadowaniu obiektu głównego. - -W tym celu tworzymy w module konkretnej aplikacji katalog __orm/custom-mappings__, który wskazaliśmy w konfiguracji SessionFactory (w projekcie maven-owym umieszczamy ten katalog w gałęzi src/main/resources) i umieszczamy w nim plik feedCategory.hbm.xml: - -{% highlight xml %} - -<hibernate-mapping package="com.example"> - <class name="FeedCategory"> - <id name="id" /> - <property name="createdDate" column="CREATED_DATE" type="date"/> - [...] - <bag name="subCategories" inverse="true" lazy="false"> - <key column="PARENT_ID" /> - <one-to-many entity-name="com.example.FeedCategory"/> - </bag> - </class> -</hibernate-mapping> - -{% endhighlight %} - -Tym razem ustawienie sposobu pobierania listy kategorii definiujemy atrybutem **lazy="false"** (czyli chciwie). - -## Problem -Napotykamy problem, który wydawało się nie powinien zaistnieć. Mianowicie adnotacja **@MappedSuperclass** nie ma odpowiednika w konfiguracji mapowań Hibernate. - -Obejściem tego problemu jest zdefiniowanie pól z klasy BaseEntity w pliku mapowań klasy FeedCategory. Jednak jest to niewygodne. Wyobraźmy sobie bowiem, że nadpisujemy 10 klas po czym dokonujemy zmiany w domyślnej konfiguracji BaseEntity... Będziemy musieli tę zmianę wprowadzić również w 10 plikach hbm.xml.. -Drugim problemem (który być może wynika z pierwszego - temat nie do końca sprawdzony) jest konieczność zdefiniowania wszystkich pól klasy FeedCategory. -Nie można zatem nadpisać tylko zmienionego elementu konfiguracji, trzeba zdefiniować całe mapowanie na nowo. - -##Rozwiązanie -Rozwiązaniem powyższych niedogodności jest skonfigurowanie Hibernate jako dostawcy JPA i zastąpienie mapowań w formacie hbm.xml mapowaniami xml w standarcie JPA. - -W tym celu konfigurację SessionFactory zastępujemy konfiguracją EntityManagerFactory ponownie korzystając z udogodnień jakie oferuje Spring, tym razem dla JPA: - -{% highlight xml %} - <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" - p:persistence-xml-location="classpath:META-INF/persistence.xml" p:data-source-ref="dataSource"> - [...] - <property name="persistenceUnitPostProcessors"> - <list> - <bean class="com.example.spring.jpa.DefaultPostprocessor" /> - </list> - </property> - </bean> -{% endhighlight %} - -Szczegółowe ustawienia dostarczamy w pliku **persistence.xml**, w którym również specyfikujemy listę naszych encji -(ustawiając parametr ``hibernate.archive.autodetection`` nakazujemy Hibernate Entity Manager aby wyszukał encje w określonych lokalizacjach, -więcej informacji na ten temat tutaj: [Do I need class elements in persistence.xml](http://stackoverflow.com/questions/1780341/do-i-need-class-elements-in-persistence-xml)): - -{% highlight xml %} -<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" [...]> - <persistence-unit> - <class>com.example.domain.FeedCategory</class> - [...] - </persistence-unit> -</persistence> -{% endhighlight %} - -Pozostaje skonfigurować wykrywanie mapowań xml dostarczonych przez poszczególne aplikacje. -Niestety w przypadku JPA nie mamy analogicznego do ``mappingDirectoryLocations`` parametru zarówno na poziomie konfiguracji w pliku persistence.xml jak i udogodnień Spring-a. -Rozwiązaniem jest przekazanie do LocalContainerEntityManagerFactoryBean klasy implementującej interfejs -``PersistenceUnitPostProcessor``. Postprocesor ma możliwość modyfikowanie opcji konfiguracyjnych, w tym dodanie mapowań xml. - -{% highlight java %} -public class DefaultPostprocessor implements PersistenceUnitPostProcessor, ResourceLoaderAware { - - private ResourceLoader resourceLoader; - - @Override - public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) { - Resource resource = resourceLoader.getResource("classpath:orm.xml"); - if (resource.exists()) { - pui.addMappingFileName("orm.xml"); - } - - } - - @Override - public void setResourceLoader(ResourceLoader resourceLoader) { - this.resourceLoader = resourceLoader; - } -} -{% endhighlight %} - -Możemy zatem w aplikacji nadpisać mapowania domyślne tworząc plik **orm.xml** (jest to standardowa nazwa pliku określona w specyfikacji JPA, aczkolwiek plików z mapowaniami może być wiele). -W naszym przykładzie plik orm.xml wygląda następująco: - -{% highlight xml %} - <entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm" [...]> - - <entity class="com.example.domain.FeedCategory"> - <attributes> - <one-to-many name="subCategories" target-entity="com.example.domain.FeedCategory" mapped-by="parent" fetch="LAZY"/> - </attributes> - </entity> - - </entity-mappings> -{% endhighlight %} - -Jak widać, ostatecznie udało się osiągnąć cel czyli nadpisać tylko to co wymagało dostosowania. -Niestety wymagało to zmiany konfiguracji projektu w celu integracji standardu JPA. - - -{% include bio_pawel_kaczor.html %} diff --git a/about.markdown b/about.markdown new file mode 100644 index 0000000..426d7e3 --- /dev/null +++ b/about.markdown @@ -0,0 +1,25 @@ +--- +layout: post +title: O mnie +hide_meta: true +--- +<p> +<br /> +<img src="/images/pawel_kaczor.png" alt="foto" class="foto"/> +</p> +Od wielu lat pracuję jako programista, projektant, konsultant IT. Pasjonuję się poznawaniem nowoczesnych technologii tworzenia oprogramowania. + +Obecnie jestem właścicielem firmy **NEWICOM**, sciśle współpracując z firmą <a href="http://www.consileon.pl">Consileon Polska</a>. W swojej pracy wykorzystuję doświadczenie zebrane w ciągu lat pracy na komercyjnych projektach w technologiach **Jave EE, Scala** + +<h2 style="padding-top:2em;" class="green">Kontakt:</h2> +<p> +<br /> +tel: <strong>+48v505v172v876</strong>, +email: <a href="mailto:[email protected]"><strong>[email protected]</strong></a> +</p> + + +<h2 style="padding-top:2em;" class="green">O pawelkaczor.com</h2> +Ta strona została zbudowana z użyciem [jekyll](http://github.com/mojombo/jekyll/tree/master), +'blog-aware, static site generator', w pełni wykorzystując możliwości [![GitHub Pages](images/logo_pages.png)](http://pages.github.com/) + diff --git a/css/iphone.css b/css/iphone.css deleted file mode 100644 index bd5e941..0000000 --- a/css/iphone.css +++ /dev/null @@ -1,5 +0,0 @@ -#container { - width: 810px; - margin-left: 20px; - margin-right: 20px; -} diff --git a/css/style.css b/css/style.css index 23e959e..1c28bd1 100644 --- a/css/style.css +++ b/css/style.css @@ -1,364 +1,285 @@ -body { - margin: 0; - padding: 0; - font: 18px "ff-dagny-web-pro-1","ff-dagny-web-pro-2",Palatino, georgia, "times new roman", serif; - line-height: 1.7em; - color: black; - background: white; -} - -.ruby:hover { - -webkit-transform: rotate(360deg); - -webkit-transition: all 1s ease-in-out; - -moz-transform: rotate(360deg); - -moz-transition: all 1s ease-in-out; -} - -#container { - width: 42em; - margin-left: auto; - margin-right: auto; -} - -.beta { - color:gray; - font-size:17px; - font-style:italic; - margin-left:-44px; - vertical-align:top; -} -.menubar { - color: #aaa; - line-height: 1.3em; - margin-top: 0; - padding-top: 0; +html { + overflow: auto; } -.menubar a { - color: #aaa; - text-decoration: none; -} - -.menubar a:hover { - color: #7CA300; -} - -#header { - padding-top: 0.3em; -} - -#footer { - margin-top: 3em; - padding-bottom: 0.3em; -} - -.name { - font-size: 2.5em; +body { + background: none repeat scroll 0 0 #ffffff; + color: #333333; + font: 14pt "ff-dagny-web-pro-1","ff-dagny-web-pro-2",Palatino, georgia, "times new roman", serif; + overflow: auto; } -h2 { - font-size: 1.8em; - font-family: "ff-tisa-web-pro-1","ff-tisa-web-pro-2",Palatino, georgia, "times new roman", serif; - font-weight: 100; - line-height: 1.2em; +h1 { border-bottom: 1px solid #ddd; - padding-bottom: 0.2em; - margin-bottom: -0.3em; - margin-top: 0; - padding-top: 1em; + padding-bottom: 0.4em; + font-size: 1.6em; + margin-bottom: 0.4em; + font-weight: normal; + line-height: 1.1em; } -h3 { +h2 { + font-weight: bold; + line-height: 1.3em; font-size: 1.3em; - font-weight: normal; + margin-bottom: 0.5em; } -h1 { - font-size: 2em; - font-weight: normal; - border-bottom: 1px solid #ddd; +h3 { + font-size: 1.1em; + font-weight: bold; + line-height: 1.3em; + margin-bottom: 0.25em; } -h1, .post, .link-post { - padding-bottom: 8px; - margin-bottom: 48px; +a { + color: #007f7f; + text-decoration: none; } - -.link-post h2 { - font-size: 1.4em; +p { + line-height: 1.55em; + margin-bottom: 1em; } -code { - font-family: Monaco, monospace; +a:hover { + text-decoration: underline; } -.highlight { - background: yellow; - margin-top: -0.3em; +ol, ul { + margin: 0 0 1em 2em; + list-style-position: outside; + list-style-type: disc; } -.osx-shortcut { - background: #f0f0f0; - color : #7CA300; - padding-left: 0.2em; - padding-right: 0.2em; - border: 1px solid #e0e0e0; - -moz-border-radius: 0.2em; - -webkit-border-radius: 0.2em; +table { + margin-bottom: 1em; + border-collapse: collapse; } -.meta { - font-family: "ff-tisa-web-pro-1","ff-tisa-web-pro-2",Palatino, georgia, "times new roman", serif; - font-size: 0.9em; - font-weight: bold; - color: #999; - border-top: 1px solid #ddd; - padding-top: 0.1em; - padding-bottom: 0.1em; - margin-top: -0.6em; +th { + font-weight: bold; + color: #007f7f; + border: 1px solid #c9c9c9; + text-align: center; + background-color: #e9e9e9; } -.meta a, .content a, .related a { - color: #7CA300; - text-decoration: none; - border-bottom: 1px dotted #d3dfee; +td { + border: 1px solid #c9c9c9; + padding: 2px 10px; } -.meta a { - font-weight: normal; - +#container { + margin: 0 auto; + padding: 10px 0; + width: 1020px; } -.meta a:hover, .content a:hover, .related a:hover { - border-bottom: 1px solid #7CA300; +#header { + margin: 20px 0 40px 0; + overflow: hidden; } -.title a { - color: #7CA300; +#header a { text-decoration: none; - border: none; - padding: 0; - margin: 0; - background: white; } -.title a:hover { +#header h1 { + font-size: 2.8em; + font-weight: bold; border: none; + margin: 0; + padding: 10px 0 0 240px; } -.andrzejsliwa { - color:#7CA300; - text-shadow:2px 2px 0 rgba(0, 0, 0, 0.15); +#header h2 { + margin: 0; + font-size: 1.4em; + padding-left: 240px; + margin-top: -5px; + font-weight: normal; } -.video { - padding-top: 0.5em; - padding-bottom: 0.5em; - padding-bottom: 0; - text-align: center; +#header h2 a { + color: #475258; } -pre { - font: 0.7em Monaco, monospace; - line-height: 1.4em; +#logo a { + margin-top: 5px; display: block; - color: white; - background: #0B2F20; - -moz-border-radius: 0.3em; - -webkit-border-radius: 0.3em; - padding: 0.6em; - white-space: pre-wrap; /* css-3 */ - white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */ - white-space: -pre-wrap; /* Opera 4-6 */ - white-space: -o-pre-wrap; /* Opera 7 */ - word-wrap: break-word; /* Internet Explorer 5.5+ */ -} - -.related { - color: #7CA300; - font-family: "ff-tisa-web-pro-1","ff-tisa-web-pro-2",Palatino, georgia, "times new roman", serif; - font-size: 0.9em; - line-height: 1.7em; -} - -.related h3 { - font-size: 1.2em; - border-bottom: 1px solid #ddd; - padding-bottom: 0; - margin-bottom: 0; + float: left; + width: 205px; + height: 100px; + background-image: url("/images/logo2.png"); + background-repeat: no-repeat; + background-position: 105px 0px; } -.related p { - margin-top: 0.4em; -} - -.content p { - margin-bottom: 1.3em; -} - -.onleft { - float : left; +#logo a:hover a { + -moz-transform: rotate(360deg); } -#rest { - float : right; - width : 600px; +#main { + overflow: hidden; } -#atom_link img { - border:medium none; +#content { + float: right; + margin-left: 25px; + padding: 0 15px; + width: 765px; } - -/* @group FancyFirst */ - .content h2 + p:first-letter { - font-size: 48px; - padding: 0 0.15em 0 0; - margin: 0.05em 0 -0.15em 0; - line-height: 1em; - float: left; +#sidebar { + float: right; + text-align: right; + width: 180px; } -.content h2 + p:first-line { - font-variant: small-caps; - font-size: larger; +#sidebar a { + font-weight: bold; } -/* @end */ -.green { - color: #7CA300; +#sidebar h3 { + font-weight: normal; + line-height: 1.5em; + margin-bottom: 0.2em; } -strong { - color: #7CA300; +#sidebar ul { + margin-bottom: 1.2em; + list-style-type: none; } -.foto { - padding:2px; - flow: left; - border:1px solid #7CA300; +#sidebar li { + margin-bottom: 0.2em; } -img { - border: 0px; +#sidebar li a:before { + content: "\00BB \0020"; } -.post img.example { - width: 43em; +#footer { + margin: 0 auto; + text-align: center; + padding-bottom: 2.5em; } - - -#loopedSlider { - margin:0 auto; - padding:40px 0; - width:740px; +#footer ul { + list-style: none; } -#loopedSlider .nav-buttons { - list-style-type:none; - margin:0; - padding:0; - position:relative; +#footer li { + border-right-color: #c8c8c8; + border-right-style: solid; + border-right-width: 1px; + display: inline; + font-size: 0.8em; + line-height: 1em; + padding-bottom: 0; + padding-left: 4px; + padding-right: 4px; + padding-top: 0; } -ul, ol { - list-style-image:none; - list-style-position:outside; - list-style-type:none; - padding:10px 0; +#footer li:last-child { + border-right-style: none; } -.related ul, ol { - list-style-type: disc; - margin: 20px; - padding:10px 0; +.post-header { + color: #007F7F; } -#loopedSlider li#p { - left:0; - position:absolute; - top:300px; +.post-header h1 { + margin: 0 0 0.25em 0; } -#loopedSlider li#p1 { - left:0; - position:absolute; - top:800px; +.post-header h1 a { + text-decoration: none; } -li { - margin:0; - padding:0; +.post-header h2 { + margin-bottom: 0.75em; + font-weight: normal; + font-size: 1em; } -a { - color:#2882C1; +/* @group FancyFirst */ +.post-content h1 + p:first-letter { + font-size: 32pt; + padding: 0 0.15em 0 0; + margin: 0.05em 0 -0.15em 0; + line-height: 1em; + float: left; } -#portfolio a { - border:medium none; - text-decoration:none; +.post-content h1 + p:first-line { + font-variant: small-caps; + font-size: 1.1em; } +/* @end */ -#loopedSlider li#n { - position:absolute; - right:0; - top:300px; +.meta a { + font-size: 1.9em; + line-height: 1.3em; + margin-bottom: 1.4em; } -#loopedSlider li#n1 { - position:absolute; - right:0; - top:800px; +.meta { + margin-bottom: 2em; + border-top-color: #C9C9C9; + border-top-style: solid; + border-top-width: 1px; + border-bottom-color: #C9C9C9; + border-bottom-style: solid; + border-bottom-width: 1px; + background-color: #F1F1F1; + padding-top: 1em; + padding-bottom: 1em; + padding-left: 1em; } -a img { - border:medium none; +#entries { + margin-bottom: 3em; } -.container { - height:320px; - margin-left:50px; - overflow:hidden; - position:relative; - width:640px; +#entries ul { + list-style: none; + margin: 0 0 1em 0; } -.slides { - left:0; - position:absolute; - top:0; +.bio { + border-top: 1px solid #C9C9C9; + border-bottom: 1px solid #c9c9c9; + background-color: #F1F1F1; + padding: 20px; } -.slides div.slide { - display:none; - position:absolute; - top:0; - width:640px; +.foto { + float: left; + display: block; + padding: 5px; + padding-bottom: 2px; + background-color: white; + border-color: #C9C9C9; + border-style: solid; + border-width: 1px; } -#portfolio h2 { - color:#7CA300; - font-size:40px; - font-weight:normal; - letter-spacing:-1px; - line-height:40px; - padding:0 0 10px; - font-family:Georgia; - text-shadow:2px 2px 0 rgba(0, 0, 0, 0.15); +.desc { + float: none; + padding-left: 135px; } -#portfolio p { - color:#333333; - font-size:14px; - line-height:20px; +#desc p { + margin-left: 120px; } -#portfolio .alignright { - float:top; - margin:5px 0 8px 20px; +.post { + margin-bottom: 5em; } -.highlight + .highlight { display:none; } /* dirty fix for jekyll highlight bug */ +.full { + width: 750px; +} \ No newline at end of file diff --git a/css/style_oryg.css b/css/style_oryg.css new file mode 100644 index 0000000..23e959e --- /dev/null +++ b/css/style_oryg.css @@ -0,0 +1,364 @@ +body { + margin: 0; + padding: 0; + font: 18px "ff-dagny-web-pro-1","ff-dagny-web-pro-2",Palatino, georgia, "times new roman", serif; + line-height: 1.7em; + color: black; + background: white; +} + +.ruby:hover { + -webkit-transform: rotate(360deg); + -webkit-transition: all 1s ease-in-out; + -moz-transform: rotate(360deg); + -moz-transition: all 1s ease-in-out; +} + +#container { + width: 42em; + margin-left: auto; + margin-right: auto; +} + +.beta { + color:gray; + font-size:17px; + font-style:italic; + margin-left:-44px; + vertical-align:top; +} +.menubar { + color: #aaa; + line-height: 1.3em; + margin-top: 0; + padding-top: 0; +} + +.menubar a { + color: #aaa; + text-decoration: none; +} + +.menubar a:hover { + color: #7CA300; +} + +#header { + padding-top: 0.3em; +} + +#footer { + margin-top: 3em; + padding-bottom: 0.3em; +} + +.name { + font-size: 2.5em; +} + +h2 { + font-size: 1.8em; + font-family: "ff-tisa-web-pro-1","ff-tisa-web-pro-2",Palatino, georgia, "times new roman", serif; + font-weight: 100; + line-height: 1.2em; + border-bottom: 1px solid #ddd; + padding-bottom: 0.2em; + margin-bottom: -0.3em; + margin-top: 0; + padding-top: 1em; +} + +h3 { + font-size: 1.3em; + font-weight: normal; +} + +h1 { + font-size: 2em; + font-weight: normal; + border-bottom: 1px solid #ddd; +} + +h1, .post, .link-post { + padding-bottom: 8px; + margin-bottom: 48px; +} + + +.link-post h2 { + font-size: 1.4em; +} + +code { + font-family: Monaco, monospace; +} + +.highlight { + background: yellow; + margin-top: -0.3em; +} + +.osx-shortcut { + background: #f0f0f0; + color : #7CA300; + padding-left: 0.2em; + padding-right: 0.2em; + border: 1px solid #e0e0e0; + -moz-border-radius: 0.2em; + -webkit-border-radius: 0.2em; +} + +.meta { + font-family: "ff-tisa-web-pro-1","ff-tisa-web-pro-2",Palatino, georgia, "times new roman", serif; + font-size: 0.9em; + font-weight: bold; + color: #999; + border-top: 1px solid #ddd; + padding-top: 0.1em; + padding-bottom: 0.1em; + margin-top: -0.6em; +} + +.meta a, .content a, .related a { + color: #7CA300; + text-decoration: none; + border-bottom: 1px dotted #d3dfee; +} + +.meta a { + font-weight: normal; + +} + +.meta a:hover, .content a:hover, .related a:hover { + border-bottom: 1px solid #7CA300; +} + +.title a { + color: #7CA300; + text-decoration: none; + border: none; + padding: 0; + margin: 0; + background: white; +} + +.title a:hover { + border: none; +} + +.andrzejsliwa { + color:#7CA300; + text-shadow:2px 2px 0 rgba(0, 0, 0, 0.15); +} + +.video { + padding-top: 0.5em; + padding-bottom: 0.5em; + padding-bottom: 0; + text-align: center; +} + +pre { + font: 0.7em Monaco, monospace; + line-height: 1.4em; + display: block; + color: white; + background: #0B2F20; + -moz-border-radius: 0.3em; + -webkit-border-radius: 0.3em; + padding: 0.6em; + white-space: pre-wrap; /* css-3 */ + white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */ + white-space: -pre-wrap; /* Opera 4-6 */ + white-space: -o-pre-wrap; /* Opera 7 */ + word-wrap: break-word; /* Internet Explorer 5.5+ */ +} + +.related { + color: #7CA300; + font-family: "ff-tisa-web-pro-1","ff-tisa-web-pro-2",Palatino, georgia, "times new roman", serif; + font-size: 0.9em; + line-height: 1.7em; +} + +.related h3 { + font-size: 1.2em; + border-bottom: 1px solid #ddd; + padding-bottom: 0; + margin-bottom: 0; +} + +.related p { + margin-top: 0.4em; +} + +.content p { + margin-bottom: 1.3em; +} + +.onleft { + float : left; +} + +#rest { + float : right; + width : 600px; +} + +#atom_link img { + border:medium none; +} + + +/* @group FancyFirst */ + .content h2 + p:first-letter { + font-size: 48px; + padding: 0 0.15em 0 0; + margin: 0.05em 0 -0.15em 0; + line-height: 1em; + float: left; +} + +.content h2 + p:first-line { + font-variant: small-caps; + font-size: larger; +} +/* @end */ + +.green { + color: #7CA300; +} + +strong { + color: #7CA300; +} + +.foto { + padding:2px; + flow: left; + border:1px solid #7CA300; +} + +img { + border: 0px; +} + +.post img.example { + width: 43em; +} + + + +#loopedSlider { + margin:0 auto; + padding:40px 0; + width:740px; +} + +#loopedSlider .nav-buttons { + list-style-type:none; + margin:0; + padding:0; + position:relative; +} + +ul, ol { + list-style-image:none; + list-style-position:outside; + list-style-type:none; + padding:10px 0; +} + +.related ul, ol { + list-style-type: disc; + margin: 20px; + padding:10px 0; +} + +#loopedSlider li#p { + left:0; + position:absolute; + top:300px; +} + +#loopedSlider li#p1 { + left:0; + position:absolute; + top:800px; +} + +li { + margin:0; + padding:0; +} + +a { + color:#2882C1; +} + +#portfolio a { + border:medium none; + text-decoration:none; +} + +#loopedSlider li#n { + position:absolute; + right:0; + top:300px; +} + +#loopedSlider li#n1 { + position:absolute; + right:0; + top:800px; +} + +a img { + border:medium none; +} + +.container { + height:320px; + margin-left:50px; + overflow:hidden; + position:relative; + width:640px; +} + +.slides { + left:0; + position:absolute; + top:0; +} + +.slides div.slide { + display:none; + position:absolute; + top:0; + width:640px; +} + +#portfolio h2 { + color:#7CA300; + font-size:40px; + font-weight:normal; + letter-spacing:-1px; + line-height:40px; + padding:0 0 10px; + font-family:Georgia; + text-shadow:2px 2px 0 rgba(0, 0, 0, 0.15); +} + +#portfolio p { + color:#333333; + font-size:14px; + line-height:20px; +} + +#portfolio .alignright { + float:top; + margin:5px 0 8px 20px; +} + +.highlight + .highlight { display:none; } /* dirty fix for jekyll highlight bug */ diff --git a/css/syntax.css b/css/syntax.css index 78f5d4d..606ab28 100644 --- a/css/syntax.css +++ b/css/syntax.css @@ -1,31 +1,48 @@ -.s1, .s2, .sx, .mi { - color: #91BB9E; +.k, .kd, .kt, .kn, .nb, .nt, .kc { + color: #c9913a; + font-weight: bold; } -.nb { - color: #FB9A4B; font-style: italic; +.nc, .no { + color: #c97c04; } -.k, .o { - color: #96DD3B; +.nf { + color: #dfcbac; } -.ss { - color: rgb(255, 207, 135); +.s, .s1, .s2, .sh, .sr { + color: #8eb370; } -.vi { - color: #FB9A4B; +.c, .c1, .x { + color: #5d575d; + font-style: italic; } -.c, .c1 { - color: #245032; +code.java .nd { + color: #7a7591; } -.no { - color: #9DF39F; +code.xml .nt { + font-weight: normal; } -.kp, .ss { - color: #497958; +code { + font: 10pt Monaco, monospace; +} + +pre { + color: #ccc; + line-height: 1.1em; + background-color: #202020; + -moz-border-radius: 0.3em; + -webkit-border-radius: 0.3em; + padding: 0.6em; + white-space: pre-wrap; /* css-3 */ + white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */ + white-space: -pre-wrap; /* Opera 4-6 */ + white-space: -o-pre-wrap; /* Opera 7 */ + word-wrap: break-word; /* Internet Explorer 5.5+ */ + margin-bottom: 1em; } diff --git a/favicon.ico b/favicon.ico new file mode 100644 index 0000000..a6b607d Binary files /dev/null and b/favicon.ico differ diff --git a/images/atom.jpg b/images/atom.jpg new file mode 100644 index 0000000..3d137ce Binary files /dev/null and b/images/atom.jpg differ diff --git a/images/next.png b/images/next.png new file mode 100644 index 0000000..0c0476e Binary files /dev/null and b/images/next.png differ diff --git a/images/pawel_kaczor.png b/images/pawel_kaczor.png new file mode 100644 index 0000000..1957edb Binary files /dev/null and b/images/pawel_kaczor.png differ diff --git a/images/previous.png b/images/previous.png new file mode 100644 index 0000000..78cff80 Binary files /dev/null and b/images/previous.png differ diff --git a/images/ruby-logo.png b/images/ruby-logo.png new file mode 100644 index 0000000..284e609 Binary files /dev/null and b/images/ruby-logo.png differ diff --git a/images/twitter_48.png b/images/twitter_48.png new file mode 100644 index 0000000..8abea56 Binary files /dev/null and b/images/twitter_48.png differ diff --git a/index.markdown b/index.markdown index 4fe87ec..7c279be 100644 --- a/index.markdown +++ b/index.markdown @@ -1,55 +1,50 @@ --- layout: default title: "Pawel Kaczor - blog" -description: "Blog Pawla Kaczora, o programowaniu w aplikacji biznesowych." +description: "Blog Pawła Kaczora, o programowaniu aplikacji biznesowych." --- <div class="related"> <h2 style="padding-top:1em;" class="green">Wpisy:</h2> <ul>{% for post in site.posts %}<li><a href="{{ post.url }}">{{ post.title }}</a></li>{% endfor %}</ul> </div> {% for page in site.posts limit:5 %} {% assign body = page.content %} {% include post-div.html %} {% if page.comments %} <div id="disqus_thread"></div> <script type="text/javascript" src="http://disqus.com/forums/Newion/embed.js"> </script> <noscript> <a href="http://Newion.disqus.com/?url=ref">View the discussion thread.</a> </noscript> <a href="http://disqus.com" class="dsq-brlink"> blog comments powered by <span class="logo-disqus">Disqus</span> </a> {% endif %} {% endfor %} <div class="related"> - <div class="onleft"> - <a id="atom_link" href="/atom.xml"> - <img alt="subscribe" src="/images/atom.jpg"/> - </a> - <br /> - <a href="http://validator.w3.org/check?uri=referer"> - <img src="http://www.w3.org/Icons/valid-xhtml10-blue" - alt="Valid XHTML 1.0 Strict" height="31" width="88" /> - </a> - </div> <div id="rest"> + <div> + <div> + <h2><a href="http://pkaczor.blogspot.com" id="blog-link" style="text-align:left;">read my blog!</a> <img alt="blog" src="http://img1.blogblog.com/img/navbar/icons_orange.png"/></h2> + </div> + </div> <div class="twitter"> <div id="twitter_div"> <h2 class="sidebar-title">ćwierkanie! <img alt="twitter" src="/images/twitter_48.png"/></h2> <ul id="twitter_update_list"><li></li></ul> <a href="http://twitter.com/Newion" id="twitter-link" style="display:block;text-align:right;">follow me on Twitter</a> </div> </div> <script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script> <script type="text/javascript" src="http://twitter.com/statuses/user_timeline/Newion.json?callback=twitterCallback2&amp;count=2"></script> </div> </div>
rjungemann/turnstile
5841528b51b498b90fe87c9d7252c5eb498726fc
Added more specs.
diff --git a/History.txt b/History.txt index 6189037..e24ab9f 100644 --- a/History.txt +++ b/History.txt @@ -1,11 +1,15 @@ == 0.0.5 / 2009-08-19 * Fixed the README.txt. == 0.0.6 / 2009-08-19 * Added some specs. Fixed some serious errors. == 0.0.7 / 2009-08-19 -* Added some code to make sure input is valid, which will hopefully squash some bugs. \ No newline at end of file +* Added some code to make sure input is valid, which will hopefully squash some bugs. + +== 0.0.8 / 2009-08-19 + +* Fixed turnstile console. Also added more specs. \ No newline at end of file
rjungemann/turnstile
23058db7d66aadfe295cc2c46f1528cfef13e807
Added some more specs. Added more validity checks in the code.
diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..03c1d10 Binary files /dev/null and b/.DS_Store differ diff --git a/.gitignore b/.gitignore index 5f27dd6..3574aab 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,2 @@ -lib/turnstile/tmp/db.sdbm.dir -lib/turnstile/tmp/db.sdbm.pag -lib/turnstile/tmp/db.sdbm_expires.dir -lib/turnstile/tmp/db.sdbm_expires.dir +tmp pkg \ No newline at end of file diff --git a/History.txt b/History.txt index 1a2522f..6189037 100644 --- a/History.txt +++ b/History.txt @@ -1,7 +1,11 @@ == 0.0.5 / 2009-08-19 * Fixed the README.txt. == 0.0.6 / 2009-08-19 -* Added some specs. Fixed some serious errors. \ No newline at end of file +* Added some specs. Fixed some serious errors. + +== 0.0.7 / 2009-08-19 + +* Added some code to make sure input is valid, which will hopefully squash some bugs. \ No newline at end of file diff --git a/Rakefile b/Rakefile index 7f28170..7bad9dc 100644 --- a/Rakefile +++ b/Rakefile @@ -1,34 +1,41 @@ # Look in the tasks/setup.rb file for the various options that can be # configured in this Rakefile. The .rake files in the tasks directory # are where the options are used. begin require 'bones' Bones.setup rescue LoadError begin load 'tasks/setup.rb' rescue LoadError raise RuntimeError, '### please install the "bones" gem ###' end end +namespace :tmp do + desc "Remove all temporary files." + task :clean do + sh "sudo rm -rf pkg tmp" + end +end + ensure_in_path 'lib' require 'turnstile' task :default => 'spec:run' PROJ.name = 'turnstile' PROJ.authors = 'Roger Jungemann' PROJ.email = '[email protected]' PROJ.url = 'http://thefifthcircuit.com' PROJ.version = Turnstile::VERSION PROJ.rubyforge.name = 'turnstile' PROJ.spec.opts << '--color' depend_on 'moneta' depend_on 'uuid' depend_on 'andand' # EOF diff --git a/bin/turnstile b/bin/turnstile index 03dd24c..392414a 100755 --- a/bin/turnstile +++ b/bin/turnstile @@ -1,3 +1,3 @@ -#!/bin/sh +#!/usr/bin/env ruby -irb -rturnstile \ No newline at end of file +exec("irb -rturnstile") \ No newline at end of file diff --git a/lib/.DS_Store b/lib/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/lib/.DS_Store differ diff --git a/lib/turnstile.rb b/lib/turnstile.rb index b15322f..b29197a 100644 --- a/lib/turnstile.rb +++ b/lib/turnstile.rb @@ -1,48 +1,48 @@ module Turnstile # :stopdoc: - VERSION = '0.0.6' + VERSION = '0.0.8' LIBPATH = ::File.expand_path(::File.dirname(__FILE__)) + ::File::SEPARATOR PATH = ::File.dirname(LIBPATH) + ::File::SEPARATOR # :startdoc: # Returns the version string for the library. # def self.version VERSION end # Returns the library path for the module. If any arguments are given, # they will be joined to the end of the libray path using # <tt>File.join</tt>. # def self.libpath( *args ) args.empty? ? LIBPATH : ::File.join(LIBPATH, args.flatten) end # Returns the lpath for the module. If any arguments are given, # they will be joined to the end of the path using # <tt>File.join</tt>. # def self.path( *args ) args.empty? ? PATH : ::File.join(PATH, args.flatten) end # Utility method used to require all files ending in .rb that lie in the # directory below this file that has the same name as the filename passed # in. Optionally, a specific _directory_ name can be passed in such that # the _filename_ does not have to be equivalent to the directory. # def self.require_all_libs_relative_to( fname, dir = nil ) dir ||= ::File.basename(fname, '.*') search_me = ::File.expand_path( ::File.join(::File.dirname(fname), dir, '**', '*.rb')) Dir.glob(search_me).sort.each {|rb| require rb} end end # module Turnstile Turnstile.require_all_libs_relative_to(__FILE__) # EOF diff --git a/lib/turnstile/model/modules/manageable.rb b/lib/turnstile/model/modules/manageable.rb index 9c0c740..21b5a01 100644 --- a/lib/turnstile/model/modules/manageable.rb +++ b/lib/turnstile/model/modules/manageable.rb @@ -1,125 +1,129 @@ require 'andand' module Turnstile module Model module Modules module Manageable module ClassMethods def find name + raise "No name was provided." if name.nil? + $t.db.has_key?("user-#{name}") ? User.new(name) : nil end def create name raise "No name was provided." if name.nil? + raise "User already exists" if User.exists? name $t.transact("user-#{name}") do |user| - raise "User already exists" unless user.empty? - { :name => name, :realms => {}, :created_on => Time.now } end User.new name end def exists? name !User.find(name).nil? end def users $t.db.keys.reject { |k| not k.match(/user-.*/) }.collect { |k| k[5..-1] } end def realms - $t.db["realms"].andand.keys + $t.db["realms"].keys end end def add_realm realm, password raise "No password was provided." if password.nil? raise "No realm was provided." if realm.nil? raise "Realm doesn't exist." if Realm.find(realm).nil? columns = $t.db["user-#{@name}"] salt = Generate.salt raise "User is already part of this realm." if not columns[:realms][realm].nil? columns[:realms][realm] = { :roles => [] } columns[:realms][realm][:salt] = salt columns[:realms][realm][:hash] = Generate.hash(salt, password) $t.db["user-#{name}"] = columns self end def remove_realm realm raise "No realm was provided." if realm.nil? raise "Realm doesn't exist." if Realm.find(realm).nil? columns = $t.db["user-#{@name}"] raise "User isn't part of realm." if not in_realm?(realm) columns[:realms].delete realm $t.db["user-#{name}"] = columns self end def in_realm? realm + raise "No realm was provided." if realm.nil? + raise "Realm doesn't exist." if Realm.find(realm).nil? + !$t.db["user-#{@name}"][:realms][realm].nil? end def change_password realm, password raise "No password was provided." if password.nil? raise "No realm was provided." if realm.nil? columns = $t.db["user-#{@name}"] raise "User isn't part of realm." if not in_realm?(realm) salt = Generate.salt columns[:realms][realm][:salt] = salt columns[:realms][realm][:hash] = Generate.hash(salt, password) $t.db["user-#{@name}"] = columns self end def check_password realm, password raise "No password was provided." if password.nil? raise "No realm was provided." if realm.nil? columns = $t.db["user-#{@name}"] raise "User isn't part of realm." if not in_realm?(realm) hash = Generate.hash(columns[:realms][realm][:salt], password) hash == columns[:realms][realm][:hash] end def realms columns = $t.db["user-#{@name}"][:realms].keys end def destroy $t.db.delete "user-#{@name}" @name = nil nil end def self.included(base) base.extend ClassMethods end end end end end \ No newline at end of file diff --git a/lib/turnstile/model/realm.rb b/lib/turnstile/model/realm.rb index 40d3ae5..0f4a9da 100644 --- a/lib/turnstile/model/realm.rb +++ b/lib/turnstile/model/realm.rb @@ -1,77 +1,82 @@ module Turnstile module Model class Realm attr_reader :name def self.init $t.db["realms"] ||= {} end def initialize name @name = name end def self.create name, *roles + raise "Name for realm wasn't provided." if name.nil? + raise "Realm already exists." if Realm.exists? "name" + $t.transact("realms") do |realms| - realms[name] ||= { :roles => roles || [] } + realms[name] = { :roles => roles || [] } realms end Realm.new name end def self.find name $t.db["realms"][name] ? Realm.new(name) : nil end def self.exists? name !Realm.find(name).nil? end def add_role name raise "Role hasn't been created yet." unless Role.exists? name raise "Role already exists in realm." if self.roles.include? name $t.transact("realms") do |realms| realms[@name][:roles] << name realms end self end def remove_role name raise "Role hasn't been created yet." unless Role.exists? name raise "Role already exists in realm." unless self.roles.include? name $t.transact("realms") do |realms| realms[@name][:roles].reject! { |r| r == name } realms end self end def destroy $t.transact("realms") do |realms| realms.delete name realms end + @name = nil + nil end def self.realms $t.db["realms"] end def roles $t.db["realms"][@name][:roles] end end end end \ No newline at end of file diff --git a/lib/turnstile/model/role.rb b/lib/turnstile/model/role.rb index 8dd781c..b6c23e8 100644 --- a/lib/turnstile/model/role.rb +++ b/lib/turnstile/model/role.rb @@ -1,82 +1,94 @@ module Turnstile module Model class Role attr_reader :name def initialize name @name = name end def self.init $t.db["roles"] ||= {} end def self.create name, *rights + raise "Name wasn't provided." if name.nil? + rights ||= [] roles = $t.db["roles"] raise "Role already exists." if roles.include? name roles[name] = { :rights => rights } $t.db["roles"] = roles Role.new name end def self.find name + raise "Name wasn't provided." if name.nil? + roles = $t.db["roles"] roles.include?(name) ? Role.new(name) : nil end def self.exists? name !$t.db["roles"][name].nil? end def self.roles $t.db["roles"].keys end def rights roles = $t.db["roles"] roles[@name][:rights] end def has_right? right + raise "Right wasn't provided." if right.nil? + rights.include? right end def add_right right + raise "Right wasn't provided." if right.nil? + raise "Right already exists." if Role.has_right? right + roles = $t.db["roles"] rights = roles[@name][:rights] + right roles[@name][:rights] = rights $t.db["roles"] = role self end def remove_right right + raise "Right wasn't provided." if right.nil? + raise "Right doesn't exist." unless Role.has_right? right + roles = $t.db["roles"] rights = roles[@name][:rights].reject right roles[@name][:rights] = rights $t.db["roles"] = role self end def destroy $t.db["roles"].delete @name @name = nil nil end end end end \ No newline at end of file diff --git a/lib/turnstile/model/turnstile.rb b/lib/turnstile/model/turnstile.rb index d598e9b..9eb6f67 100644 --- a/lib/turnstile/model/turnstile.rb +++ b/lib/turnstile/model/turnstile.rb @@ -1,31 +1,31 @@ require 'moneta' require 'moneta/sdbm' module Turnstile module Model class Turnstile attr_reader :db def self.init User.init Realm.init Role.init end def initialize(options = {}) - tmp_dir = File.join(File.dirname(__FILE__), "..", "tmp") + tmp_dir = File.join(File.dirname(__FILE__), %w[.. .. .. tmp]) Dir.mkdir(tmp_dir) unless File.directory?(tmp_dir) options[:path] ||= File.join(tmp_dir, "db.sdbm") options[:moneta_store] ||= Moneta::SDBM @db = options[:moneta_store].new(:file => options[:path]) end def transact(key, &block) item = @db[key] || {} @db[key] = yield(item) end end end end \ No newline at end of file
rjungemann/turnstile
60536051c468355cc050cbbd8451ec11ded24227
Fixed README and added some more validity checks, which will hopefully squash some bugs.
diff --git a/README.txt b/README.txt index bcb57b8..1163cf9 100644 --- a/README.txt +++ b/README.txt @@ -1,98 +1,97 @@ turnstile by Roger Jungemann http://thefifthcircuit.com/ == DESCRIPTION: Turnstile is meant to be a flexible authentication and authorization system for Ruby. Currently it is merely a set of "model" classes, although I will shortly release a set of Rack middleware and an HTTP client library which will allow one to create providers, consumers, and clients which are available to Rails apps (or any Rack-compatible app for that matter), for a modest "single sign-on" solution. Turnstile is built on Moneta, which is a hot-swappable interface for various key-value stores. Moneta uses SDBM as its data-store by default, but it can also use Tokyo Cabinet, Redis, or even SQL-based sources, thanks to the DataMapper Moneta wrapper. == FEATURES/PROBLEMS: -* Tests are glaringly missing. * I need to add in my set of Rack middleware for creating providers, consumers, and clients. I have a mostly completed set of code for these. * I am considering OAuth and/or OpenID support for my provider, consumer, and client, which could be useful for different aspects of turnstile. == SYNOPSIS: To get started, try typing in `turnstile` in your terminal. This will open a prompt allowing one to interact with the turnstile database. Let's first try and create a role. A role is a collection of limited rights for a particular resource. For example, a web application with a "/treasures" url might want to limit access to that resource to only a small set of users. For example: Role.create "king", "/", "/treasures" Role.create "hero", "/" Role.create "damsel", "/" Next, let's create a realm. A realm is a collection of resources which need to be authorized and authenticated. Let's create a realm called `magical_kingdom` and associate some roles with it. realm = "magical_kingdom" Realm.create realm, "king", "hero", "damsel" Next, let's try actually creating a user. name, password = "mickey", "mouse" user = User.create "mickey" user.add_realm realm, password user.add_role realm, "hero" Now, the important part. How does one sign in a user? How does one keep track of signedin users? Here's how to signin a user: user.signin realm, password Once a user is signed in, the `uuid` method will give a value which can be freely given to the user. The user can later be looked up by turnstile just by using the uuid for that user's session. uuid = user.uuid realm user = User.from_uuid uuid You can also see if a user is signed into a realm, or sign them out. user.signedin? realm user.signout realm == REQUIREMENTS: * Moneta, uuid, and andand gems == INSTALL: gem sources -a http://gems.github.com sudo gem install thefifthcircuit-turnstile To use, either type `turnstile` into your terminal, or create a new text file, type in require 'rubygems' require 'turnstile' $t = Turnstile::Model::Turnstile.new # create and instantiate database Turnstile::Model::Turnstile.init # setup database with default values include Turnstile::Model User.create "minnie" == LICENSE: (The MIT License) -Copyright (c) 2008 FIXME (different license?) +Copyright (c) 2009 thefifthcircuit. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/lib/turnstile/model/modules/authorizable.rb b/lib/turnstile/model/modules/authorizable.rb index 700445f..15c1da6 100644 --- a/lib/turnstile/model/modules/authorizable.rb +++ b/lib/turnstile/model/modules/authorizable.rb @@ -1,61 +1,81 @@ module Turnstile module Model module Modules module Authorizable def authorized? realm, role + raise "Realm wasn't provided." if realm.nil? + raise "Role wasn't provided." if role.nil? + raise "Role doesn't exist." unless Role.exists? role + raise "Realm doesn't exist." unless Realm.exists? realm + raise "User isn't part of realm." unless in_realm?(realm) + columns = $t.db["user-#{@name}"] raise "User isn't part of realm." if columns[:realms][realm].nil? columns[:realms][realm][:roles].include? role end def add_role realm, role - raise "Role doesn't exist." if Role.find(role).nil? + raise "Realm wasn't provided." if realm.nil? + raise "Role wasn't provided." if role.nil? + raise "Role doesn't exist." unless Role.exists? role + raise "Realm doesn't exist." unless Realm.exists? realm raise "User isn't part of realm." unless in_realm?(realm) columns = $t.db["user-#{@name}"] roles = columns[:realms][realm][:roles] raise "User already has this role." if roles.include? role roles << role columns[:realms][realm][:roles] = roles $t.db["user-#{@name}"] = columns end def remove_role realm, role - raise "Role doesn't exist." if Role.find(role).nil? + raise "Realm wasn't provided." if realm.nil? + raise "Role wasn't provided." if role.nil? + raise "Role doesn't exist." unless Role.exists? role + raise "Realm doesn't exist." unless Realm.exists? realm raise "User isn't part of realm." unless in_realm?(realm) columns = $t.db["user-#{@name}"] roles = columns[:realms][realm][:roles] raise "User doesn't have this role." if not roles.include? role roles.reject! { |r| r == role } columns[:realms][realm][:roles] = roles $t.db["user-#{@name}"] = columns end def roles realm + raise "Realm wasn't provided." if realm.nil? + raise "Realm doesn't exist." unless Realm.exists? realm + columns = $t.db["user-#{@name}"] raise "User isn't part of realm" unless in_realm?(realm) columns[:realms][realm][:roles] end def has_right? realm, right + raise "Realm wasn't provided." if realm.nil? + raise "Right wasn't provided." if right.nil? + raise "Realm doesn't exist." unless Realm.exists? realm + raise "User isn't part of realm." unless in_realm?(realm) + not roles(realm).reject { |role| not Role.find(role).has_right? role }.empty? end end end end end \ No newline at end of file diff --git a/lib/turnstile/model/turnstile.rb b/lib/turnstile/model/turnstile.rb index 029ade4..d598e9b 100644 --- a/lib/turnstile/model/turnstile.rb +++ b/lib/turnstile/model/turnstile.rb @@ -1,31 +1,31 @@ require 'moneta' require 'moneta/sdbm' module Turnstile module Model class Turnstile attr_reader :db def self.init User.init Realm.init Role.init end def initialize(options = {}) tmp_dir = File.join(File.dirname(__FILE__), "..", "tmp") - Dir.mkdirs(tmp_dir) unless File.directory?(tmp_dir) + Dir.mkdir(tmp_dir) unless File.directory?(tmp_dir) options[:path] ||= File.join(tmp_dir, "db.sdbm") options[:moneta_store] ||= Moneta::SDBM @db = options[:moneta_store].new(:file => options[:path]) end def transact(key, &block) item = @db[key] || {} @db[key] = yield(item) end end end end \ No newline at end of file
rjungemann/turnstile
7fdeb4b4f020a67eb40718e43dff5c7be67770ba
Added .gitignore and ignored packaged files.
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5f27dd6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +lib/turnstile/tmp/db.sdbm.dir +lib/turnstile/tmp/db.sdbm.pag +lib/turnstile/tmp/db.sdbm_expires.dir +lib/turnstile/tmp/db.sdbm_expires.dir +pkg \ No newline at end of file diff --git a/History.txt b/History.txt index 2cb38ba..1a2522f 100644 --- a/History.txt +++ b/History.txt @@ -1,3 +1,7 @@ == 0.0.5 / 2009-08-19 -* Fixed the README.txt. \ No newline at end of file +* Fixed the README.txt. + +== 0.0.6 / 2009-08-19 + +* Added some specs. Fixed some serious errors. \ No newline at end of file diff --git a/lib/turnstile.rb b/lib/turnstile.rb index 3b73b14..b15322f 100644 --- a/lib/turnstile.rb +++ b/lib/turnstile.rb @@ -1,48 +1,48 @@ module Turnstile # :stopdoc: - VERSION = '0.0.5' + VERSION = '0.0.6' LIBPATH = ::File.expand_path(::File.dirname(__FILE__)) + ::File::SEPARATOR PATH = ::File.dirname(LIBPATH) + ::File::SEPARATOR # :startdoc: # Returns the version string for the library. # def self.version VERSION end # Returns the library path for the module. If any arguments are given, # they will be joined to the end of the libray path using # <tt>File.join</tt>. # def self.libpath( *args ) args.empty? ? LIBPATH : ::File.join(LIBPATH, args.flatten) end # Returns the lpath for the module. If any arguments are given, # they will be joined to the end of the path using # <tt>File.join</tt>. # def self.path( *args ) args.empty? ? PATH : ::File.join(PATH, args.flatten) end # Utility method used to require all files ending in .rb that lie in the # directory below this file that has the same name as the filename passed # in. Optionally, a specific _directory_ name can be passed in such that # the _filename_ does not have to be equivalent to the directory. # def self.require_all_libs_relative_to( fname, dir = nil ) dir ||= ::File.basename(fname, '.*') search_me = ::File.expand_path( ::File.join(::File.dirname(fname), dir, '**', '*.rb')) Dir.glob(search_me).sort.each {|rb| require rb} end end # module Turnstile Turnstile.require_all_libs_relative_to(__FILE__) # EOF diff --git a/lib/turnstile/model/turnstile.rb b/lib/turnstile/model/turnstile.rb index 8b094e1..029ade4 100644 --- a/lib/turnstile/model/turnstile.rb +++ b/lib/turnstile/model/turnstile.rb @@ -1,28 +1,31 @@ require 'moneta' require 'moneta/sdbm' module Turnstile module Model class Turnstile attr_reader :db def self.init User.init Realm.init Role.init end def initialize(options = {}) - options[:path] ||= File.join(File.dirname(__FILE__), "..", "tmp", "db.sdbm") + tmp_dir = File.join(File.dirname(__FILE__), "..", "tmp") + Dir.mkdirs(tmp_dir) unless File.directory?(tmp_dir) + + options[:path] ||= File.join(tmp_dir, "db.sdbm") options[:moneta_store] ||= Moneta::SDBM @db = options[:moneta_store].new(:file => options[:path]) end def transact(key, &block) item = @db[key] || {} @db[key] = yield(item) end end end end \ No newline at end of file diff --git a/lib/turnstile/tmp/db.sdbm.dir b/lib/turnstile/tmp/db.sdbm.dir deleted file mode 100644 index b57c670..0000000 Binary files a/lib/turnstile/tmp/db.sdbm.dir and /dev/null differ diff --git a/lib/turnstile/tmp/db.sdbm.pag b/lib/turnstile/tmp/db.sdbm.pag deleted file mode 100644 index 2724033..0000000 Binary files a/lib/turnstile/tmp/db.sdbm.pag and /dev/null differ diff --git a/lib/turnstile/tmp/db.sdbm_expires.dir b/lib/turnstile/tmp/db.sdbm_expires.dir deleted file mode 100644 index e69de29..0000000 diff --git a/lib/turnstile/tmp/db.sdbm_expires.pag b/lib/turnstile/tmp/db.sdbm_expires.pag deleted file mode 100644 index e69de29..0000000 diff --git a/pkg/turnstile-0.0.4.gem b/pkg/turnstile-0.0.4.gem deleted file mode 100644 index 4f7d8fa..0000000 Binary files a/pkg/turnstile-0.0.4.gem and /dev/null differ diff --git a/pkg/turnstile-0.0.4.tgz b/pkg/turnstile-0.0.4.tgz deleted file mode 100644 index d25dd59..0000000 Binary files a/pkg/turnstile-0.0.4.tgz and /dev/null differ diff --git a/pkg/turnstile-0.0.4/History.txt b/pkg/turnstile-0.0.4/History.txt deleted file mode 100644 index e800986..0000000 --- a/pkg/turnstile-0.0.4/History.txt +++ /dev/null @@ -1,4 +0,0 @@ -== 1.0.0 / 2009-08-19 - -* 1 major enhancement - * Birthday! diff --git a/pkg/turnstile-0.0.4/README.txt b/pkg/turnstile-0.0.4/README.txt deleted file mode 100644 index bcb57b8..0000000 --- a/pkg/turnstile-0.0.4/README.txt +++ /dev/null @@ -1,98 +0,0 @@ -turnstile - by Roger Jungemann - http://thefifthcircuit.com/ - -== DESCRIPTION: - -Turnstile is meant to be a flexible authentication and authorization system for Ruby. Currently it is merely a set of "model" classes, although I will shortly release a set of Rack middleware and an HTTP client library which will allow one to create providers, consumers, and clients which are available to Rails apps (or any Rack-compatible app for that matter), for a modest "single sign-on" solution. - -Turnstile is built on Moneta, which is a hot-swappable interface for various key-value stores. Moneta uses SDBM as its data-store by default, but it can also use Tokyo Cabinet, Redis, or even SQL-based sources, thanks to the DataMapper Moneta wrapper. - -== FEATURES/PROBLEMS: - -* Tests are glaringly missing. -* I need to add in my set of Rack middleware for creating providers, consumers, and clients. I have a mostly completed set of code for these. -* I am considering OAuth and/or OpenID support for my provider, consumer, and client, which could be useful for different aspects of turnstile. - -== SYNOPSIS: - -To get started, try typing in `turnstile` in your terminal. This will open a prompt allowing one to interact with the turnstile database. Let's first try and create a role. A role is a collection of limited rights for a particular resource. For example, a web application with a "/treasures" url might want to limit access to that resource to only a small set of users. For example: - - Role.create "king", "/", "/treasures" - Role.create "hero", "/" - Role.create "damsel", "/" - -Next, let's create a realm. A realm is a collection of resources which need to be authorized and authenticated. Let's create a realm called `magical_kingdom` and associate some roles with it. - - realm = "magical_kingdom" - - Realm.create realm, "king", "hero", "damsel" - -Next, let's try actually creating a user. - - name, password = "mickey", "mouse" - - user = User.create "mickey" - user.add_realm realm, password - user.add_role realm, "hero" - -Now, the important part. How does one sign in a user? How does one keep track of signedin users? Here's how to signin a user: - - user.signin realm, password - -Once a user is signed in, the `uuid` method will give a value which can be freely given to the user. The user can later be looked up by turnstile just by using the uuid for that user's session. - - uuid = user.uuid realm - - user = User.from_uuid uuid - -You can also see if a user is signed into a realm, or sign them out. - - user.signedin? realm - user.signout realm - -== REQUIREMENTS: - -* Moneta, uuid, and andand gems - -== INSTALL: - - gem sources -a http://gems.github.com - sudo gem install thefifthcircuit-turnstile - -To use, either type `turnstile` into your terminal, or create a new text file, type in - - require 'rubygems' - require 'turnstile' - - $t = Turnstile::Model::Turnstile.new # create and instantiate database - Turnstile::Model::Turnstile.init # setup database with default values - - include Turnstile::Model - - User.create "minnie" - -== LICENSE: - -(The MIT License) - -Copyright (c) 2008 FIXME (different license?) - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/pkg/turnstile-0.0.4/Rakefile b/pkg/turnstile-0.0.4/Rakefile deleted file mode 100644 index 7f28170..0000000 --- a/pkg/turnstile-0.0.4/Rakefile +++ /dev/null @@ -1,34 +0,0 @@ -# Look in the tasks/setup.rb file for the various options that can be -# configured in this Rakefile. The .rake files in the tasks directory -# are where the options are used. - -begin - require 'bones' - Bones.setup -rescue LoadError - begin - load 'tasks/setup.rb' - rescue LoadError - raise RuntimeError, '### please install the "bones" gem ###' - end -end - -ensure_in_path 'lib' -require 'turnstile' - -task :default => 'spec:run' - -PROJ.name = 'turnstile' -PROJ.authors = 'Roger Jungemann' -PROJ.email = '[email protected]' -PROJ.url = 'http://thefifthcircuit.com' -PROJ.version = Turnstile::VERSION -PROJ.rubyforge.name = 'turnstile' - -PROJ.spec.opts << '--color' - -depend_on 'moneta' -depend_on 'uuid' -depend_on 'andand' - -# EOF diff --git a/pkg/turnstile-0.0.4/bin/turnstile b/pkg/turnstile-0.0.4/bin/turnstile deleted file mode 100755 index 2458bd7..0000000 --- a/pkg/turnstile-0.0.4/bin/turnstile +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env ruby - -require 'rubygems' - -require File.expand_path( - File.join(File.dirname(__FILE__), %w[.. lib turnstile])) - -$t = Turnstile::Model::Turnstile.new -Turnstile::Model::Turnstile.init - -include Turnstile::Model \ No newline at end of file diff --git a/pkg/turnstile-0.0.4/lib/turnstile.rb b/pkg/turnstile-0.0.4/lib/turnstile.rb deleted file mode 100644 index a3da37e..0000000 --- a/pkg/turnstile-0.0.4/lib/turnstile.rb +++ /dev/null @@ -1,48 +0,0 @@ -module Turnstile - - # :stopdoc: - VERSION = '0.0.4' - LIBPATH = ::File.expand_path(::File.dirname(__FILE__)) + ::File::SEPARATOR - PATH = ::File.dirname(LIBPATH) + ::File::SEPARATOR - # :startdoc: - - # Returns the version string for the library. - # - def self.version - VERSION - end - - # Returns the library path for the module. If any arguments are given, - # they will be joined to the end of the libray path using - # <tt>File.join</tt>. - # - def self.libpath( *args ) - args.empty? ? LIBPATH : ::File.join(LIBPATH, args.flatten) - end - - # Returns the lpath for the module. If any arguments are given, - # they will be joined to the end of the path using - # <tt>File.join</tt>. - # - def self.path( *args ) - args.empty? ? PATH : ::File.join(PATH, args.flatten) - end - - # Utility method used to require all files ending in .rb that lie in the - # directory below this file that has the same name as the filename passed - # in. Optionally, a specific _directory_ name can be passed in such that - # the _filename_ does not have to be equivalent to the directory. - # - def self.require_all_libs_relative_to( fname, dir = nil ) - dir ||= ::File.basename(fname, '.*') - search_me = ::File.expand_path( - ::File.join(::File.dirname(fname), dir, '**', '*.rb')) - - Dir.glob(search_me).sort.each {|rb| require rb} - end - -end # module Turnstile - -Turnstile.require_all_libs_relative_to(__FILE__) - -# EOF diff --git a/pkg/turnstile-0.0.4/lib/turnstile/init.rb b/pkg/turnstile-0.0.4/lib/turnstile/init.rb deleted file mode 100644 index f79f039..0000000 --- a/pkg/turnstile-0.0.4/lib/turnstile/init.rb +++ /dev/null @@ -1,10 +0,0 @@ -dir = File.dirname(__FILE__) - -require "#{dir}/utils/generate" -require "#{dir}/model/turnstile" -require "#{dir}/model/user" -require "#{dir}/model/realm" -require "#{dir}/model/role" - -$t = Turnstile::Model::Turnstile.new -Turnstile::Model::Turnstile.init \ No newline at end of file diff --git a/pkg/turnstile-0.0.4/lib/turnstile/model/modules/authenticable.rb b/pkg/turnstile-0.0.4/lib/turnstile/model/modules/authenticable.rb deleted file mode 100644 index c37cb76..0000000 --- a/pkg/turnstile-0.0.4/lib/turnstile/model/modules/authenticable.rb +++ /dev/null @@ -1,74 +0,0 @@ -module Turnstile - module Model - module Modules - module Authenticable - module ClassMethods - def signin(realm, name, password) - raise "No name was provided." if name.nil? - raise "No password was provided." if password.nil? - raise "No realm was provided." if realm.nil? - - user = User.find name - - if user.nil? - return nil - else - raise "User isn't part of realm." if not user.in_realm?(realm) - raise "Wrong password was provided." if !user.check_password(realm, password) - - uuid = Generate.uuid - - user.set_uuid uuid, realm - - return user - end - end - - def from_uuid(uuid) - raise "No uuid was provided." if uuid.nil? - - uuids = $t.db["uuids"] - - name, realm = uuids[uuid][:name], uuids[uuid][:realm] - - user = User.find name - - user.in_realm?(realm) ? user : nil - end - end - - def signout(realm) - raise "No realm was provided." if realm.nil? - raise "User isn't part of realm." if not in_realm?(realm) - - set_uuid nil, realm - - nil - end - - def signedin?(realm) - $t.db["user-#{@name}"][:realms][realm].andand[:uuid].nil? ? nil : self - end - - def uuid(realm) - $t.db["user-#{@name}"][:realms][realm][:uuid] - end - - def set_uuid(uuid, realm) - uuids = $t.db["uuids"] - uuids[uuid] = { :name => self.name, :realm => realm } - $t.db["uuids"] = uuids - - $t.transact("user-#{@name}") do |u| - u[:realms][realm][:uuid] = uuid - u - end - end - - def self.included(base) - base.extend ClassMethods - end - end - end - end -end \ No newline at end of file diff --git a/pkg/turnstile-0.0.4/lib/turnstile/model/modules/authorizable.rb b/pkg/turnstile-0.0.4/lib/turnstile/model/modules/authorizable.rb deleted file mode 100644 index 1891d7e..0000000 --- a/pkg/turnstile-0.0.4/lib/turnstile/model/modules/authorizable.rb +++ /dev/null @@ -1,55 +0,0 @@ -module Turnstile - module Model - module Modules - module Authorizable - def authorized? realm, role - columns = $t.db["user-#{@name}"] - - raise "User isn't part of realm." if columns[:realms][realm].nil? - - columns[:realms][realm][:roles].include? role - end - - def add_role realm, role - columns = $t.db["user-#{@name}"] - - raise "User isn't part of realm." unless in_realm?(realm) - - roles = columns[:realms][realm][:roles] - - raise "User already has this role." if roles.include? role - - roles << role - - columns[:realms][realm][:roles] = roles - - $t.db["user-#{@name}"] = columns - end - - def remove_role realm, role - columns = $t.db["user-#{@name}"] - - raise "User isn't part of realm." unless in_realm?(realm) - - roles = columns[:realms][realm][:roles] - - raise "User doesn't have this role." if not roles.include? role - - roles.reject! { |r| r == role } - - columns[:realms][realm][:roles] = roles - - $t.db["user-#{@name}"] = columns - end - - def roles realm - columns = $t.db["user-#{@name}"] - - raise "User isn't part of realm" unless in_realm?(realm) - - columns[:realms][realm][:roles] - end - end - end - end -end \ No newline at end of file diff --git a/pkg/turnstile-0.0.4/lib/turnstile/model/modules/manageable.rb b/pkg/turnstile-0.0.4/lib/turnstile/model/modules/manageable.rb deleted file mode 100644 index 9408b17..0000000 --- a/pkg/turnstile-0.0.4/lib/turnstile/model/modules/manageable.rb +++ /dev/null @@ -1,119 +0,0 @@ -require 'andand' - -module Turnstile - module Model - module Modules - module Manageable - module ClassMethods - def find name - $t.db.has_key?("user-#{name}") ? User.new(name) : nil - end - - def create name - raise "No name was provided." if name.nil? - - $t.transact("user-#{name}") do |user| - raise "User already exists" unless user.empty? - - { :name => name, :realms => {}, :created_on => Time.now } - end - - User.new name - end - - def users - $t.db.keys.reject { |k| not k.match(/user-.*/) }.collect { |k| k[5..-1] } - end - - def realms - $t.db["realms"].andand.keys - end - end - - def add_realm realm, password - raise "No password was provided." if password.nil? - raise "No realm was provided." if realm.nil? - - columns = $t.db["user-#{@name}"] - - salt = Generate.salt - - raise "User is already part of this realm." if not columns[:realms][realm].nil? - - columns[:realms][realm] = { :roles => [] } - columns[:realms][realm][:salt] = salt - columns[:realms][realm][:hash] = Generate.hash(salt, password) - - $t.db["user-#{name}"] = columns - - self - end - - def remove_realm realm - raise "No realm was provided." if realm.nil? - - columns = $t.db["user-#{@name}"] - - raise "User isn't part of realm." if not in_realm?(realm) - - columns[:realms].delete! realm - - $t.db["user-#{name}"] = columns - - self - end - - def in_realm? realm - !$t.db["user-#{@name}"][:realms][realm].nil? - end - - def change_password realm, password - raise "No password was provided." if password.nil? - raise "No realm was provided." if realm.nil? - - columns = $t.db["user-#{@name}"] - - raise "User isn't part of realm." if not in_realm?(realm) - - salt = Generate.salt - - columns[:realms][realm][:salt] = salt - columns[:realms][realm][:hash] = Generate.hash(salt, password) - - $t.db["user-#{@name}"] = columns - - self - end - - def check_password realm, password - raise "No password was provided." if password.nil? - raise "No realm was provided." if realm.nil? - - columns = $t.db["user-#{@name}"] - - raise "User isn't part of realm." if not in_realm?(realm) - - hash = Generate.hash(columns[:realms][realm][:salt], password) - - hash == columns[:realms][realm][:hash] - end - - def realms - columns = $t.db["user-#{@name}"][:realms].keys - end - - def destroy - $t.db.delete "user-#{@name}" - - @name = nil - - nil - end - - def self.included(base) - base.extend ClassMethods - end - end - end - end -end \ No newline at end of file diff --git a/pkg/turnstile-0.0.4/lib/turnstile/model/realm.rb b/pkg/turnstile-0.0.4/lib/turnstile/model/realm.rb deleted file mode 100644 index e30774d..0000000 --- a/pkg/turnstile-0.0.4/lib/turnstile/model/realm.rb +++ /dev/null @@ -1,63 +0,0 @@ -module Turnstile - module Model - class Realm - attr_reader :name - - def self.init - $t.db["realms"] ||= {} - end - - def initialize name - @name = name - end - - def self.create name, *roles - $t.transact("realms") do |realms| - realms[name] ||= { :roles => roles || [] } - - realms - end - - Realm.new name - end - - def self.find name - $t.db["realms"][name] ? Realm.new : nil - end - - def add_role name - $t.transact("realms") do |realm| - realms[@name][:roles] << name - - realms - end - - self - end - - def remove_role name - $t.transact("realms") do |realm| - realms[@name][:roles].reject { |r| r == name } - - realms - end - - self - end - - def destroy - $t.transact("realms") do |realms| - realms.delete name - - realms - end - - nil - end - - def self.realms - $t.db["realms"] - end - end - end -end \ No newline at end of file diff --git a/pkg/turnstile-0.0.4/lib/turnstile/model/role.rb b/pkg/turnstile-0.0.4/lib/turnstile/model/role.rb deleted file mode 100644 index 3fd5eac..0000000 --- a/pkg/turnstile-0.0.4/lib/turnstile/model/role.rb +++ /dev/null @@ -1,76 +0,0 @@ -module Turnstile - module Model - class Role - attr_reader :name - - def initialize name - @name = name - end - - def self.init - $t.db["roles"] ||= {} - end - - def self.create name, *rights - rights ||= [] - roles = $t.db["roles"] - - raise "Role already exists." if roles.include? name - - roles[name] = { :rights => rights } - - $t.db["roles"] = roles - - Role.new name - end - - def self.find name - roles = $t.db["roles"] - - return nil unless roles.include? name - - Role.new name - end - - def self.roles - $t.db["roles"].keys - end - - def rights - roles = $t.db["roles"] - - roles[@name][:rights] - end - - def add_right right - roles = $t.db["roles"] - - rights = roles[@name][:rights] + right - roles[@name][:rights] = rights - - $t.db["roles"] = role - - self - end - - def remove_right right - roles = $t.db["roles"] - - rights = roles[@name][:rights].reject right - roles[@name][:rights] = rights - - $t.db["roles"] = role - - self - end - - def destroy - $t.db["roles"].remove @name - - @name = nil - - nil - end - end - end -end \ No newline at end of file diff --git a/pkg/turnstile-0.0.4/lib/turnstile/model/turnstile.rb b/pkg/turnstile-0.0.4/lib/turnstile/model/turnstile.rb deleted file mode 100644 index 8b094e1..0000000 --- a/pkg/turnstile-0.0.4/lib/turnstile/model/turnstile.rb +++ /dev/null @@ -1,28 +0,0 @@ -require 'moneta' -require 'moneta/sdbm' - -module Turnstile - module Model - class Turnstile - attr_reader :db - - def self.init - User.init - Realm.init - Role.init - end - - def initialize(options = {}) - options[:path] ||= File.join(File.dirname(__FILE__), "..", "tmp", "db.sdbm") - options[:moneta_store] ||= Moneta::SDBM - - @db = options[:moneta_store].new(:file => options[:path]) - end - - def transact(key, &block) - item = @db[key] || {} - @db[key] = yield(item) - end - end - end -end \ No newline at end of file diff --git a/pkg/turnstile-0.0.4/lib/turnstile/model/user.rb b/pkg/turnstile-0.0.4/lib/turnstile/model/user.rb deleted file mode 100644 index 35b5053..0000000 --- a/pkg/turnstile-0.0.4/lib/turnstile/model/user.rb +++ /dev/null @@ -1,25 +0,0 @@ -dir = File.dirname(__FILE__) - -require "#{dir}/modules/manageable" -require "#{dir}/modules/authenticable" -require "#{dir}/modules/authorizable" - -module Turnstile - module Model - class User - include Modules::Manageable - include Modules::Authenticable - include Modules::Authorizable - - attr_accessor :name - - def self.init - $t.db["uuids"] ||= {} - end - - def initialize(name = nil) - @name = name - end - end - end -end \ No newline at end of file diff --git a/pkg/turnstile-0.0.4/lib/turnstile/tmp/db.sdbm.dir b/pkg/turnstile-0.0.4/lib/turnstile/tmp/db.sdbm.dir deleted file mode 100644 index e69de29..0000000 diff --git a/pkg/turnstile-0.0.4/lib/turnstile/tmp/db.sdbm.pag b/pkg/turnstile-0.0.4/lib/turnstile/tmp/db.sdbm.pag deleted file mode 100644 index 9a0ec60..0000000 Binary files a/pkg/turnstile-0.0.4/lib/turnstile/tmp/db.sdbm.pag and /dev/null differ diff --git a/pkg/turnstile-0.0.4/lib/turnstile/tmp/db.sdbm_expires.dir b/pkg/turnstile-0.0.4/lib/turnstile/tmp/db.sdbm_expires.dir deleted file mode 100644 index e69de29..0000000 diff --git a/pkg/turnstile-0.0.4/lib/turnstile/tmp/db.sdbm_expires.pag b/pkg/turnstile-0.0.4/lib/turnstile/tmp/db.sdbm_expires.pag deleted file mode 100644 index e69de29..0000000 diff --git a/pkg/turnstile-0.0.4/lib/turnstile/utils/generate.rb b/pkg/turnstile-0.0.4/lib/turnstile/utils/generate.rb deleted file mode 100644 index b26a2ba..0000000 --- a/pkg/turnstile-0.0.4/lib/turnstile/utils/generate.rb +++ /dev/null @@ -1,18 +0,0 @@ -require 'digest/sha2' -require 'uuid' - -class Generate - @@uuid = UUID.new - - def self.salt - [Array.new(6) { rand(256).chr }.join].pack('m').chomp - end - - def self.hash password, salt - Digest::SHA256.hexdigest password + salt - end - - def self.uuid - @@uuid.generate - end -end \ No newline at end of file diff --git a/pkg/turnstile-0.0.4/spec/spec_helper.rb b/pkg/turnstile-0.0.4/spec/spec_helper.rb deleted file mode 100644 index ed0072c..0000000 --- a/pkg/turnstile-0.0.4/spec/spec_helper.rb +++ /dev/null @@ -1,16 +0,0 @@ - -require File.expand_path( - File.join(File.dirname(__FILE__), %w[.. lib turnstile])) - -Spec::Runner.configure do |config| - # == Mock Framework - # - # RSpec uses it's own mocking framework by default. If you prefer to - # use mocha, flexmock or RR, uncomment the appropriate line: - # - # config.mock_with :mocha - # config.mock_with :flexmock - # config.mock_with :rr -end - -# EOF diff --git a/pkg/turnstile-0.0.4/spec/turnstile_spec.rb b/pkg/turnstile-0.0.4/spec/turnstile_spec.rb deleted file mode 100644 index 9ff5a8c..0000000 --- a/pkg/turnstile-0.0.4/spec/turnstile_spec.rb +++ /dev/null @@ -1,7 +0,0 @@ - -require File.join(File.dirname(__FILE__), %w[spec_helper]) - -describe Turnstile do -end - -# EOF diff --git a/pkg/turnstile-0.0.4/tasks/ann.rake b/pkg/turnstile-0.0.4/tasks/ann.rake deleted file mode 100644 index d07084e..0000000 --- a/pkg/turnstile-0.0.4/tasks/ann.rake +++ /dev/null @@ -1,80 +0,0 @@ - -begin - require 'bones/smtp_tls' -rescue LoadError - require 'net/smtp' -end -require 'time' - -namespace :ann do - - # A prerequisites task that all other tasks depend upon - task :prereqs - - file PROJ.ann.file do - ann = PROJ.ann - puts "Generating #{ann.file}" - File.open(ann.file,'w') do |fd| - fd.puts("#{PROJ.name} version #{PROJ.version}") - fd.puts(" by #{Array(PROJ.authors).first}") if PROJ.authors - fd.puts(" #{PROJ.url}") if PROJ.url.valid? - fd.puts(" (the \"#{PROJ.release_name}\" release)") if PROJ.release_name - fd.puts - fd.puts("== DESCRIPTION") - fd.puts - fd.puts(PROJ.description) - fd.puts - fd.puts(PROJ.changes.sub(%r/^.*$/, '== CHANGES')) - fd.puts - ann.paragraphs.each do |p| - fd.puts "== #{p.upcase}" - fd.puts - fd.puts paragraphs_of(PROJ.readme_file, p).join("\n\n") - fd.puts - end - fd.puts ann.text if ann.text - end - end - - desc "Create an announcement file" - task :announcement => ['ann:prereqs', PROJ.ann.file] - - desc "Send an email announcement" - task :email => ['ann:prereqs', PROJ.ann.file] do - ann = PROJ.ann - from = ann.email[:from] || Array(PROJ.authors).first || PROJ.email - to = Array(ann.email[:to]) - - ### build a mail header for RFC 822 - rfc822msg = "From: #{from}\n" - rfc822msg << "To: #{to.join(',')}\n" - rfc822msg << "Subject: [ANN] #{PROJ.name} #{PROJ.version}" - rfc822msg << " (#{PROJ.release_name})" if PROJ.release_name - rfc822msg << "\n" - rfc822msg << "Date: #{Time.new.rfc822}\n" - rfc822msg << "Message-Id: " - rfc822msg << "<#{"%.8f" % Time.now.to_f}@#{ann.email[:domain]}>\n\n" - rfc822msg << File.read(ann.file) - - params = [:server, :port, :domain, :acct, :passwd, :authtype].map do |key| - ann.email[key] - end - - params[3] = PROJ.email if params[3].nil? - - if params[4].nil? - STDOUT.write "Please enter your e-mail password (#{params[3]}): " - params[4] = STDIN.gets.chomp - end - - ### send email - Net::SMTP.start(*params) {|smtp| smtp.sendmail(rfc822msg, from, to)} - end -end # namespace :ann - -desc 'Alias to ann:announcement' -task :ann => 'ann:announcement' - -CLOBBER << PROJ.ann.file - -# EOF diff --git a/pkg/turnstile-0.0.4/tasks/bones.rake b/pkg/turnstile-0.0.4/tasks/bones.rake deleted file mode 100644 index 2093b03..0000000 --- a/pkg/turnstile-0.0.4/tasks/bones.rake +++ /dev/null @@ -1,20 +0,0 @@ - -if HAVE_BONES - -namespace :bones do - - desc 'Show the PROJ open struct' - task :debug do |t| - atr = if t.application.top_level_tasks.length == 2 - t.application.top_level_tasks.pop - end - - if atr then Bones::Debug.show_attr(PROJ, atr) - else Bones::Debug.show PROJ end - end - -end # namespace :bones - -end # HAVE_BONES - -# EOF diff --git a/pkg/turnstile-0.0.4/tasks/gem.rake b/pkg/turnstile-0.0.4/tasks/gem.rake deleted file mode 100644 index ab68fc1..0000000 --- a/pkg/turnstile-0.0.4/tasks/gem.rake +++ /dev/null @@ -1,201 +0,0 @@ - -require 'find' -require 'rake/packagetask' -require 'rubygems/user_interaction' -require 'rubygems/builder' - -module Bones -class GemPackageTask < Rake::PackageTask - # Ruby GEM spec containing the metadata for this package. The - # name, version and package_files are automatically determined - # from the GEM spec and don't need to be explicitly provided. - # - attr_accessor :gem_spec - - # Tasks from the Bones gem directory - attr_reader :bones_files - - # Create a GEM Package task library. Automatically define the gem - # if a block is given. If no block is supplied, then +define+ - # needs to be called to define the task. - # - def initialize(gem_spec) - init(gem_spec) - yield self if block_given? - define if block_given? - end - - # Initialization tasks without the "yield self" or define - # operations. - # - def init(gem) - super(gem.name, gem.version) - @gem_spec = gem - @package_files += gem_spec.files if gem_spec.files - @bones_files = [] - - local_setup = File.join(Dir.pwd, %w[tasks setup.rb]) - if !test(?e, local_setup) - Dir.glob(::Bones.path(%w[lib bones tasks *])).each {|fn| bones_files << fn} - end - end - - # Create the Rake tasks and actions specified by this - # GemPackageTask. (+define+ is automatically called if a block is - # given to +new+). - # - def define - super - task :prereqs - task :package => ['gem:prereqs', "#{package_dir_path}/#{gem_file}"] - file "#{package_dir_path}/#{gem_file}" => [package_dir_path] + package_files + bones_files do - when_writing("Creating GEM") { - chdir(package_dir_path) do - Gem::Builder.new(gem_spec).build - verbose(true) { - mv gem_file, "../#{gem_file}" - } - end - } - end - - file package_dir_path => bones_files do - mkdir_p package_dir rescue nil - - gem_spec.files = (gem_spec.files + - bones_files.map {|fn| File.join('tasks', File.basename(fn))}).sort - - bones_files.each do |fn| - base_fn = File.join('tasks', File.basename(fn)) - f = File.join(package_dir_path, base_fn) - fdir = File.dirname(f) - mkdir_p(fdir) if !File.exist?(fdir) - if File.directory?(fn) - mkdir_p(f) - else - raise "file name conflict for '#{base_fn}' (conflicts with '#{fn}')" if test(?e, f) - safe_ln(fn, f) - end - end - end - end - - def gem_file - if @gem_spec.platform == Gem::Platform::RUBY - "#{package_name}.gem" - else - "#{package_name}-#{@gem_spec.platform}.gem" - end - end -end # class GemPackageTask -end # module Bones - -namespace :gem do - - PROJ.gem._spec = Gem::Specification.new do |s| - s.name = PROJ.name - s.version = PROJ.version - s.summary = PROJ.summary - s.authors = Array(PROJ.authors) - s.email = PROJ.email - s.homepage = Array(PROJ.url).first - s.rubyforge_project = PROJ.rubyforge.name - - s.description = PROJ.description - - PROJ.gem.dependencies.each do |dep| - s.add_dependency(*dep) - end - - PROJ.gem.development_dependencies.each do |dep| - s.add_development_dependency(*dep) - end - - s.files = PROJ.gem.files - s.executables = PROJ.gem.executables.map {|fn| File.basename(fn)} - s.extensions = PROJ.gem.files.grep %r/extconf\.rb$/ - - s.bindir = 'bin' - dirs = Dir["{#{PROJ.libs.join(',')}}"] - s.require_paths = dirs unless dirs.empty? - - incl = Regexp.new(PROJ.rdoc.include.join('|')) - excl = PROJ.rdoc.exclude.dup.concat %w[\.rb$ ^(\.\/|\/)?ext] - excl = Regexp.new(excl.join('|')) - rdoc_files = PROJ.gem.files.find_all do |fn| - case fn - when excl; false - when incl; true - else false end - end - s.rdoc_options = PROJ.rdoc.opts + ['--main', PROJ.rdoc.main] - s.extra_rdoc_files = rdoc_files - s.has_rdoc = true - - if test ?f, PROJ.test.file - s.test_file = PROJ.test.file - else - s.test_files = PROJ.test.files.to_a - end - - # Do any extra stuff the user wants - PROJ.gem.extras.each do |msg, val| - case val - when Proc - val.call(s.send(msg)) - else - s.send "#{msg}=", val - end - end - end # Gem::Specification.new - - Bones::GemPackageTask.new(PROJ.gem._spec) do |pkg| - pkg.need_tar = PROJ.gem.need_tar - pkg.need_zip = PROJ.gem.need_zip - end - - desc 'Show information about the gem' - task :debug => 'gem:prereqs' do - puts PROJ.gem._spec.to_ruby - end - - desc 'Write the gemspec ' - task :spec => 'gem:prereqs' do - File.open("#{PROJ.name}.gemspec", 'w') do |f| - f.write PROJ.gem._spec.to_ruby - end - end - - desc 'Install the gem' - task :install => [:clobber, 'gem:package'] do - sh "#{SUDO} #{GEM} install --local pkg/#{PROJ.gem._spec.full_name}" - - # use this version of the command for rubygems > 1.0.0 - #sh "#{SUDO} #{GEM} install --no-update-sources pkg/#{PROJ.gem._spec.full_name}" - end - - desc 'Uninstall the gem' - task :uninstall do - installed_list = Gem.source_index.find_name(PROJ.name) - if installed_list and installed_list.collect { |s| s.version.to_s}.include?(PROJ.version) then - sh "#{SUDO} #{GEM} uninstall --version '#{PROJ.version}' --ignore-dependencies --executables #{PROJ.name}" - end - end - - desc 'Reinstall the gem' - task :reinstall => [:uninstall, :install] - - desc 'Cleanup the gem' - task :cleanup do - sh "#{SUDO} #{GEM} cleanup #{PROJ.gem._spec.name}" - end -end # namespace :gem - - -desc 'Alias to gem:package' -task :gem => 'gem:package' - -task :clobber => 'gem:clobber_package' -remove_desc_for_task 'gem:clobber_package' - -# EOF diff --git a/pkg/turnstile-0.0.4/tasks/git.rake b/pkg/turnstile-0.0.4/tasks/git.rake deleted file mode 100644 index 4f9194b..0000000 --- a/pkg/turnstile-0.0.4/tasks/git.rake +++ /dev/null @@ -1,40 +0,0 @@ - -if HAVE_GIT - -namespace :git do - - # A prerequisites task that all other tasks depend upon - task :prereqs - - desc 'Show tags from the Git repository' - task :show_tags => 'git:prereqs' do |t| - puts %x/git tag/ - end - - desc 'Create a new tag in the Git repository' - task :create_tag => 'git:prereqs' do |t| - v = ENV['VERSION'] or abort 'Must supply VERSION=x.y.z' - abort "Versions don't match #{v} vs #{PROJ.version}" if v != PROJ.version - - tag = "%s-%s" % [PROJ.name, PROJ.version] - msg = "Creating tag for #{PROJ.name} version #{PROJ.version}" - - puts "Creating Git tag '#{tag}'" - unless system "git tag -a -m '#{msg}' #{tag}" - abort "Tag creation failed" - end - - if %x/git remote/ =~ %r/^origin\s*$/ - unless system "git push origin #{tag}" - abort "Could not push tag to remote Git repository" - end - end - end - -end # namespace :git - -task 'gem:release' => 'git:create_tag' - -end # if HAVE_GIT - -# EOF diff --git a/pkg/turnstile-0.0.4/tasks/notes.rake b/pkg/turnstile-0.0.4/tasks/notes.rake deleted file mode 100644 index 5360dfa..0000000 --- a/pkg/turnstile-0.0.4/tasks/notes.rake +++ /dev/null @@ -1,27 +0,0 @@ - -if HAVE_BONES - -desc "Enumerate all annotations" -task :notes do |t| - id = if t.application.top_level_tasks.length > 1 - t.application.top_level_tasks.slice!(1..-1).join(' ') - end - Bones::AnnotationExtractor.enumerate( - PROJ, PROJ.notes.tags.join('|'), id, :tag => true) -end - -namespace :notes do - PROJ.notes.tags.each do |tag| - desc "Enumerate all #{tag} annotations" - task tag.downcase.to_sym do |t| - id = if t.application.top_level_tasks.length > 1 - t.application.top_level_tasks.slice!(1..-1).join(' ') - end - Bones::AnnotationExtractor.enumerate(PROJ, tag, id) - end - end -end - -end # if HAVE_BONES - -# EOF diff --git a/pkg/turnstile-0.0.4/tasks/post_load.rake b/pkg/turnstile-0.0.4/tasks/post_load.rake deleted file mode 100644 index 3ec82d1..0000000 --- a/pkg/turnstile-0.0.4/tasks/post_load.rake +++ /dev/null @@ -1,34 +0,0 @@ - -# This file does not define any rake tasks. It is used to load some project -# settings if they are not defined by the user. - -PROJ.exclude << ["^#{Regexp.escape(PROJ.ann.file)}$", - "^#{Regexp.escape(PROJ.ignore_file)}$", - "^#{Regexp.escape(PROJ.rdoc.dir)}/", - "^#{Regexp.escape(PROJ.rcov.dir)}/"] - -flatten_arrays = lambda do |this,os| - os.instance_variable_get(:@table).each do |key,val| - next if key == :dependencies \ - or key == :development_dependencies - case val - when Array; val.flatten! - when OpenStruct; this.call(this,val) - end - end - end -flatten_arrays.call(flatten_arrays,PROJ) - -PROJ.changes ||= paragraphs_of(PROJ.history_file, 0..1).join("\n\n") - -PROJ.description ||= paragraphs_of(PROJ.readme_file, 'description').join("\n\n") - -PROJ.summary ||= PROJ.description.split('.').first - -PROJ.gem.files ||= manifest - -PROJ.gem.executables ||= PROJ.gem.files.find_all {|fn| fn =~ %r/^bin/} - -PROJ.rdoc.main ||= PROJ.readme_file - -# EOF diff --git a/pkg/turnstile-0.0.4/tasks/rdoc.rake b/pkg/turnstile-0.0.4/tasks/rdoc.rake deleted file mode 100644 index edbb804..0000000 --- a/pkg/turnstile-0.0.4/tasks/rdoc.rake +++ /dev/null @@ -1,51 +0,0 @@ - -require 'rake/rdoctask' - -namespace :doc do - - desc 'Generate RDoc documentation' - Rake::RDocTask.new do |rd| - rdoc = PROJ.rdoc - rd.main = rdoc.main - rd.rdoc_dir = rdoc.dir - - incl = Regexp.new(rdoc.include.join('|')) - excl = Regexp.new(rdoc.exclude.join('|')) - files = PROJ.gem.files.find_all do |fn| - case fn - when excl; false - when incl; true - else false end - end - rd.rdoc_files.push(*files) - - name = PROJ.name - rf_name = PROJ.rubyforge.name - - title = "#{name}-#{PROJ.version} Documentation" - title = "#{rf_name}'s " + title if rf_name.valid? and rf_name != name - - rd.options << "-t #{title}" - rd.options.concat(rdoc.opts) - end - - desc 'Generate ri locally for testing' - task :ri => :clobber_ri do - sh "#{RDOC} --ri -o ri ." - end - - task :clobber_ri do - rm_r 'ri' rescue nil - end - -end # namespace :doc - -desc 'Alias to doc:rdoc' -task :doc => 'doc:rdoc' - -desc 'Remove all build products' -task :clobber => %w(doc:clobber_rdoc doc:clobber_ri) - -remove_desc_for_task %w(doc:clobber_rdoc) - -# EOF diff --git a/pkg/turnstile-0.0.4/tasks/rubyforge.rake b/pkg/turnstile-0.0.4/tasks/rubyforge.rake deleted file mode 100644 index 87b3d31..0000000 --- a/pkg/turnstile-0.0.4/tasks/rubyforge.rake +++ /dev/null @@ -1,55 +0,0 @@ - -if PROJ.rubyforge.name.valid? && HAVE_RUBYFORGE - -require 'rubyforge' -require 'rake/contrib/sshpublisher' - -namespace :gem do - desc 'Package and upload to RubyForge' - task :release => [:clobber, 'gem'] do |t| - v = ENV['VERSION'] or abort 'Must supply VERSION=x.y.z' - abort "Versions don't match #{v} vs #{PROJ.version}" if v != PROJ.version - pkg = "pkg/#{PROJ.gem._spec.full_name}" - - if $DEBUG then - puts "release_id = rf.add_release #{PROJ.rubyforge.name.inspect}, #{PROJ.name.inspect}, #{PROJ.version.inspect}, \"#{pkg}.tgz\"" - puts "rf.add_file #{PROJ.rubyforge.name.inspect}, #{PROJ.name.inspect}, release_id, \"#{pkg}.gem\"" - end - - rf = RubyForge.new - rf.configure rescue nil - puts 'Logging in' - rf.login - - c = rf.userconfig - c['release_notes'] = PROJ.description if PROJ.description - c['release_changes'] = PROJ.changes if PROJ.changes - c['preformatted'] = true - - files = Dir.glob("#{pkg}*.*") - - puts "Releasing #{PROJ.name} v. #{PROJ.version}" - rf.add_release PROJ.rubyforge.name, PROJ.name, PROJ.version, *files - end -end # namespace :gem - - -namespace :doc do - desc "Publish RDoc to RubyForge" - task :release => %w(doc:clobber_rdoc doc:rdoc) do - config = YAML.load( - File.read(File.expand_path('~/.rubyforge/user-config.yml')) - ) - - host = "#{config['username']}@rubyforge.org" - remote_dir = "/var/www/gforge-projects/#{PROJ.rubyforge.name}/" - remote_dir << PROJ.rdoc.remote_dir if PROJ.rdoc.remote_dir - local_dir = PROJ.rdoc.dir - - Rake::SshDirPublisher.new(host, remote_dir, local_dir).upload - end -end # namespace :doc - -end # if HAVE_RUBYFORGE - -# EOF diff --git a/pkg/turnstile-0.0.4/tasks/setup.rb b/pkg/turnstile-0.0.4/tasks/setup.rb deleted file mode 100644 index a752385..0000000 --- a/pkg/turnstile-0.0.4/tasks/setup.rb +++ /dev/null @@ -1,292 +0,0 @@ - -require 'rubygems' -require 'rake' -require 'rake/clean' -require 'fileutils' -require 'ostruct' -require 'find' - -class OpenStruct; undef :gem if defined? :gem; end - -# TODO: make my own openstruct type object that includes descriptions -# TODO: use the descriptions to output help on the available bones options - -PROJ = OpenStruct.new( - # Project Defaults - :name => nil, - :summary => nil, - :description => nil, - :changes => nil, - :authors => nil, - :email => nil, - :url => "\000", - :version => ENV['VERSION'] || '0.0.0', - :exclude => %w(tmp$ bak$ ~$ CVS \.svn/ \.git/ ^pkg/), - :release_name => ENV['RELEASE'], - - # System Defaults - :ruby_opts => %w(-w), - :libs => [], - :history_file => 'History.txt', - :readme_file => 'README.txt', - :ignore_file => '.bnsignore', - - # Announce - :ann => OpenStruct.new( - :file => 'announcement.txt', - :text => nil, - :paragraphs => [], - :email => { - :from => nil, - :to => %w([email protected]), - :server => 'localhost', - :port => 25, - :domain => ENV['HOSTNAME'], - :acct => nil, - :passwd => nil, - :authtype => :plain - } - ), - - # Gem Packaging - :gem => OpenStruct.new( - :dependencies => [], - :development_dependencies => [], - :executables => nil, - :extensions => FileList['ext/**/extconf.rb'], - :files => nil, - :need_tar => true, - :need_zip => false, - :extras => {} - ), - - # File Annotations - :notes => OpenStruct.new( - :exclude => %w(^tasks/setup\.rb$), - :extensions => %w(.txt .rb .erb .rdoc) << '', - :tags => %w(FIXME OPTIMIZE TODO) - ), - - # Rcov - :rcov => OpenStruct.new( - :dir => 'coverage', - :opts => %w[--sort coverage -T], - :threshold => 90.0, - :threshold_exact => false - ), - - # Rdoc - :rdoc => OpenStruct.new( - :opts => [], - :include => %w(^lib/ ^bin/ ^ext/ \.txt$ \.rdoc$), - :exclude => %w(extconf\.rb$), - :main => nil, - :dir => 'doc', - :remote_dir => nil - ), - - # Rubyforge - :rubyforge => OpenStruct.new( - :name => "\000" - ), - - # Rspec - :spec => OpenStruct.new( - :files => FileList['spec/**/*_spec.rb'], - :opts => [] - ), - - # Subversion Repository - :svn => OpenStruct.new( - :root => nil, - :path => '', - :trunk => 'trunk', - :tags => 'tags', - :branches => 'branches' - ), - - # Test::Unit - :test => OpenStruct.new( - :files => FileList['test/**/test_*.rb'], - :file => 'test/all.rb', - :opts => [] - ) -) - -# Load the other rake files in the tasks folder -tasks_dir = File.expand_path(File.dirname(__FILE__)) -post_load_fn = File.join(tasks_dir, 'post_load.rake') -rakefiles = Dir.glob(File.join(tasks_dir, '*.rake')).sort -rakefiles.unshift(rakefiles.delete(post_load_fn)).compact! -import(*rakefiles) - -# Setup the project libraries -%w(lib ext).each {|dir| PROJ.libs << dir if test ?d, dir} - -# Setup some constants -DEV_NULL = File.exist?('/dev/null') ? '/dev/null' : 'NUL:' - -def quiet( &block ) - io = [STDOUT.dup, STDERR.dup] - STDOUT.reopen DEV_NULL - STDERR.reopen DEV_NULL - block.call -ensure - STDOUT.reopen io.first - STDERR.reopen io.last - $stdout, $stderr = STDOUT, STDERR -end - -DIFF = if system("gdiff '#{__FILE__}' '#{__FILE__}' > #{DEV_NULL} 2>&1") then 'gdiff' - else 'diff' end unless defined? DIFF - -SUDO = if system("which sudo > #{DEV_NULL} 2>&1") then 'sudo' - else '' end unless defined? SUDO - -RCOV = "#{RUBY} -S rcov" -RDOC = "#{RUBY} -S rdoc" -GEM = "#{RUBY} -S gem" - -%w(rcov spec/rake/spectask rubyforge bones facets/ansicode zentest).each do |lib| - begin - require lib - Object.instance_eval {const_set "HAVE_#{lib.tr('/','_').upcase}", true} - rescue LoadError - Object.instance_eval {const_set "HAVE_#{lib.tr('/','_').upcase}", false} - end -end -HAVE_SVN = (Dir.entries(Dir.pwd).include?('.svn') and - system("svn --version 2>&1 > #{DEV_NULL}")) -HAVE_GIT = (Dir.entries(Dir.pwd).include?('.git') and - system("git --version 2>&1 > #{DEV_NULL}")) - -# Add bones as a development dependency -# -if HAVE_BONES - PROJ.gem.development_dependencies << ['bones', ">= #{Bones::VERSION}"] -end - -# Reads a file at +path+ and spits out an array of the +paragraphs+ -# specified. -# -# changes = paragraphs_of('History.txt', 0..1).join("\n\n") -# summary, *description = paragraphs_of('README.txt', 3, 3..8) -# -def paragraphs_of( path, *paragraphs ) - title = String === paragraphs.first ? paragraphs.shift : nil - ary = File.read(path).delete("\r").split(/\n\n+/) - - result = if title - tmp, matching = [], false - rgxp = %r/^=+\s*#{Regexp.escape(title)}/i - paragraphs << (0..-1) if paragraphs.empty? - - ary.each do |val| - if val =~ rgxp - break if matching - matching = true - rgxp = %r/^=+/i - elsif matching - tmp << val - end - end - tmp - else ary end - - result.values_at(*paragraphs) -end - -# Adds the given gem _name_ to the current project's dependency list. An -# optional gem _version_ can be given. If omitted, the newest gem version -# will be used. -# -def depend_on( name, version = nil ) - spec = Gem.source_index.find_name(name).last - version = spec.version.to_s if version.nil? and !spec.nil? - - PROJ.gem.dependencies << case version - when nil; [name] - when %r/^\d/; [name, ">= #{version}"] - else [name, version] end -end - -# Adds the given arguments to the include path if they are not already there -# -def ensure_in_path( *args ) - args.each do |path| - path = File.expand_path(path) - $:.unshift(path) if test(?d, path) and not $:.include?(path) - end -end - -# Find a rake task using the task name and remove any description text. This -# will prevent the task from being displayed in the list of available tasks. -# -def remove_desc_for_task( names ) - Array(names).each do |task_name| - task = Rake.application.tasks.find {|t| t.name == task_name} - next if task.nil? - task.instance_variable_set :@comment, nil - end -end - -# Change working directories to _dir_, call the _block_ of code, and then -# change back to the original working directory (the current directory when -# this method was called). -# -def in_directory( dir, &block ) - curdir = pwd - begin - cd dir - return block.call - ensure - cd curdir - end -end - -# Scans the current working directory and creates a list of files that are -# candidates to be in the manifest. -# -def manifest - files = [] - exclude = PROJ.exclude.dup - comment = %r/^\s*#/ - - # process the ignore file and add the items there to the exclude list - if test(?f, PROJ.ignore_file) - ary = [] - File.readlines(PROJ.ignore_file).each do |line| - next if line =~ comment - line.chomp! - line.strip! - next if line.nil? or line.empty? - - glob = line =~ %r/\*\./ ? File.join('**', line) : line - Dir.glob(glob).each {|fn| ary << "^#{Regexp.escape(fn)}"} - end - exclude.concat ary - end - - # generate a regular expression from the exclude list - exclude = Regexp.new(exclude.join('|')) - - Find.find '.' do |path| - path.sub! %r/^(\.\/|\/)/o, '' - next unless test ?f, path - next if path =~ exclude - files << path - end - files.sort! -end - -# We need a "valid" method thtat determines if a string is suitable for use -# in the gem specification. -# -class Object - def valid? - return !(self.empty? or self == "\000") if self.respond_to?(:to_str) - return false - end -end - -# EOF diff --git a/pkg/turnstile-0.0.4/tasks/spec.rake b/pkg/turnstile-0.0.4/tasks/spec.rake deleted file mode 100644 index 103acf6..0000000 --- a/pkg/turnstile-0.0.4/tasks/spec.rake +++ /dev/null @@ -1,54 +0,0 @@ - -if HAVE_SPEC_RAKE_SPECTASK and not PROJ.spec.files.to_a.empty? -require 'spec/rake/verify_rcov' - -namespace :spec do - - desc 'Run all specs with basic output' - Spec::Rake::SpecTask.new(:run) do |t| - t.ruby_opts = PROJ.ruby_opts - t.spec_opts = PROJ.spec.opts - t.spec_files = PROJ.spec.files - t.libs += PROJ.libs - end - - desc 'Run all specs with text output' - Spec::Rake::SpecTask.new(:specdoc) do |t| - t.ruby_opts = PROJ.ruby_opts - t.spec_opts = PROJ.spec.opts + ['--format', 'specdoc'] - t.spec_files = PROJ.spec.files - t.libs += PROJ.libs - end - - if HAVE_RCOV - desc 'Run all specs with RCov' - Spec::Rake::SpecTask.new(:rcov) do |t| - t.ruby_opts = PROJ.ruby_opts - t.spec_opts = PROJ.spec.opts - t.spec_files = PROJ.spec.files - t.libs += PROJ.libs - t.rcov = true - t.rcov_dir = PROJ.rcov.dir - t.rcov_opts = PROJ.rcov.opts + ['--exclude', 'spec'] - end - - RCov::VerifyTask.new(:verify) do |t| - t.threshold = PROJ.rcov.threshold - t.index_html = File.join(PROJ.rcov.dir, 'index.html') - t.require_exact_threshold = PROJ.rcov.threshold_exact - end - - task :verify => :rcov - remove_desc_for_task %w(spec:clobber_rcov) - end - -end # namespace :spec - -desc 'Alias to spec:run' -task :spec => 'spec:run' - -task :clobber => 'spec:clobber_rcov' if HAVE_RCOV - -end # if HAVE_SPEC_RAKE_SPECTASK - -# EOF diff --git a/pkg/turnstile-0.0.4/tasks/svn.rake b/pkg/turnstile-0.0.4/tasks/svn.rake deleted file mode 100644 index c186cc6..0000000 --- a/pkg/turnstile-0.0.4/tasks/svn.rake +++ /dev/null @@ -1,47 +0,0 @@ - -if HAVE_SVN - -unless PROJ.svn.root - info = %x/svn info ./ - m = %r/^Repository Root:\s+(.*)$/.match(info) - PROJ.svn.root = (m.nil? ? '' : m[1]) -end -PROJ.svn.root = File.join(PROJ.svn.root, PROJ.svn.path) unless PROJ.svn.path.empty? - -namespace :svn do - - # A prerequisites task that all other tasks depend upon - task :prereqs - - desc 'Show tags from the SVN repository' - task :show_tags => 'svn:prereqs' do |t| - tags = %x/svn list #{File.join(PROJ.svn.root, PROJ.svn.tags)}/ - tags.gsub!(%r/\/$/, '') - tags = tags.split("\n").sort {|a,b| b <=> a} - puts tags - end - - desc 'Create a new tag in the SVN repository' - task :create_tag => 'svn:prereqs' do |t| - v = ENV['VERSION'] or abort 'Must supply VERSION=x.y.z' - abort "Versions don't match #{v} vs #{PROJ.version}" if v != PROJ.version - - svn = PROJ.svn - trunk = File.join(svn.root, svn.trunk) - tag = "%s-%s" % [PROJ.name, PROJ.version] - tag = File.join(svn.root, svn.tags, tag) - msg = "Creating tag for #{PROJ.name} version #{PROJ.version}" - - puts "Creating SVN tag '#{tag}'" - unless system "svn cp -m '#{msg}' #{trunk} #{tag}" - abort "Tag creation failed" - end - end - -end # namespace :svn - -task 'gem:release' => 'svn:create_tag' - -end # if PROJ.svn.path - -# EOF diff --git a/pkg/turnstile-0.0.4/tasks/test.rake b/pkg/turnstile-0.0.4/tasks/test.rake deleted file mode 100644 index 4123f9a..0000000 --- a/pkg/turnstile-0.0.4/tasks/test.rake +++ /dev/null @@ -1,40 +0,0 @@ - -if test(?e, PROJ.test.file) or not PROJ.test.files.to_a.empty? -require 'rake/testtask' - -namespace :test do - - Rake::TestTask.new(:run) do |t| - t.libs = PROJ.libs - t.test_files = if test(?f, PROJ.test.file) then [PROJ.test.file] - else PROJ.test.files end - t.ruby_opts += PROJ.ruby_opts - t.ruby_opts += PROJ.test.opts - end - - if HAVE_RCOV - desc 'Run rcov on the unit tests' - task :rcov => :clobber_rcov do - opts = PROJ.rcov.opts.dup << '-o' << PROJ.rcov.dir - opts = opts.join(' ') - files = if test(?f, PROJ.test.file) then [PROJ.test.file] - else PROJ.test.files end - files = files.join(' ') - sh "#{RCOV} #{files} #{opts}" - end - - task :clobber_rcov do - rm_r 'coverage' rescue nil - end - end - -end # namespace :test - -desc 'Alias to test:run' -task :test => 'test:run' - -task :clobber => 'test:clobber_rcov' if HAVE_RCOV - -end - -# EOF diff --git a/pkg/turnstile-0.0.4/tasks/zentest.rake b/pkg/turnstile-0.0.4/tasks/zentest.rake deleted file mode 100644 index 7ccfd82..0000000 --- a/pkg/turnstile-0.0.4/tasks/zentest.rake +++ /dev/null @@ -1,36 +0,0 @@ -if HAVE_ZENTEST - -# -------------------------------------------------------------------------- -if test(?e, PROJ.test.file) or not PROJ.test.files.to_a.empty? -require 'autotest' - -namespace :test do - task :autotest do - Autotest.run - end -end - -desc "Run the autotest loop" -task :autotest => 'test:autotest' - -end # if test - -# -------------------------------------------------------------------------- -if HAVE_SPEC_RAKE_SPECTASK and not PROJ.spec.files.to_a.empty? -require 'autotest/rspec' - -namespace :spec do - task :autotest do - load '.autotest' if test(?f, '.autotest') - Autotest::Rspec.run - end -end - -desc "Run the autotest loop" -task :autotest => 'spec:autotest' - -end # if rspec - -end # if HAVE_ZENTEST - -# EOF diff --git a/pkg/turnstile-0.0.4/test/test_turnstile.rb b/pkg/turnstile-0.0.4/test/test_turnstile.rb deleted file mode 100644 index e69de29..0000000 diff --git a/pkg/turnstile-0.0.5.gem b/pkg/turnstile-0.0.5.gem deleted file mode 100644 index 22b8e08..0000000 Binary files a/pkg/turnstile-0.0.5.gem and /dev/null differ diff --git a/pkg/turnstile-0.0.5.tgz b/pkg/turnstile-0.0.5.tgz deleted file mode 100644 index 2c47c73..0000000 Binary files a/pkg/turnstile-0.0.5.tgz and /dev/null differ diff --git a/pkg/turnstile-0.0.5/History.txt b/pkg/turnstile-0.0.5/History.txt deleted file mode 100644 index 2cb38ba..0000000 --- a/pkg/turnstile-0.0.5/History.txt +++ /dev/null @@ -1,3 +0,0 @@ -== 0.0.5 / 2009-08-19 - -* Fixed the README.txt. \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/README.txt b/pkg/turnstile-0.0.5/README.txt deleted file mode 100644 index bcb57b8..0000000 --- a/pkg/turnstile-0.0.5/README.txt +++ /dev/null @@ -1,98 +0,0 @@ -turnstile - by Roger Jungemann - http://thefifthcircuit.com/ - -== DESCRIPTION: - -Turnstile is meant to be a flexible authentication and authorization system for Ruby. Currently it is merely a set of "model" classes, although I will shortly release a set of Rack middleware and an HTTP client library which will allow one to create providers, consumers, and clients which are available to Rails apps (or any Rack-compatible app for that matter), for a modest "single sign-on" solution. - -Turnstile is built on Moneta, which is a hot-swappable interface for various key-value stores. Moneta uses SDBM as its data-store by default, but it can also use Tokyo Cabinet, Redis, or even SQL-based sources, thanks to the DataMapper Moneta wrapper. - -== FEATURES/PROBLEMS: - -* Tests are glaringly missing. -* I need to add in my set of Rack middleware for creating providers, consumers, and clients. I have a mostly completed set of code for these. -* I am considering OAuth and/or OpenID support for my provider, consumer, and client, which could be useful for different aspects of turnstile. - -== SYNOPSIS: - -To get started, try typing in `turnstile` in your terminal. This will open a prompt allowing one to interact with the turnstile database. Let's first try and create a role. A role is a collection of limited rights for a particular resource. For example, a web application with a "/treasures" url might want to limit access to that resource to only a small set of users. For example: - - Role.create "king", "/", "/treasures" - Role.create "hero", "/" - Role.create "damsel", "/" - -Next, let's create a realm. A realm is a collection of resources which need to be authorized and authenticated. Let's create a realm called `magical_kingdom` and associate some roles with it. - - realm = "magical_kingdom" - - Realm.create realm, "king", "hero", "damsel" - -Next, let's try actually creating a user. - - name, password = "mickey", "mouse" - - user = User.create "mickey" - user.add_realm realm, password - user.add_role realm, "hero" - -Now, the important part. How does one sign in a user? How does one keep track of signedin users? Here's how to signin a user: - - user.signin realm, password - -Once a user is signed in, the `uuid` method will give a value which can be freely given to the user. The user can later be looked up by turnstile just by using the uuid for that user's session. - - uuid = user.uuid realm - - user = User.from_uuid uuid - -You can also see if a user is signed into a realm, or sign them out. - - user.signedin? realm - user.signout realm - -== REQUIREMENTS: - -* Moneta, uuid, and andand gems - -== INSTALL: - - gem sources -a http://gems.github.com - sudo gem install thefifthcircuit-turnstile - -To use, either type `turnstile` into your terminal, or create a new text file, type in - - require 'rubygems' - require 'turnstile' - - $t = Turnstile::Model::Turnstile.new # create and instantiate database - Turnstile::Model::Turnstile.init # setup database with default values - - include Turnstile::Model - - User.create "minnie" - -== LICENSE: - -(The MIT License) - -Copyright (c) 2008 FIXME (different license?) - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/pkg/turnstile-0.0.5/Rakefile b/pkg/turnstile-0.0.5/Rakefile deleted file mode 100644 index 7f28170..0000000 --- a/pkg/turnstile-0.0.5/Rakefile +++ /dev/null @@ -1,34 +0,0 @@ -# Look in the tasks/setup.rb file for the various options that can be -# configured in this Rakefile. The .rake files in the tasks directory -# are where the options are used. - -begin - require 'bones' - Bones.setup -rescue LoadError - begin - load 'tasks/setup.rb' - rescue LoadError - raise RuntimeError, '### please install the "bones" gem ###' - end -end - -ensure_in_path 'lib' -require 'turnstile' - -task :default => 'spec:run' - -PROJ.name = 'turnstile' -PROJ.authors = 'Roger Jungemann' -PROJ.email = '[email protected]' -PROJ.url = 'http://thefifthcircuit.com' -PROJ.version = Turnstile::VERSION -PROJ.rubyforge.name = 'turnstile' - -PROJ.spec.opts << '--color' - -depend_on 'moneta' -depend_on 'uuid' -depend_on 'andand' - -# EOF diff --git a/pkg/turnstile-0.0.5/bin/turnstile b/pkg/turnstile-0.0.5/bin/turnstile deleted file mode 100755 index 03dd24c..0000000 --- a/pkg/turnstile-0.0.5/bin/turnstile +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh - -irb -rturnstile \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile.rb b/pkg/turnstile-0.0.5/lib/turnstile.rb deleted file mode 100644 index 3b73b14..0000000 --- a/pkg/turnstile-0.0.5/lib/turnstile.rb +++ /dev/null @@ -1,48 +0,0 @@ -module Turnstile - - # :stopdoc: - VERSION = '0.0.5' - LIBPATH = ::File.expand_path(::File.dirname(__FILE__)) + ::File::SEPARATOR - PATH = ::File.dirname(LIBPATH) + ::File::SEPARATOR - # :startdoc: - - # Returns the version string for the library. - # - def self.version - VERSION - end - - # Returns the library path for the module. If any arguments are given, - # they will be joined to the end of the libray path using - # <tt>File.join</tt>. - # - def self.libpath( *args ) - args.empty? ? LIBPATH : ::File.join(LIBPATH, args.flatten) - end - - # Returns the lpath for the module. If any arguments are given, - # they will be joined to the end of the path using - # <tt>File.join</tt>. - # - def self.path( *args ) - args.empty? ? PATH : ::File.join(PATH, args.flatten) - end - - # Utility method used to require all files ending in .rb that lie in the - # directory below this file that has the same name as the filename passed - # in. Optionally, a specific _directory_ name can be passed in such that - # the _filename_ does not have to be equivalent to the directory. - # - def self.require_all_libs_relative_to( fname, dir = nil ) - dir ||= ::File.basename(fname, '.*') - search_me = ::File.expand_path( - ::File.join(::File.dirname(fname), dir, '**', '*.rb')) - - Dir.glob(search_me).sort.each {|rb| require rb} - end - -end # module Turnstile - -Turnstile.require_all_libs_relative_to(__FILE__) - -# EOF diff --git a/pkg/turnstile-0.0.5/lib/turnstile/init.rb b/pkg/turnstile-0.0.5/lib/turnstile/init.rb deleted file mode 100644 index 29e5700..0000000 --- a/pkg/turnstile-0.0.5/lib/turnstile/init.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'rubygems' -require 'uuid' - -dir = File.dirname(__FILE__) - -require "#{dir}/utils/generate" -require "#{dir}/model/turnstile" -require "#{dir}/model/user" -require "#{dir}/model/realm" -require "#{dir}/model/role" - -$t = Turnstile::Model::Turnstile.new -Turnstile::Model::Turnstile.init \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile/model/modules/authenticable.rb b/pkg/turnstile-0.0.5/lib/turnstile/model/modules/authenticable.rb deleted file mode 100644 index c37cb76..0000000 --- a/pkg/turnstile-0.0.5/lib/turnstile/model/modules/authenticable.rb +++ /dev/null @@ -1,74 +0,0 @@ -module Turnstile - module Model - module Modules - module Authenticable - module ClassMethods - def signin(realm, name, password) - raise "No name was provided." if name.nil? - raise "No password was provided." if password.nil? - raise "No realm was provided." if realm.nil? - - user = User.find name - - if user.nil? - return nil - else - raise "User isn't part of realm." if not user.in_realm?(realm) - raise "Wrong password was provided." if !user.check_password(realm, password) - - uuid = Generate.uuid - - user.set_uuid uuid, realm - - return user - end - end - - def from_uuid(uuid) - raise "No uuid was provided." if uuid.nil? - - uuids = $t.db["uuids"] - - name, realm = uuids[uuid][:name], uuids[uuid][:realm] - - user = User.find name - - user.in_realm?(realm) ? user : nil - end - end - - def signout(realm) - raise "No realm was provided." if realm.nil? - raise "User isn't part of realm." if not in_realm?(realm) - - set_uuid nil, realm - - nil - end - - def signedin?(realm) - $t.db["user-#{@name}"][:realms][realm].andand[:uuid].nil? ? nil : self - end - - def uuid(realm) - $t.db["user-#{@name}"][:realms][realm][:uuid] - end - - def set_uuid(uuid, realm) - uuids = $t.db["uuids"] - uuids[uuid] = { :name => self.name, :realm => realm } - $t.db["uuids"] = uuids - - $t.transact("user-#{@name}") do |u| - u[:realms][realm][:uuid] = uuid - u - end - end - - def self.included(base) - base.extend ClassMethods - end - end - end - end -end \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile/model/modules/authorizable.rb b/pkg/turnstile-0.0.5/lib/turnstile/model/modules/authorizable.rb deleted file mode 100644 index 700445f..0000000 --- a/pkg/turnstile-0.0.5/lib/turnstile/model/modules/authorizable.rb +++ /dev/null @@ -1,61 +0,0 @@ -module Turnstile - module Model - module Modules - module Authorizable - def authorized? realm, role - columns = $t.db["user-#{@name}"] - - raise "User isn't part of realm." if columns[:realms][realm].nil? - - columns[:realms][realm][:roles].include? role - end - - def add_role realm, role - raise "Role doesn't exist." if Role.find(role).nil? - raise "User isn't part of realm." unless in_realm?(realm) - - columns = $t.db["user-#{@name}"] - roles = columns[:realms][realm][:roles] - - raise "User already has this role." if roles.include? role - - roles << role - - columns[:realms][realm][:roles] = roles - - $t.db["user-#{@name}"] = columns - end - - def remove_role realm, role - raise "Role doesn't exist." if Role.find(role).nil? - raise "User isn't part of realm." unless in_realm?(realm) - - columns = $t.db["user-#{@name}"] - roles = columns[:realms][realm][:roles] - - raise "User doesn't have this role." if not roles.include? role - - roles.reject! { |r| r == role } - - columns[:realms][realm][:roles] = roles - - $t.db["user-#{@name}"] = columns - end - - def roles realm - columns = $t.db["user-#{@name}"] - - raise "User isn't part of realm" unless in_realm?(realm) - - columns[:realms][realm][:roles] - end - - def has_right? realm, right - not roles(realm).reject { |role| - not Role.find(role).has_right? role - }.empty? - end - end - end - end -end \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile/model/modules/manageable.rb b/pkg/turnstile-0.0.5/lib/turnstile/model/modules/manageable.rb deleted file mode 100644 index 9c0c740..0000000 --- a/pkg/turnstile-0.0.5/lib/turnstile/model/modules/manageable.rb +++ /dev/null @@ -1,125 +0,0 @@ -require 'andand' - -module Turnstile - module Model - module Modules - module Manageable - module ClassMethods - def find name - $t.db.has_key?("user-#{name}") ? User.new(name) : nil - end - - def create name - raise "No name was provided." if name.nil? - - $t.transact("user-#{name}") do |user| - raise "User already exists" unless user.empty? - - { :name => name, :realms => {}, :created_on => Time.now } - end - - User.new name - end - - def exists? name - !User.find(name).nil? - end - - def users - $t.db.keys.reject { |k| not k.match(/user-.*/) }.collect { |k| k[5..-1] } - end - - def realms - $t.db["realms"].andand.keys - end - end - - def add_realm realm, password - raise "No password was provided." if password.nil? - raise "No realm was provided." if realm.nil? - raise "Realm doesn't exist." if Realm.find(realm).nil? - - columns = $t.db["user-#{@name}"] - - salt = Generate.salt - - raise "User is already part of this realm." if not columns[:realms][realm].nil? - - columns[:realms][realm] = { :roles => [] } - columns[:realms][realm][:salt] = salt - columns[:realms][realm][:hash] = Generate.hash(salt, password) - - $t.db["user-#{name}"] = columns - - self - end - - def remove_realm realm - raise "No realm was provided." if realm.nil? - raise "Realm doesn't exist." if Realm.find(realm).nil? - - columns = $t.db["user-#{@name}"] - - raise "User isn't part of realm." if not in_realm?(realm) - - columns[:realms].delete realm - - $t.db["user-#{name}"] = columns - - self - end - - def in_realm? realm - !$t.db["user-#{@name}"][:realms][realm].nil? - end - - def change_password realm, password - raise "No password was provided." if password.nil? - raise "No realm was provided." if realm.nil? - - columns = $t.db["user-#{@name}"] - - raise "User isn't part of realm." if not in_realm?(realm) - - salt = Generate.salt - - columns[:realms][realm][:salt] = salt - columns[:realms][realm][:hash] = Generate.hash(salt, password) - - $t.db["user-#{@name}"] = columns - - self - end - - def check_password realm, password - raise "No password was provided." if password.nil? - raise "No realm was provided." if realm.nil? - - columns = $t.db["user-#{@name}"] - - raise "User isn't part of realm." if not in_realm?(realm) - - hash = Generate.hash(columns[:realms][realm][:salt], password) - - hash == columns[:realms][realm][:hash] - end - - def realms - columns = $t.db["user-#{@name}"][:realms].keys - end - - def destroy - $t.db.delete "user-#{@name}" - - @name = nil - - nil - end - - def self.included(base) - base.extend ClassMethods - end - end - end - end -end \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile/model/realm.rb b/pkg/turnstile-0.0.5/lib/turnstile/model/realm.rb deleted file mode 100644 index 40d3ae5..0000000 --- a/pkg/turnstile-0.0.5/lib/turnstile/model/realm.rb +++ /dev/null @@ -1,77 +0,0 @@ -module Turnstile - module Model - class Realm - attr_reader :name - - def self.init - $t.db["realms"] ||= {} - end - - def initialize name - @name = name - end - - def self.create name, *roles - $t.transact("realms") do |realms| - realms[name] ||= { :roles => roles || [] } - - realms - end - - Realm.new name - end - - def self.find name - $t.db["realms"][name] ? Realm.new(name) : nil - end - - def self.exists? name - !Realm.find(name).nil? - end - - def add_role name - raise "Role hasn't been created yet." unless Role.exists? name - raise "Role already exists in realm." if self.roles.include? name - - $t.transact("realms") do |realms| - realms[@name][:roles] << name - - realms - end - - self - end - - def remove_role name - raise "Role hasn't been created yet." unless Role.exists? name - raise "Role already exists in realm." unless self.roles.include? name - - $t.transact("realms") do |realms| - realms[@name][:roles].reject! { |r| r == name } - - realms - end - - self - end - - def destroy - $t.transact("realms") do |realms| - realms.delete name - - realms - end - - nil - end - - def self.realms - $t.db["realms"] - end - - def roles - $t.db["realms"][@name][:roles] - end - end - end -end \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile/model/role.rb b/pkg/turnstile-0.0.5/lib/turnstile/model/role.rb deleted file mode 100644 index 8dd781c..0000000 --- a/pkg/turnstile-0.0.5/lib/turnstile/model/role.rb +++ /dev/null @@ -1,82 +0,0 @@ -module Turnstile - module Model - class Role - attr_reader :name - - def initialize name - @name = name - end - - def self.init - $t.db["roles"] ||= {} - end - - def self.create name, *rights - rights ||= [] - roles = $t.db["roles"] - - raise "Role already exists." if roles.include? name - - roles[name] = { :rights => rights } - - $t.db["roles"] = roles - - Role.new name - end - - def self.find name - roles = $t.db["roles"] - - roles.include?(name) ? Role.new(name) : nil - end - - def self.exists? name - !$t.db["roles"][name].nil? - end - - def self.roles - $t.db["roles"].keys - end - - def rights - roles = $t.db["roles"] - - roles[@name][:rights] - end - - def has_right? right - rights.include? right - end - - def add_right right - roles = $t.db["roles"] - - rights = roles[@name][:rights] + right - roles[@name][:rights] = rights - - $t.db["roles"] = role - - self - end - - def remove_right right - roles = $t.db["roles"] - - rights = roles[@name][:rights].reject right - roles[@name][:rights] = rights - - $t.db["roles"] = role - - self - end - - def destroy - $t.db["roles"].delete @name - - @name = nil - - nil - end - end - end -end \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile/model/turnstile.rb b/pkg/turnstile-0.0.5/lib/turnstile/model/turnstile.rb deleted file mode 100644 index 8b094e1..0000000 --- a/pkg/turnstile-0.0.5/lib/turnstile/model/turnstile.rb +++ /dev/null @@ -1,28 +0,0 @@ -require 'moneta' -require 'moneta/sdbm' - -module Turnstile - module Model - class Turnstile - attr_reader :db - - def self.init - User.init - Realm.init - Role.init - end - - def initialize(options = {}) - options[:path] ||= File.join(File.dirname(__FILE__), "..", "tmp", "db.sdbm") - options[:moneta_store] ||= Moneta::SDBM - - @db = options[:moneta_store].new(:file => options[:path]) - end - - def transact(key, &block) - item = @db[key] || {} - @db[key] = yield(item) - end - end - end -end \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile/model/user.rb b/pkg/turnstile-0.0.5/lib/turnstile/model/user.rb deleted file mode 100644 index 35b5053..0000000 --- a/pkg/turnstile-0.0.5/lib/turnstile/model/user.rb +++ /dev/null @@ -1,25 +0,0 @@ -dir = File.dirname(__FILE__) - -require "#{dir}/modules/manageable" -require "#{dir}/modules/authenticable" -require "#{dir}/modules/authorizable" - -module Turnstile - module Model - class User - include Modules::Manageable - include Modules::Authenticable - include Modules::Authorizable - - attr_accessor :name - - def self.init - $t.db["uuids"] ||= {} - end - - def initialize(name = nil) - @name = name - end - end - end -end \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm.dir b/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm.dir deleted file mode 100644 index fdcfd81..0000000 Binary files a/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm.dir and /dev/null differ diff --git a/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm.pag b/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm.pag deleted file mode 100644 index ba4cbe4..0000000 Binary files a/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm.pag and /dev/null differ diff --git a/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm_expires.dir b/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm_expires.dir deleted file mode 100644 index e69de29..0000000 diff --git a/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm_expires.pag b/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm_expires.pag deleted file mode 100644 index e69de29..0000000 diff --git a/pkg/turnstile-0.0.5/lib/turnstile/utils/generate.rb b/pkg/turnstile-0.0.5/lib/turnstile/utils/generate.rb deleted file mode 100644 index b26a2ba..0000000 --- a/pkg/turnstile-0.0.5/lib/turnstile/utils/generate.rb +++ /dev/null @@ -1,18 +0,0 @@ -require 'digest/sha2' -require 'uuid' - -class Generate - @@uuid = UUID.new - - def self.salt - [Array.new(6) { rand(256).chr }.join].pack('m').chomp - end - - def self.hash password, salt - Digest::SHA256.hexdigest password + salt - end - - def self.uuid - @@uuid.generate - end -end \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/spec/spec_helper.rb b/pkg/turnstile-0.0.5/spec/spec_helper.rb deleted file mode 100644 index dd2ad9a..0000000 --- a/pkg/turnstile-0.0.5/spec/spec_helper.rb +++ /dev/null @@ -1,16 +0,0 @@ - -require File.expand_path( - File.join(File.dirname(__FILE__), %w[.. lib turnstile])) - -Spec::Runner.configure do |config| - # == Mock Framework - # - # RSpec uses it's own mocking framework by default. If you prefer to - # use mocha, flexmock or RR, uncomment the appropriate line: - # - # config.mock_with :mocha - # config.mock_with :flexmock - # config.mock_with :rr -end - -include Turnstile::Model \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/spec/turnstile_spec.rb b/pkg/turnstile-0.0.5/spec/turnstile_spec.rb deleted file mode 100644 index 9ff5a8c..0000000 --- a/pkg/turnstile-0.0.5/spec/turnstile_spec.rb +++ /dev/null @@ -1,7 +0,0 @@ - -require File.join(File.dirname(__FILE__), %w[spec_helper]) - -describe Turnstile do -end - -# EOF diff --git a/pkg/turnstile-0.0.5/tasks/ann.rake b/pkg/turnstile-0.0.5/tasks/ann.rake deleted file mode 100644 index d07084e..0000000 --- a/pkg/turnstile-0.0.5/tasks/ann.rake +++ /dev/null @@ -1,80 +0,0 @@ - -begin - require 'bones/smtp_tls' -rescue LoadError - require 'net/smtp' -end -require 'time' - -namespace :ann do - - # A prerequisites task that all other tasks depend upon - task :prereqs - - file PROJ.ann.file do - ann = PROJ.ann - puts "Generating #{ann.file}" - File.open(ann.file,'w') do |fd| - fd.puts("#{PROJ.name} version #{PROJ.version}") - fd.puts(" by #{Array(PROJ.authors).first}") if PROJ.authors - fd.puts(" #{PROJ.url}") if PROJ.url.valid? - fd.puts(" (the \"#{PROJ.release_name}\" release)") if PROJ.release_name - fd.puts - fd.puts("== DESCRIPTION") - fd.puts - fd.puts(PROJ.description) - fd.puts - fd.puts(PROJ.changes.sub(%r/^.*$/, '== CHANGES')) - fd.puts - ann.paragraphs.each do |p| - fd.puts "== #{p.upcase}" - fd.puts - fd.puts paragraphs_of(PROJ.readme_file, p).join("\n\n") - fd.puts - end - fd.puts ann.text if ann.text - end - end - - desc "Create an announcement file" - task :announcement => ['ann:prereqs', PROJ.ann.file] - - desc "Send an email announcement" - task :email => ['ann:prereqs', PROJ.ann.file] do - ann = PROJ.ann - from = ann.email[:from] || Array(PROJ.authors).first || PROJ.email - to = Array(ann.email[:to]) - - ### build a mail header for RFC 822 - rfc822msg = "From: #{from}\n" - rfc822msg << "To: #{to.join(',')}\n" - rfc822msg << "Subject: [ANN] #{PROJ.name} #{PROJ.version}" - rfc822msg << " (#{PROJ.release_name})" if PROJ.release_name - rfc822msg << "\n" - rfc822msg << "Date: #{Time.new.rfc822}\n" - rfc822msg << "Message-Id: " - rfc822msg << "<#{"%.8f" % Time.now.to_f}@#{ann.email[:domain]}>\n\n" - rfc822msg << File.read(ann.file) - - params = [:server, :port, :domain, :acct, :passwd, :authtype].map do |key| - ann.email[key] - end - - params[3] = PROJ.email if params[3].nil? - - if params[4].nil? - STDOUT.write "Please enter your e-mail password (#{params[3]}): " - params[4] = STDIN.gets.chomp - end - - ### send email - Net::SMTP.start(*params) {|smtp| smtp.sendmail(rfc822msg, from, to)} - end -end # namespace :ann - -desc 'Alias to ann:announcement' -task :ann => 'ann:announcement' - -CLOBBER << PROJ.ann.file - -# EOF diff --git a/pkg/turnstile-0.0.5/tasks/bones.rake b/pkg/turnstile-0.0.5/tasks/bones.rake deleted file mode 100644 index 2093b03..0000000 --- a/pkg/turnstile-0.0.5/tasks/bones.rake +++ /dev/null @@ -1,20 +0,0 @@ - -if HAVE_BONES - -namespace :bones do - - desc 'Show the PROJ open struct' - task :debug do |t| - atr = if t.application.top_level_tasks.length == 2 - t.application.top_level_tasks.pop - end - - if atr then Bones::Debug.show_attr(PROJ, atr) - else Bones::Debug.show PROJ end - end - -end # namespace :bones - -end # HAVE_BONES - -# EOF diff --git a/pkg/turnstile-0.0.5/tasks/gem.rake b/pkg/turnstile-0.0.5/tasks/gem.rake deleted file mode 100644 index ab68fc1..0000000 --- a/pkg/turnstile-0.0.5/tasks/gem.rake +++ /dev/null @@ -1,201 +0,0 @@ - -require 'find' -require 'rake/packagetask' -require 'rubygems/user_interaction' -require 'rubygems/builder' - -module Bones -class GemPackageTask < Rake::PackageTask - # Ruby GEM spec containing the metadata for this package. The - # name, version and package_files are automatically determined - # from the GEM spec and don't need to be explicitly provided. - # - attr_accessor :gem_spec - - # Tasks from the Bones gem directory - attr_reader :bones_files - - # Create a GEM Package task library. Automatically define the gem - # if a block is given. If no block is supplied, then +define+ - # needs to be called to define the task. - # - def initialize(gem_spec) - init(gem_spec) - yield self if block_given? - define if block_given? - end - - # Initialization tasks without the "yield self" or define - # operations. - # - def init(gem) - super(gem.name, gem.version) - @gem_spec = gem - @package_files += gem_spec.files if gem_spec.files - @bones_files = [] - - local_setup = File.join(Dir.pwd, %w[tasks setup.rb]) - if !test(?e, local_setup) - Dir.glob(::Bones.path(%w[lib bones tasks *])).each {|fn| bones_files << fn} - end - end - - # Create the Rake tasks and actions specified by this - # GemPackageTask. (+define+ is automatically called if a block is - # given to +new+). - # - def define - super - task :prereqs - task :package => ['gem:prereqs', "#{package_dir_path}/#{gem_file}"] - file "#{package_dir_path}/#{gem_file}" => [package_dir_path] + package_files + bones_files do - when_writing("Creating GEM") { - chdir(package_dir_path) do - Gem::Builder.new(gem_spec).build - verbose(true) { - mv gem_file, "../#{gem_file}" - } - end - } - end - - file package_dir_path => bones_files do - mkdir_p package_dir rescue nil - - gem_spec.files = (gem_spec.files + - bones_files.map {|fn| File.join('tasks', File.basename(fn))}).sort - - bones_files.each do |fn| - base_fn = File.join('tasks', File.basename(fn)) - f = File.join(package_dir_path, base_fn) - fdir = File.dirname(f) - mkdir_p(fdir) if !File.exist?(fdir) - if File.directory?(fn) - mkdir_p(f) - else - raise "file name conflict for '#{base_fn}' (conflicts with '#{fn}')" if test(?e, f) - safe_ln(fn, f) - end - end - end - end - - def gem_file - if @gem_spec.platform == Gem::Platform::RUBY - "#{package_name}.gem" - else - "#{package_name}-#{@gem_spec.platform}.gem" - end - end -end # class GemPackageTask -end # module Bones - -namespace :gem do - - PROJ.gem._spec = Gem::Specification.new do |s| - s.name = PROJ.name - s.version = PROJ.version - s.summary = PROJ.summary - s.authors = Array(PROJ.authors) - s.email = PROJ.email - s.homepage = Array(PROJ.url).first - s.rubyforge_project = PROJ.rubyforge.name - - s.description = PROJ.description - - PROJ.gem.dependencies.each do |dep| - s.add_dependency(*dep) - end - - PROJ.gem.development_dependencies.each do |dep| - s.add_development_dependency(*dep) - end - - s.files = PROJ.gem.files - s.executables = PROJ.gem.executables.map {|fn| File.basename(fn)} - s.extensions = PROJ.gem.files.grep %r/extconf\.rb$/ - - s.bindir = 'bin' - dirs = Dir["{#{PROJ.libs.join(',')}}"] - s.require_paths = dirs unless dirs.empty? - - incl = Regexp.new(PROJ.rdoc.include.join('|')) - excl = PROJ.rdoc.exclude.dup.concat %w[\.rb$ ^(\.\/|\/)?ext] - excl = Regexp.new(excl.join('|')) - rdoc_files = PROJ.gem.files.find_all do |fn| - case fn - when excl; false - when incl; true - else false end - end - s.rdoc_options = PROJ.rdoc.opts + ['--main', PROJ.rdoc.main] - s.extra_rdoc_files = rdoc_files - s.has_rdoc = true - - if test ?f, PROJ.test.file - s.test_file = PROJ.test.file - else - s.test_files = PROJ.test.files.to_a - end - - # Do any extra stuff the user wants - PROJ.gem.extras.each do |msg, val| - case val - when Proc - val.call(s.send(msg)) - else - s.send "#{msg}=", val - end - end - end # Gem::Specification.new - - Bones::GemPackageTask.new(PROJ.gem._spec) do |pkg| - pkg.need_tar = PROJ.gem.need_tar - pkg.need_zip = PROJ.gem.need_zip - end - - desc 'Show information about the gem' - task :debug => 'gem:prereqs' do - puts PROJ.gem._spec.to_ruby - end - - desc 'Write the gemspec ' - task :spec => 'gem:prereqs' do - File.open("#{PROJ.name}.gemspec", 'w') do |f| - f.write PROJ.gem._spec.to_ruby - end - end - - desc 'Install the gem' - task :install => [:clobber, 'gem:package'] do - sh "#{SUDO} #{GEM} install --local pkg/#{PROJ.gem._spec.full_name}" - - # use this version of the command for rubygems > 1.0.0 - #sh "#{SUDO} #{GEM} install --no-update-sources pkg/#{PROJ.gem._spec.full_name}" - end - - desc 'Uninstall the gem' - task :uninstall do - installed_list = Gem.source_index.find_name(PROJ.name) - if installed_list and installed_list.collect { |s| s.version.to_s}.include?(PROJ.version) then - sh "#{SUDO} #{GEM} uninstall --version '#{PROJ.version}' --ignore-dependencies --executables #{PROJ.name}" - end - end - - desc 'Reinstall the gem' - task :reinstall => [:uninstall, :install] - - desc 'Cleanup the gem' - task :cleanup do - sh "#{SUDO} #{GEM} cleanup #{PROJ.gem._spec.name}" - end -end # namespace :gem - - -desc 'Alias to gem:package' -task :gem => 'gem:package' - -task :clobber => 'gem:clobber_package' -remove_desc_for_task 'gem:clobber_package' - -# EOF diff --git a/pkg/turnstile-0.0.5/tasks/git.rake b/pkg/turnstile-0.0.5/tasks/git.rake deleted file mode 100644 index 4f9194b..0000000 --- a/pkg/turnstile-0.0.5/tasks/git.rake +++ /dev/null @@ -1,40 +0,0 @@ - -if HAVE_GIT - -namespace :git do - - # A prerequisites task that all other tasks depend upon - task :prereqs - - desc 'Show tags from the Git repository' - task :show_tags => 'git:prereqs' do |t| - puts %x/git tag/ - end - - desc 'Create a new tag in the Git repository' - task :create_tag => 'git:prereqs' do |t| - v = ENV['VERSION'] or abort 'Must supply VERSION=x.y.z' - abort "Versions don't match #{v} vs #{PROJ.version}" if v != PROJ.version - - tag = "%s-%s" % [PROJ.name, PROJ.version] - msg = "Creating tag for #{PROJ.name} version #{PROJ.version}" - - puts "Creating Git tag '#{tag}'" - unless system "git tag -a -m '#{msg}' #{tag}" - abort "Tag creation failed" - end - - if %x/git remote/ =~ %r/^origin\s*$/ - unless system "git push origin #{tag}" - abort "Could not push tag to remote Git repository" - end - end - end - -end # namespace :git - -task 'gem:release' => 'git:create_tag' - -end # if HAVE_GIT - -# EOF diff --git a/pkg/turnstile-0.0.5/tasks/notes.rake b/pkg/turnstile-0.0.5/tasks/notes.rake deleted file mode 100644 index 5360dfa..0000000 --- a/pkg/turnstile-0.0.5/tasks/notes.rake +++ /dev/null @@ -1,27 +0,0 @@ - -if HAVE_BONES - -desc "Enumerate all annotations" -task :notes do |t| - id = if t.application.top_level_tasks.length > 1 - t.application.top_level_tasks.slice!(1..-1).join(' ') - end - Bones::AnnotationExtractor.enumerate( - PROJ, PROJ.notes.tags.join('|'), id, :tag => true) -end - -namespace :notes do - PROJ.notes.tags.each do |tag| - desc "Enumerate all #{tag} annotations" - task tag.downcase.to_sym do |t| - id = if t.application.top_level_tasks.length > 1 - t.application.top_level_tasks.slice!(1..-1).join(' ') - end - Bones::AnnotationExtractor.enumerate(PROJ, tag, id) - end - end -end - -end # if HAVE_BONES - -# EOF diff --git a/pkg/turnstile-0.0.5/tasks/post_load.rake b/pkg/turnstile-0.0.5/tasks/post_load.rake deleted file mode 100644 index 3ec82d1..0000000 --- a/pkg/turnstile-0.0.5/tasks/post_load.rake +++ /dev/null @@ -1,34 +0,0 @@ - -# This file does not define any rake tasks. It is used to load some project -# settings if they are not defined by the user. - -PROJ.exclude << ["^#{Regexp.escape(PROJ.ann.file)}$", - "^#{Regexp.escape(PROJ.ignore_file)}$", - "^#{Regexp.escape(PROJ.rdoc.dir)}/", - "^#{Regexp.escape(PROJ.rcov.dir)}/"] - -flatten_arrays = lambda do |this,os| - os.instance_variable_get(:@table).each do |key,val| - next if key == :dependencies \ - or key == :development_dependencies - case val - when Array; val.flatten! - when OpenStruct; this.call(this,val) - end - end - end -flatten_arrays.call(flatten_arrays,PROJ) - -PROJ.changes ||= paragraphs_of(PROJ.history_file, 0..1).join("\n\n") - -PROJ.description ||= paragraphs_of(PROJ.readme_file, 'description').join("\n\n") - -PROJ.summary ||= PROJ.description.split('.').first - -PROJ.gem.files ||= manifest - -PROJ.gem.executables ||= PROJ.gem.files.find_all {|fn| fn =~ %r/^bin/} - -PROJ.rdoc.main ||= PROJ.readme_file - -# EOF diff --git a/pkg/turnstile-0.0.5/tasks/rdoc.rake b/pkg/turnstile-0.0.5/tasks/rdoc.rake deleted file mode 100644 index edbb804..0000000 --- a/pkg/turnstile-0.0.5/tasks/rdoc.rake +++ /dev/null @@ -1,51 +0,0 @@ - -require 'rake/rdoctask' - -namespace :doc do - - desc 'Generate RDoc documentation' - Rake::RDocTask.new do |rd| - rdoc = PROJ.rdoc - rd.main = rdoc.main - rd.rdoc_dir = rdoc.dir - - incl = Regexp.new(rdoc.include.join('|')) - excl = Regexp.new(rdoc.exclude.join('|')) - files = PROJ.gem.files.find_all do |fn| - case fn - when excl; false - when incl; true - else false end - end - rd.rdoc_files.push(*files) - - name = PROJ.name - rf_name = PROJ.rubyforge.name - - title = "#{name}-#{PROJ.version} Documentation" - title = "#{rf_name}'s " + title if rf_name.valid? and rf_name != name - - rd.options << "-t #{title}" - rd.options.concat(rdoc.opts) - end - - desc 'Generate ri locally for testing' - task :ri => :clobber_ri do - sh "#{RDOC} --ri -o ri ." - end - - task :clobber_ri do - rm_r 'ri' rescue nil - end - -end # namespace :doc - -desc 'Alias to doc:rdoc' -task :doc => 'doc:rdoc' - -desc 'Remove all build products' -task :clobber => %w(doc:clobber_rdoc doc:clobber_ri) - -remove_desc_for_task %w(doc:clobber_rdoc) - -# EOF diff --git a/pkg/turnstile-0.0.5/tasks/rubyforge.rake b/pkg/turnstile-0.0.5/tasks/rubyforge.rake deleted file mode 100644 index 87b3d31..0000000 --- a/pkg/turnstile-0.0.5/tasks/rubyforge.rake +++ /dev/null @@ -1,55 +0,0 @@ - -if PROJ.rubyforge.name.valid? && HAVE_RUBYFORGE - -require 'rubyforge' -require 'rake/contrib/sshpublisher' - -namespace :gem do - desc 'Package and upload to RubyForge' - task :release => [:clobber, 'gem'] do |t| - v = ENV['VERSION'] or abort 'Must supply VERSION=x.y.z' - abort "Versions don't match #{v} vs #{PROJ.version}" if v != PROJ.version - pkg = "pkg/#{PROJ.gem._spec.full_name}" - - if $DEBUG then - puts "release_id = rf.add_release #{PROJ.rubyforge.name.inspect}, #{PROJ.name.inspect}, #{PROJ.version.inspect}, \"#{pkg}.tgz\"" - puts "rf.add_file #{PROJ.rubyforge.name.inspect}, #{PROJ.name.inspect}, release_id, \"#{pkg}.gem\"" - end - - rf = RubyForge.new - rf.configure rescue nil - puts 'Logging in' - rf.login - - c = rf.userconfig - c['release_notes'] = PROJ.description if PROJ.description - c['release_changes'] = PROJ.changes if PROJ.changes - c['preformatted'] = true - - files = Dir.glob("#{pkg}*.*") - - puts "Releasing #{PROJ.name} v. #{PROJ.version}" - rf.add_release PROJ.rubyforge.name, PROJ.name, PROJ.version, *files - end -end # namespace :gem - - -namespace :doc do - desc "Publish RDoc to RubyForge" - task :release => %w(doc:clobber_rdoc doc:rdoc) do - config = YAML.load( - File.read(File.expand_path('~/.rubyforge/user-config.yml')) - ) - - host = "#{config['username']}@rubyforge.org" - remote_dir = "/var/www/gforge-projects/#{PROJ.rubyforge.name}/" - remote_dir << PROJ.rdoc.remote_dir if PROJ.rdoc.remote_dir - local_dir = PROJ.rdoc.dir - - Rake::SshDirPublisher.new(host, remote_dir, local_dir).upload - end -end # namespace :doc - -end # if HAVE_RUBYFORGE - -# EOF diff --git a/pkg/turnstile-0.0.5/tasks/setup.rb b/pkg/turnstile-0.0.5/tasks/setup.rb deleted file mode 100644 index a752385..0000000 --- a/pkg/turnstile-0.0.5/tasks/setup.rb +++ /dev/null @@ -1,292 +0,0 @@ - -require 'rubygems' -require 'rake' -require 'rake/clean' -require 'fileutils' -require 'ostruct' -require 'find' - -class OpenStruct; undef :gem if defined? :gem; end - -# TODO: make my own openstruct type object that includes descriptions -# TODO: use the descriptions to output help on the available bones options - -PROJ = OpenStruct.new( - # Project Defaults - :name => nil, - :summary => nil, - :description => nil, - :changes => nil, - :authors => nil, - :email => nil, - :url => "\000", - :version => ENV['VERSION'] || '0.0.0', - :exclude => %w(tmp$ bak$ ~$ CVS \.svn/ \.git/ ^pkg/), - :release_name => ENV['RELEASE'], - - # System Defaults - :ruby_opts => %w(-w), - :libs => [], - :history_file => 'History.txt', - :readme_file => 'README.txt', - :ignore_file => '.bnsignore', - - # Announce - :ann => OpenStruct.new( - :file => 'announcement.txt', - :text => nil, - :paragraphs => [], - :email => { - :from => nil, - :to => %w([email protected]), - :server => 'localhost', - :port => 25, - :domain => ENV['HOSTNAME'], - :acct => nil, - :passwd => nil, - :authtype => :plain - } - ), - - # Gem Packaging - :gem => OpenStruct.new( - :dependencies => [], - :development_dependencies => [], - :executables => nil, - :extensions => FileList['ext/**/extconf.rb'], - :files => nil, - :need_tar => true, - :need_zip => false, - :extras => {} - ), - - # File Annotations - :notes => OpenStruct.new( - :exclude => %w(^tasks/setup\.rb$), - :extensions => %w(.txt .rb .erb .rdoc) << '', - :tags => %w(FIXME OPTIMIZE TODO) - ), - - # Rcov - :rcov => OpenStruct.new( - :dir => 'coverage', - :opts => %w[--sort coverage -T], - :threshold => 90.0, - :threshold_exact => false - ), - - # Rdoc - :rdoc => OpenStruct.new( - :opts => [], - :include => %w(^lib/ ^bin/ ^ext/ \.txt$ \.rdoc$), - :exclude => %w(extconf\.rb$), - :main => nil, - :dir => 'doc', - :remote_dir => nil - ), - - # Rubyforge - :rubyforge => OpenStruct.new( - :name => "\000" - ), - - # Rspec - :spec => OpenStruct.new( - :files => FileList['spec/**/*_spec.rb'], - :opts => [] - ), - - # Subversion Repository - :svn => OpenStruct.new( - :root => nil, - :path => '', - :trunk => 'trunk', - :tags => 'tags', - :branches => 'branches' - ), - - # Test::Unit - :test => OpenStruct.new( - :files => FileList['test/**/test_*.rb'], - :file => 'test/all.rb', - :opts => [] - ) -) - -# Load the other rake files in the tasks folder -tasks_dir = File.expand_path(File.dirname(__FILE__)) -post_load_fn = File.join(tasks_dir, 'post_load.rake') -rakefiles = Dir.glob(File.join(tasks_dir, '*.rake')).sort -rakefiles.unshift(rakefiles.delete(post_load_fn)).compact! -import(*rakefiles) - -# Setup the project libraries -%w(lib ext).each {|dir| PROJ.libs << dir if test ?d, dir} - -# Setup some constants -DEV_NULL = File.exist?('/dev/null') ? '/dev/null' : 'NUL:' - -def quiet( &block ) - io = [STDOUT.dup, STDERR.dup] - STDOUT.reopen DEV_NULL - STDERR.reopen DEV_NULL - block.call -ensure - STDOUT.reopen io.first - STDERR.reopen io.last - $stdout, $stderr = STDOUT, STDERR -end - -DIFF = if system("gdiff '#{__FILE__}' '#{__FILE__}' > #{DEV_NULL} 2>&1") then 'gdiff' - else 'diff' end unless defined? DIFF - -SUDO = if system("which sudo > #{DEV_NULL} 2>&1") then 'sudo' - else '' end unless defined? SUDO - -RCOV = "#{RUBY} -S rcov" -RDOC = "#{RUBY} -S rdoc" -GEM = "#{RUBY} -S gem" - -%w(rcov spec/rake/spectask rubyforge bones facets/ansicode zentest).each do |lib| - begin - require lib - Object.instance_eval {const_set "HAVE_#{lib.tr('/','_').upcase}", true} - rescue LoadError - Object.instance_eval {const_set "HAVE_#{lib.tr('/','_').upcase}", false} - end -end -HAVE_SVN = (Dir.entries(Dir.pwd).include?('.svn') and - system("svn --version 2>&1 > #{DEV_NULL}")) -HAVE_GIT = (Dir.entries(Dir.pwd).include?('.git') and - system("git --version 2>&1 > #{DEV_NULL}")) - -# Add bones as a development dependency -# -if HAVE_BONES - PROJ.gem.development_dependencies << ['bones', ">= #{Bones::VERSION}"] -end - -# Reads a file at +path+ and spits out an array of the +paragraphs+ -# specified. -# -# changes = paragraphs_of('History.txt', 0..1).join("\n\n") -# summary, *description = paragraphs_of('README.txt', 3, 3..8) -# -def paragraphs_of( path, *paragraphs ) - title = String === paragraphs.first ? paragraphs.shift : nil - ary = File.read(path).delete("\r").split(/\n\n+/) - - result = if title - tmp, matching = [], false - rgxp = %r/^=+\s*#{Regexp.escape(title)}/i - paragraphs << (0..-1) if paragraphs.empty? - - ary.each do |val| - if val =~ rgxp - break if matching - matching = true - rgxp = %r/^=+/i - elsif matching - tmp << val - end - end - tmp - else ary end - - result.values_at(*paragraphs) -end - -# Adds the given gem _name_ to the current project's dependency list. An -# optional gem _version_ can be given. If omitted, the newest gem version -# will be used. -# -def depend_on( name, version = nil ) - spec = Gem.source_index.find_name(name).last - version = spec.version.to_s if version.nil? and !spec.nil? - - PROJ.gem.dependencies << case version - when nil; [name] - when %r/^\d/; [name, ">= #{version}"] - else [name, version] end -end - -# Adds the given arguments to the include path if they are not already there -# -def ensure_in_path( *args ) - args.each do |path| - path = File.expand_path(path) - $:.unshift(path) if test(?d, path) and not $:.include?(path) - end -end - -# Find a rake task using the task name and remove any description text. This -# will prevent the task from being displayed in the list of available tasks. -# -def remove_desc_for_task( names ) - Array(names).each do |task_name| - task = Rake.application.tasks.find {|t| t.name == task_name} - next if task.nil? - task.instance_variable_set :@comment, nil - end -end - -# Change working directories to _dir_, call the _block_ of code, and then -# change back to the original working directory (the current directory when -# this method was called). -# -def in_directory( dir, &block ) - curdir = pwd - begin - cd dir - return block.call - ensure - cd curdir - end -end - -# Scans the current working directory and creates a list of files that are -# candidates to be in the manifest. -# -def manifest - files = [] - exclude = PROJ.exclude.dup - comment = %r/^\s*#/ - - # process the ignore file and add the items there to the exclude list - if test(?f, PROJ.ignore_file) - ary = [] - File.readlines(PROJ.ignore_file).each do |line| - next if line =~ comment - line.chomp! - line.strip! - next if line.nil? or line.empty? - - glob = line =~ %r/\*\./ ? File.join('**', line) : line - Dir.glob(glob).each {|fn| ary << "^#{Regexp.escape(fn)}"} - end - exclude.concat ary - end - - # generate a regular expression from the exclude list - exclude = Regexp.new(exclude.join('|')) - - Find.find '.' do |path| - path.sub! %r/^(\.\/|\/)/o, '' - next unless test ?f, path - next if path =~ exclude - files << path - end - files.sort! -end - -# We need a "valid" method thtat determines if a string is suitable for use -# in the gem specification. -# -class Object - def valid? - return !(self.empty? or self == "\000") if self.respond_to?(:to_str) - return false - end -end - -# EOF diff --git a/pkg/turnstile-0.0.5/tasks/spec.rake b/pkg/turnstile-0.0.5/tasks/spec.rake deleted file mode 100644 index 103acf6..0000000 --- a/pkg/turnstile-0.0.5/tasks/spec.rake +++ /dev/null @@ -1,54 +0,0 @@ - -if HAVE_SPEC_RAKE_SPECTASK and not PROJ.spec.files.to_a.empty? -require 'spec/rake/verify_rcov' - -namespace :spec do - - desc 'Run all specs with basic output' - Spec::Rake::SpecTask.new(:run) do |t| - t.ruby_opts = PROJ.ruby_opts - t.spec_opts = PROJ.spec.opts - t.spec_files = PROJ.spec.files - t.libs += PROJ.libs - end - - desc 'Run all specs with text output' - Spec::Rake::SpecTask.new(:specdoc) do |t| - t.ruby_opts = PROJ.ruby_opts - t.spec_opts = PROJ.spec.opts + ['--format', 'specdoc'] - t.spec_files = PROJ.spec.files - t.libs += PROJ.libs - end - - if HAVE_RCOV - desc 'Run all specs with RCov' - Spec::Rake::SpecTask.new(:rcov) do |t| - t.ruby_opts = PROJ.ruby_opts - t.spec_opts = PROJ.spec.opts - t.spec_files = PROJ.spec.files - t.libs += PROJ.libs - t.rcov = true - t.rcov_dir = PROJ.rcov.dir - t.rcov_opts = PROJ.rcov.opts + ['--exclude', 'spec'] - end - - RCov::VerifyTask.new(:verify) do |t| - t.threshold = PROJ.rcov.threshold - t.index_html = File.join(PROJ.rcov.dir, 'index.html') - t.require_exact_threshold = PROJ.rcov.threshold_exact - end - - task :verify => :rcov - remove_desc_for_task %w(spec:clobber_rcov) - end - -end # namespace :spec - -desc 'Alias to spec:run' -task :spec => 'spec:run' - -task :clobber => 'spec:clobber_rcov' if HAVE_RCOV - -end # if HAVE_SPEC_RAKE_SPECTASK - -# EOF diff --git a/pkg/turnstile-0.0.5/tasks/svn.rake b/pkg/turnstile-0.0.5/tasks/svn.rake deleted file mode 100644 index c186cc6..0000000 --- a/pkg/turnstile-0.0.5/tasks/svn.rake +++ /dev/null @@ -1,47 +0,0 @@ - -if HAVE_SVN - -unless PROJ.svn.root - info = %x/svn info ./ - m = %r/^Repository Root:\s+(.*)$/.match(info) - PROJ.svn.root = (m.nil? ? '' : m[1]) -end -PROJ.svn.root = File.join(PROJ.svn.root, PROJ.svn.path) unless PROJ.svn.path.empty? - -namespace :svn do - - # A prerequisites task that all other tasks depend upon - task :prereqs - - desc 'Show tags from the SVN repository' - task :show_tags => 'svn:prereqs' do |t| - tags = %x/svn list #{File.join(PROJ.svn.root, PROJ.svn.tags)}/ - tags.gsub!(%r/\/$/, '') - tags = tags.split("\n").sort {|a,b| b <=> a} - puts tags - end - - desc 'Create a new tag in the SVN repository' - task :create_tag => 'svn:prereqs' do |t| - v = ENV['VERSION'] or abort 'Must supply VERSION=x.y.z' - abort "Versions don't match #{v} vs #{PROJ.version}" if v != PROJ.version - - svn = PROJ.svn - trunk = File.join(svn.root, svn.trunk) - tag = "%s-%s" % [PROJ.name, PROJ.version] - tag = File.join(svn.root, svn.tags, tag) - msg = "Creating tag for #{PROJ.name} version #{PROJ.version}" - - puts "Creating SVN tag '#{tag}'" - unless system "svn cp -m '#{msg}' #{trunk} #{tag}" - abort "Tag creation failed" - end - end - -end # namespace :svn - -task 'gem:release' => 'svn:create_tag' - -end # if PROJ.svn.path - -# EOF diff --git a/pkg/turnstile-0.0.5/tasks/test.rake b/pkg/turnstile-0.0.5/tasks/test.rake deleted file mode 100644 index 4123f9a..0000000 --- a/pkg/turnstile-0.0.5/tasks/test.rake +++ /dev/null @@ -1,40 +0,0 @@ - -if test(?e, PROJ.test.file) or not PROJ.test.files.to_a.empty? -require 'rake/testtask' - -namespace :test do - - Rake::TestTask.new(:run) do |t| - t.libs = PROJ.libs - t.test_files = if test(?f, PROJ.test.file) then [PROJ.test.file] - else PROJ.test.files end - t.ruby_opts += PROJ.ruby_opts - t.ruby_opts += PROJ.test.opts - end - - if HAVE_RCOV - desc 'Run rcov on the unit tests' - task :rcov => :clobber_rcov do - opts = PROJ.rcov.opts.dup << '-o' << PROJ.rcov.dir - opts = opts.join(' ') - files = if test(?f, PROJ.test.file) then [PROJ.test.file] - else PROJ.test.files end - files = files.join(' ') - sh "#{RCOV} #{files} #{opts}" - end - - task :clobber_rcov do - rm_r 'coverage' rescue nil - end - end - -end # namespace :test - -desc 'Alias to test:run' -task :test => 'test:run' - -task :clobber => 'test:clobber_rcov' if HAVE_RCOV - -end - -# EOF diff --git a/pkg/turnstile-0.0.5/tasks/zentest.rake b/pkg/turnstile-0.0.5/tasks/zentest.rake deleted file mode 100644 index 7ccfd82..0000000 --- a/pkg/turnstile-0.0.5/tasks/zentest.rake +++ /dev/null @@ -1,36 +0,0 @@ -if HAVE_ZENTEST - -# -------------------------------------------------------------------------- -if test(?e, PROJ.test.file) or not PROJ.test.files.to_a.empty? -require 'autotest' - -namespace :test do - task :autotest do - Autotest.run - end -end - -desc "Run the autotest loop" -task :autotest => 'test:autotest' - -end # if test - -# -------------------------------------------------------------------------- -if HAVE_SPEC_RAKE_SPECTASK and not PROJ.spec.files.to_a.empty? -require 'autotest/rspec' - -namespace :spec do - task :autotest do - load '.autotest' if test(?f, '.autotest') - Autotest::Rspec.run - end -end - -desc "Run the autotest loop" -task :autotest => 'spec:autotest' - -end # if rspec - -end # if HAVE_ZENTEST - -# EOF diff --git a/pkg/turnstile-0.0.5/test/test_turnstile.rb b/pkg/turnstile-0.0.5/test/test_turnstile.rb deleted file mode 100644 index e69de29..0000000
rjungemann/turnstile
d9eec357137e1db57cfd1b9e9ea89220ee513c99
Added some specs and fixed some major bugs.
diff --git a/History.txt b/History.txt index e800986..2cb38ba 100644 --- a/History.txt +++ b/History.txt @@ -1,4 +1,3 @@ -== 1.0.0 / 2009-08-19 +== 0.0.5 / 2009-08-19 -* 1 major enhancement - * Birthday! +* Fixed the README.txt. \ No newline at end of file diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..bcb57b8 --- /dev/null +++ b/README.txt @@ -0,0 +1,98 @@ +turnstile + by Roger Jungemann + http://thefifthcircuit.com/ + +== DESCRIPTION: + +Turnstile is meant to be a flexible authentication and authorization system for Ruby. Currently it is merely a set of "model" classes, although I will shortly release a set of Rack middleware and an HTTP client library which will allow one to create providers, consumers, and clients which are available to Rails apps (or any Rack-compatible app for that matter), for a modest "single sign-on" solution. + +Turnstile is built on Moneta, which is a hot-swappable interface for various key-value stores. Moneta uses SDBM as its data-store by default, but it can also use Tokyo Cabinet, Redis, or even SQL-based sources, thanks to the DataMapper Moneta wrapper. + +== FEATURES/PROBLEMS: + +* Tests are glaringly missing. +* I need to add in my set of Rack middleware for creating providers, consumers, and clients. I have a mostly completed set of code for these. +* I am considering OAuth and/or OpenID support for my provider, consumer, and client, which could be useful for different aspects of turnstile. + +== SYNOPSIS: + +To get started, try typing in `turnstile` in your terminal. This will open a prompt allowing one to interact with the turnstile database. Let's first try and create a role. A role is a collection of limited rights for a particular resource. For example, a web application with a "/treasures" url might want to limit access to that resource to only a small set of users. For example: + + Role.create "king", "/", "/treasures" + Role.create "hero", "/" + Role.create "damsel", "/" + +Next, let's create a realm. A realm is a collection of resources which need to be authorized and authenticated. Let's create a realm called `magical_kingdom` and associate some roles with it. + + realm = "magical_kingdom" + + Realm.create realm, "king", "hero", "damsel" + +Next, let's try actually creating a user. + + name, password = "mickey", "mouse" + + user = User.create "mickey" + user.add_realm realm, password + user.add_role realm, "hero" + +Now, the important part. How does one sign in a user? How does one keep track of signedin users? Here's how to signin a user: + + user.signin realm, password + +Once a user is signed in, the `uuid` method will give a value which can be freely given to the user. The user can later be looked up by turnstile just by using the uuid for that user's session. + + uuid = user.uuid realm + + user = User.from_uuid uuid + +You can also see if a user is signed into a realm, or sign them out. + + user.signedin? realm + user.signout realm + +== REQUIREMENTS: + +* Moneta, uuid, and andand gems + +== INSTALL: + + gem sources -a http://gems.github.com + sudo gem install thefifthcircuit-turnstile + +To use, either type `turnstile` into your terminal, or create a new text file, type in + + require 'rubygems' + require 'turnstile' + + $t = Turnstile::Model::Turnstile.new # create and instantiate database + Turnstile::Model::Turnstile.init # setup database with default values + + include Turnstile::Model + + User.create "minnie" + +== LICENSE: + +(The MIT License) + +Copyright (c) 2008 FIXME (different license?) + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/lib/turnstile.rb b/lib/turnstile.rb index a3da37e..3b73b14 100644 --- a/lib/turnstile.rb +++ b/lib/turnstile.rb @@ -1,48 +1,48 @@ module Turnstile # :stopdoc: - VERSION = '0.0.4' + VERSION = '0.0.5' LIBPATH = ::File.expand_path(::File.dirname(__FILE__)) + ::File::SEPARATOR PATH = ::File.dirname(LIBPATH) + ::File::SEPARATOR # :startdoc: # Returns the version string for the library. # def self.version VERSION end # Returns the library path for the module. If any arguments are given, # they will be joined to the end of the libray path using # <tt>File.join</tt>. # def self.libpath( *args ) args.empty? ? LIBPATH : ::File.join(LIBPATH, args.flatten) end # Returns the lpath for the module. If any arguments are given, # they will be joined to the end of the path using # <tt>File.join</tt>. # def self.path( *args ) args.empty? ? PATH : ::File.join(PATH, args.flatten) end # Utility method used to require all files ending in .rb that lie in the # directory below this file that has the same name as the filename passed # in. Optionally, a specific _directory_ name can be passed in such that # the _filename_ does not have to be equivalent to the directory. # def self.require_all_libs_relative_to( fname, dir = nil ) dir ||= ::File.basename(fname, '.*') search_me = ::File.expand_path( ::File.join(::File.dirname(fname), dir, '**', '*.rb')) Dir.glob(search_me).sort.each {|rb| require rb} end end # module Turnstile Turnstile.require_all_libs_relative_to(__FILE__) # EOF diff --git a/lib/turnstile/init.rb b/lib/turnstile/init.rb index f79f039..29e5700 100644 --- a/lib/turnstile/init.rb +++ b/lib/turnstile/init.rb @@ -1,10 +1,13 @@ +require 'rubygems' +require 'uuid' + dir = File.dirname(__FILE__) require "#{dir}/utils/generate" require "#{dir}/model/turnstile" require "#{dir}/model/user" require "#{dir}/model/realm" require "#{dir}/model/role" $t = Turnstile::Model::Turnstile.new Turnstile::Model::Turnstile.init \ No newline at end of file diff --git a/lib/turnstile/model/modules/authorizable.rb b/lib/turnstile/model/modules/authorizable.rb index 1891d7e..700445f 100644 --- a/lib/turnstile/model/modules/authorizable.rb +++ b/lib/turnstile/model/modules/authorizable.rb @@ -1,55 +1,61 @@ module Turnstile module Model module Modules module Authorizable def authorized? realm, role columns = $t.db["user-#{@name}"] raise "User isn't part of realm." if columns[:realms][realm].nil? columns[:realms][realm][:roles].include? role end def add_role realm, role - columns = $t.db["user-#{@name}"] - + raise "Role doesn't exist." if Role.find(role).nil? raise "User isn't part of realm." unless in_realm?(realm) - + + columns = $t.db["user-#{@name}"] roles = columns[:realms][realm][:roles] raise "User already has this role." if roles.include? role roles << role columns[:realms][realm][:roles] = roles $t.db["user-#{@name}"] = columns end def remove_role realm, role - columns = $t.db["user-#{@name}"] - + raise "Role doesn't exist." if Role.find(role).nil? raise "User isn't part of realm." unless in_realm?(realm) - + + columns = $t.db["user-#{@name}"] roles = columns[:realms][realm][:roles] raise "User doesn't have this role." if not roles.include? role roles.reject! { |r| r == role } columns[:realms][realm][:roles] = roles $t.db["user-#{@name}"] = columns end def roles realm columns = $t.db["user-#{@name}"] raise "User isn't part of realm" unless in_realm?(realm) columns[:realms][realm][:roles] end + + def has_right? realm, right + not roles(realm).reject { |role| + not Role.find(role).has_right? role + }.empty? + end end end end end \ No newline at end of file diff --git a/lib/turnstile/model/modules/manageable.rb b/lib/turnstile/model/modules/manageable.rb index 9408b17..9c0c740 100644 --- a/lib/turnstile/model/modules/manageable.rb +++ b/lib/turnstile/model/modules/manageable.rb @@ -1,119 +1,125 @@ require 'andand' module Turnstile module Model module Modules module Manageable module ClassMethods def find name $t.db.has_key?("user-#{name}") ? User.new(name) : nil end def create name raise "No name was provided." if name.nil? $t.transact("user-#{name}") do |user| raise "User already exists" unless user.empty? { :name => name, :realms => {}, :created_on => Time.now } end User.new name end + + def exists? name + !User.find(name).nil? + end def users $t.db.keys.reject { |k| not k.match(/user-.*/) }.collect { |k| k[5..-1] } end def realms $t.db["realms"].andand.keys end end def add_realm realm, password raise "No password was provided." if password.nil? raise "No realm was provided." if realm.nil? + raise "Realm doesn't exist." if Realm.find(realm).nil? columns = $t.db["user-#{@name}"] salt = Generate.salt raise "User is already part of this realm." if not columns[:realms][realm].nil? columns[:realms][realm] = { :roles => [] } columns[:realms][realm][:salt] = salt columns[:realms][realm][:hash] = Generate.hash(salt, password) $t.db["user-#{name}"] = columns self end def remove_realm realm raise "No realm was provided." if realm.nil? + raise "Realm doesn't exist." if Realm.find(realm).nil? columns = $t.db["user-#{@name}"] raise "User isn't part of realm." if not in_realm?(realm) - columns[:realms].delete! realm + columns[:realms].delete realm $t.db["user-#{name}"] = columns self end def in_realm? realm !$t.db["user-#{@name}"][:realms][realm].nil? end def change_password realm, password raise "No password was provided." if password.nil? raise "No realm was provided." if realm.nil? columns = $t.db["user-#{@name}"] raise "User isn't part of realm." if not in_realm?(realm) salt = Generate.salt columns[:realms][realm][:salt] = salt columns[:realms][realm][:hash] = Generate.hash(salt, password) $t.db["user-#{@name}"] = columns self end def check_password realm, password raise "No password was provided." if password.nil? raise "No realm was provided." if realm.nil? columns = $t.db["user-#{@name}"] raise "User isn't part of realm." if not in_realm?(realm) hash = Generate.hash(columns[:realms][realm][:salt], password) hash == columns[:realms][realm][:hash] end def realms columns = $t.db["user-#{@name}"][:realms].keys end def destroy $t.db.delete "user-#{@name}" @name = nil nil end def self.included(base) base.extend ClassMethods end end end end end \ No newline at end of file diff --git a/lib/turnstile/model/realm.rb b/lib/turnstile/model/realm.rb index e30774d..40d3ae5 100644 --- a/lib/turnstile/model/realm.rb +++ b/lib/turnstile/model/realm.rb @@ -1,63 +1,77 @@ module Turnstile module Model class Realm attr_reader :name def self.init $t.db["realms"] ||= {} end def initialize name @name = name end def self.create name, *roles $t.transact("realms") do |realms| realms[name] ||= { :roles => roles || [] } realms end Realm.new name end def self.find name - $t.db["realms"][name] ? Realm.new : nil + $t.db["realms"][name] ? Realm.new(name) : nil + end + + def self.exists? name + !Realm.find(name).nil? end def add_role name - $t.transact("realms") do |realm| + raise "Role hasn't been created yet." unless Role.exists? name + raise "Role already exists in realm." if self.roles.include? name + + $t.transact("realms") do |realms| realms[@name][:roles] << name realms end self end def remove_role name - $t.transact("realms") do |realm| - realms[@name][:roles].reject { |r| r == name } + raise "Role hasn't been created yet." unless Role.exists? name + raise "Role already exists in realm." unless self.roles.include? name + + $t.transact("realms") do |realms| + realms[@name][:roles].reject! { |r| r == name } realms end self end def destroy $t.transact("realms") do |realms| realms.delete name realms end nil end def self.realms $t.db["realms"] end + + def roles + $t.db["realms"][@name][:roles] + end end end end \ No newline at end of file diff --git a/lib/turnstile/model/role.rb b/lib/turnstile/model/role.rb index 3fd5eac..8dd781c 100644 --- a/lib/turnstile/model/role.rb +++ b/lib/turnstile/model/role.rb @@ -1,76 +1,82 @@ module Turnstile module Model class Role attr_reader :name def initialize name @name = name end def self.init $t.db["roles"] ||= {} end def self.create name, *rights rights ||= [] roles = $t.db["roles"] raise "Role already exists." if roles.include? name roles[name] = { :rights => rights } $t.db["roles"] = roles Role.new name end def self.find name roles = $t.db["roles"] - return nil unless roles.include? name - - Role.new name + roles.include?(name) ? Role.new(name) : nil + end + + def self.exists? name + !$t.db["roles"][name].nil? end def self.roles $t.db["roles"].keys end def rights roles = $t.db["roles"] roles[@name][:rights] end + + def has_right? right + rights.include? right + end def add_right right roles = $t.db["roles"] rights = roles[@name][:rights] + right roles[@name][:rights] = rights $t.db["roles"] = role self end def remove_right right roles = $t.db["roles"] rights = roles[@name][:rights].reject right roles[@name][:rights] = rights $t.db["roles"] = role self end def destroy - $t.db["roles"].remove @name + $t.db["roles"].delete @name @name = nil nil end end end end \ No newline at end of file diff --git a/lib/turnstile/tmp/db.sdbm.dir b/lib/turnstile/tmp/db.sdbm.dir index e69de29..b57c670 100644 Binary files a/lib/turnstile/tmp/db.sdbm.dir and b/lib/turnstile/tmp/db.sdbm.dir differ diff --git a/lib/turnstile/tmp/db.sdbm.pag b/lib/turnstile/tmp/db.sdbm.pag index 9a0ec60..2724033 100644 Binary files a/lib/turnstile/tmp/db.sdbm.pag and b/lib/turnstile/tmp/db.sdbm.pag differ diff --git a/pkg/turnstile-0.0.5.gem b/pkg/turnstile-0.0.5.gem new file mode 100644 index 0000000..22b8e08 Binary files /dev/null and b/pkg/turnstile-0.0.5.gem differ diff --git a/pkg/turnstile-0.0.5.tgz b/pkg/turnstile-0.0.5.tgz new file mode 100644 index 0000000..2c47c73 Binary files /dev/null and b/pkg/turnstile-0.0.5.tgz differ diff --git a/pkg/turnstile-0.0.5/History.txt b/pkg/turnstile-0.0.5/History.txt new file mode 100644 index 0000000..2cb38ba --- /dev/null +++ b/pkg/turnstile-0.0.5/History.txt @@ -0,0 +1,3 @@ +== 0.0.5 / 2009-08-19 + +* Fixed the README.txt. \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/README.txt b/pkg/turnstile-0.0.5/README.txt new file mode 100644 index 0000000..bcb57b8 --- /dev/null +++ b/pkg/turnstile-0.0.5/README.txt @@ -0,0 +1,98 @@ +turnstile + by Roger Jungemann + http://thefifthcircuit.com/ + +== DESCRIPTION: + +Turnstile is meant to be a flexible authentication and authorization system for Ruby. Currently it is merely a set of "model" classes, although I will shortly release a set of Rack middleware and an HTTP client library which will allow one to create providers, consumers, and clients which are available to Rails apps (or any Rack-compatible app for that matter), for a modest "single sign-on" solution. + +Turnstile is built on Moneta, which is a hot-swappable interface for various key-value stores. Moneta uses SDBM as its data-store by default, but it can also use Tokyo Cabinet, Redis, or even SQL-based sources, thanks to the DataMapper Moneta wrapper. + +== FEATURES/PROBLEMS: + +* Tests are glaringly missing. +* I need to add in my set of Rack middleware for creating providers, consumers, and clients. I have a mostly completed set of code for these. +* I am considering OAuth and/or OpenID support for my provider, consumer, and client, which could be useful for different aspects of turnstile. + +== SYNOPSIS: + +To get started, try typing in `turnstile` in your terminal. This will open a prompt allowing one to interact with the turnstile database. Let's first try and create a role. A role is a collection of limited rights for a particular resource. For example, a web application with a "/treasures" url might want to limit access to that resource to only a small set of users. For example: + + Role.create "king", "/", "/treasures" + Role.create "hero", "/" + Role.create "damsel", "/" + +Next, let's create a realm. A realm is a collection of resources which need to be authorized and authenticated. Let's create a realm called `magical_kingdom` and associate some roles with it. + + realm = "magical_kingdom" + + Realm.create realm, "king", "hero", "damsel" + +Next, let's try actually creating a user. + + name, password = "mickey", "mouse" + + user = User.create "mickey" + user.add_realm realm, password + user.add_role realm, "hero" + +Now, the important part. How does one sign in a user? How does one keep track of signedin users? Here's how to signin a user: + + user.signin realm, password + +Once a user is signed in, the `uuid` method will give a value which can be freely given to the user. The user can later be looked up by turnstile just by using the uuid for that user's session. + + uuid = user.uuid realm + + user = User.from_uuid uuid + +You can also see if a user is signed into a realm, or sign them out. + + user.signedin? realm + user.signout realm + +== REQUIREMENTS: + +* Moneta, uuid, and andand gems + +== INSTALL: + + gem sources -a http://gems.github.com + sudo gem install thefifthcircuit-turnstile + +To use, either type `turnstile` into your terminal, or create a new text file, type in + + require 'rubygems' + require 'turnstile' + + $t = Turnstile::Model::Turnstile.new # create and instantiate database + Turnstile::Model::Turnstile.init # setup database with default values + + include Turnstile::Model + + User.create "minnie" + +== LICENSE: + +(The MIT License) + +Copyright (c) 2008 FIXME (different license?) + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/pkg/turnstile-0.0.5/Rakefile b/pkg/turnstile-0.0.5/Rakefile new file mode 100644 index 0000000..7f28170 --- /dev/null +++ b/pkg/turnstile-0.0.5/Rakefile @@ -0,0 +1,34 @@ +# Look in the tasks/setup.rb file for the various options that can be +# configured in this Rakefile. The .rake files in the tasks directory +# are where the options are used. + +begin + require 'bones' + Bones.setup +rescue LoadError + begin + load 'tasks/setup.rb' + rescue LoadError + raise RuntimeError, '### please install the "bones" gem ###' + end +end + +ensure_in_path 'lib' +require 'turnstile' + +task :default => 'spec:run' + +PROJ.name = 'turnstile' +PROJ.authors = 'Roger Jungemann' +PROJ.email = '[email protected]' +PROJ.url = 'http://thefifthcircuit.com' +PROJ.version = Turnstile::VERSION +PROJ.rubyforge.name = 'turnstile' + +PROJ.spec.opts << '--color' + +depend_on 'moneta' +depend_on 'uuid' +depend_on 'andand' + +# EOF diff --git a/pkg/turnstile-0.0.5/bin/turnstile b/pkg/turnstile-0.0.5/bin/turnstile new file mode 100755 index 0000000..03dd24c --- /dev/null +++ b/pkg/turnstile-0.0.5/bin/turnstile @@ -0,0 +1,3 @@ +#!/bin/sh + +irb -rturnstile \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile.rb b/pkg/turnstile-0.0.5/lib/turnstile.rb new file mode 100644 index 0000000..3b73b14 --- /dev/null +++ b/pkg/turnstile-0.0.5/lib/turnstile.rb @@ -0,0 +1,48 @@ +module Turnstile + + # :stopdoc: + VERSION = '0.0.5' + LIBPATH = ::File.expand_path(::File.dirname(__FILE__)) + ::File::SEPARATOR + PATH = ::File.dirname(LIBPATH) + ::File::SEPARATOR + # :startdoc: + + # Returns the version string for the library. + # + def self.version + VERSION + end + + # Returns the library path for the module. If any arguments are given, + # they will be joined to the end of the libray path using + # <tt>File.join</tt>. + # + def self.libpath( *args ) + args.empty? ? LIBPATH : ::File.join(LIBPATH, args.flatten) + end + + # Returns the lpath for the module. If any arguments are given, + # they will be joined to the end of the path using + # <tt>File.join</tt>. + # + def self.path( *args ) + args.empty? ? PATH : ::File.join(PATH, args.flatten) + end + + # Utility method used to require all files ending in .rb that lie in the + # directory below this file that has the same name as the filename passed + # in. Optionally, a specific _directory_ name can be passed in such that + # the _filename_ does not have to be equivalent to the directory. + # + def self.require_all_libs_relative_to( fname, dir = nil ) + dir ||= ::File.basename(fname, '.*') + search_me = ::File.expand_path( + ::File.join(::File.dirname(fname), dir, '**', '*.rb')) + + Dir.glob(search_me).sort.each {|rb| require rb} + end + +end # module Turnstile + +Turnstile.require_all_libs_relative_to(__FILE__) + +# EOF diff --git a/pkg/turnstile-0.0.5/lib/turnstile/init.rb b/pkg/turnstile-0.0.5/lib/turnstile/init.rb new file mode 100644 index 0000000..29e5700 --- /dev/null +++ b/pkg/turnstile-0.0.5/lib/turnstile/init.rb @@ -0,0 +1,13 @@ +require 'rubygems' +require 'uuid' + +dir = File.dirname(__FILE__) + +require "#{dir}/utils/generate" +require "#{dir}/model/turnstile" +require "#{dir}/model/user" +require "#{dir}/model/realm" +require "#{dir}/model/role" + +$t = Turnstile::Model::Turnstile.new +Turnstile::Model::Turnstile.init \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile/model/modules/authenticable.rb b/pkg/turnstile-0.0.5/lib/turnstile/model/modules/authenticable.rb new file mode 100644 index 0000000..c37cb76 --- /dev/null +++ b/pkg/turnstile-0.0.5/lib/turnstile/model/modules/authenticable.rb @@ -0,0 +1,74 @@ +module Turnstile + module Model + module Modules + module Authenticable + module ClassMethods + def signin(realm, name, password) + raise "No name was provided." if name.nil? + raise "No password was provided." if password.nil? + raise "No realm was provided." if realm.nil? + + user = User.find name + + if user.nil? + return nil + else + raise "User isn't part of realm." if not user.in_realm?(realm) + raise "Wrong password was provided." if !user.check_password(realm, password) + + uuid = Generate.uuid + + user.set_uuid uuid, realm + + return user + end + end + + def from_uuid(uuid) + raise "No uuid was provided." if uuid.nil? + + uuids = $t.db["uuids"] + + name, realm = uuids[uuid][:name], uuids[uuid][:realm] + + user = User.find name + + user.in_realm?(realm) ? user : nil + end + end + + def signout(realm) + raise "No realm was provided." if realm.nil? + raise "User isn't part of realm." if not in_realm?(realm) + + set_uuid nil, realm + + nil + end + + def signedin?(realm) + $t.db["user-#{@name}"][:realms][realm].andand[:uuid].nil? ? nil : self + end + + def uuid(realm) + $t.db["user-#{@name}"][:realms][realm][:uuid] + end + + def set_uuid(uuid, realm) + uuids = $t.db["uuids"] + uuids[uuid] = { :name => self.name, :realm => realm } + $t.db["uuids"] = uuids + + $t.transact("user-#{@name}") do |u| + u[:realms][realm][:uuid] = uuid + u + end + end + + def self.included(base) + base.extend ClassMethods + end + end + end + end +end \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile/model/modules/authorizable.rb b/pkg/turnstile-0.0.5/lib/turnstile/model/modules/authorizable.rb new file mode 100644 index 0000000..700445f --- /dev/null +++ b/pkg/turnstile-0.0.5/lib/turnstile/model/modules/authorizable.rb @@ -0,0 +1,61 @@ +module Turnstile + module Model + module Modules + module Authorizable + def authorized? realm, role + columns = $t.db["user-#{@name}"] + + raise "User isn't part of realm." if columns[:realms][realm].nil? + + columns[:realms][realm][:roles].include? role + end + + def add_role realm, role + raise "Role doesn't exist." if Role.find(role).nil? + raise "User isn't part of realm." unless in_realm?(realm) + + columns = $t.db["user-#{@name}"] + roles = columns[:realms][realm][:roles] + + raise "User already has this role." if roles.include? role + + roles << role + + columns[:realms][realm][:roles] = roles + + $t.db["user-#{@name}"] = columns + end + + def remove_role realm, role + raise "Role doesn't exist." if Role.find(role).nil? + raise "User isn't part of realm." unless in_realm?(realm) + + columns = $t.db["user-#{@name}"] + roles = columns[:realms][realm][:roles] + + raise "User doesn't have this role." if not roles.include? role + + roles.reject! { |r| r == role } + + columns[:realms][realm][:roles] = roles + + $t.db["user-#{@name}"] = columns + end + + def roles realm + columns = $t.db["user-#{@name}"] + + raise "User isn't part of realm" unless in_realm?(realm) + + columns[:realms][realm][:roles] + end + + def has_right? realm, right + not roles(realm).reject { |role| + not Role.find(role).has_right? role + }.empty? + end + end + end + end +end \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile/model/modules/manageable.rb b/pkg/turnstile-0.0.5/lib/turnstile/model/modules/manageable.rb new file mode 100644 index 0000000..9c0c740 --- /dev/null +++ b/pkg/turnstile-0.0.5/lib/turnstile/model/modules/manageable.rb @@ -0,0 +1,125 @@ +require 'andand' + +module Turnstile + module Model + module Modules + module Manageable + module ClassMethods + def find name + $t.db.has_key?("user-#{name}") ? User.new(name) : nil + end + + def create name + raise "No name was provided." if name.nil? + + $t.transact("user-#{name}") do |user| + raise "User already exists" unless user.empty? + + { :name => name, :realms => {}, :created_on => Time.now } + end + + User.new name + end + + def exists? name + !User.find(name).nil? + end + + def users + $t.db.keys.reject { |k| not k.match(/user-.*/) }.collect { |k| k[5..-1] } + end + + def realms + $t.db["realms"].andand.keys + end + end + + def add_realm realm, password + raise "No password was provided." if password.nil? + raise "No realm was provided." if realm.nil? + raise "Realm doesn't exist." if Realm.find(realm).nil? + + columns = $t.db["user-#{@name}"] + + salt = Generate.salt + + raise "User is already part of this realm." if not columns[:realms][realm].nil? + + columns[:realms][realm] = { :roles => [] } + columns[:realms][realm][:salt] = salt + columns[:realms][realm][:hash] = Generate.hash(salt, password) + + $t.db["user-#{name}"] = columns + + self + end + + def remove_realm realm + raise "No realm was provided." if realm.nil? + raise "Realm doesn't exist." if Realm.find(realm).nil? + + columns = $t.db["user-#{@name}"] + + raise "User isn't part of realm." if not in_realm?(realm) + + columns[:realms].delete realm + + $t.db["user-#{name}"] = columns + + self + end + + def in_realm? realm + !$t.db["user-#{@name}"][:realms][realm].nil? + end + + def change_password realm, password + raise "No password was provided." if password.nil? + raise "No realm was provided." if realm.nil? + + columns = $t.db["user-#{@name}"] + + raise "User isn't part of realm." if not in_realm?(realm) + + salt = Generate.salt + + columns[:realms][realm][:salt] = salt + columns[:realms][realm][:hash] = Generate.hash(salt, password) + + $t.db["user-#{@name}"] = columns + + self + end + + def check_password realm, password + raise "No password was provided." if password.nil? + raise "No realm was provided." if realm.nil? + + columns = $t.db["user-#{@name}"] + + raise "User isn't part of realm." if not in_realm?(realm) + + hash = Generate.hash(columns[:realms][realm][:salt], password) + + hash == columns[:realms][realm][:hash] + end + + def realms + columns = $t.db["user-#{@name}"][:realms].keys + end + + def destroy + $t.db.delete "user-#{@name}" + + @name = nil + + nil + end + + def self.included(base) + base.extend ClassMethods + end + end + end + end +end \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile/model/realm.rb b/pkg/turnstile-0.0.5/lib/turnstile/model/realm.rb new file mode 100644 index 0000000..40d3ae5 --- /dev/null +++ b/pkg/turnstile-0.0.5/lib/turnstile/model/realm.rb @@ -0,0 +1,77 @@ +module Turnstile + module Model + class Realm + attr_reader :name + + def self.init + $t.db["realms"] ||= {} + end + + def initialize name + @name = name + end + + def self.create name, *roles + $t.transact("realms") do |realms| + realms[name] ||= { :roles => roles || [] } + + realms + end + + Realm.new name + end + + def self.find name + $t.db["realms"][name] ? Realm.new(name) : nil + end + + def self.exists? name + !Realm.find(name).nil? + end + + def add_role name + raise "Role hasn't been created yet." unless Role.exists? name + raise "Role already exists in realm." if self.roles.include? name + + $t.transact("realms") do |realms| + realms[@name][:roles] << name + + realms + end + + self + end + + def remove_role name + raise "Role hasn't been created yet." unless Role.exists? name + raise "Role already exists in realm." unless self.roles.include? name + + $t.transact("realms") do |realms| + realms[@name][:roles].reject! { |r| r == name } + + realms + end + + self + end + + def destroy + $t.transact("realms") do |realms| + realms.delete name + + realms + end + + nil + end + + def self.realms + $t.db["realms"] + end + + def roles + $t.db["realms"][@name][:roles] + end + end + end +end \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile/model/role.rb b/pkg/turnstile-0.0.5/lib/turnstile/model/role.rb new file mode 100644 index 0000000..8dd781c --- /dev/null +++ b/pkg/turnstile-0.0.5/lib/turnstile/model/role.rb @@ -0,0 +1,82 @@ +module Turnstile + module Model + class Role + attr_reader :name + + def initialize name + @name = name + end + + def self.init + $t.db["roles"] ||= {} + end + + def self.create name, *rights + rights ||= [] + roles = $t.db["roles"] + + raise "Role already exists." if roles.include? name + + roles[name] = { :rights => rights } + + $t.db["roles"] = roles + + Role.new name + end + + def self.find name + roles = $t.db["roles"] + + roles.include?(name) ? Role.new(name) : nil + end + + def self.exists? name + !$t.db["roles"][name].nil? + end + + def self.roles + $t.db["roles"].keys + end + + def rights + roles = $t.db["roles"] + + roles[@name][:rights] + end + + def has_right? right + rights.include? right + end + + def add_right right + roles = $t.db["roles"] + + rights = roles[@name][:rights] + right + roles[@name][:rights] = rights + + $t.db["roles"] = role + + self + end + + def remove_right right + roles = $t.db["roles"] + + rights = roles[@name][:rights].reject right + roles[@name][:rights] = rights + + $t.db["roles"] = role + + self + end + + def destroy + $t.db["roles"].delete @name + + @name = nil + + nil + end + end + end +end \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile/model/turnstile.rb b/pkg/turnstile-0.0.5/lib/turnstile/model/turnstile.rb new file mode 100644 index 0000000..8b094e1 --- /dev/null +++ b/pkg/turnstile-0.0.5/lib/turnstile/model/turnstile.rb @@ -0,0 +1,28 @@ +require 'moneta' +require 'moneta/sdbm' + +module Turnstile + module Model + class Turnstile + attr_reader :db + + def self.init + User.init + Realm.init + Role.init + end + + def initialize(options = {}) + options[:path] ||= File.join(File.dirname(__FILE__), "..", "tmp", "db.sdbm") + options[:moneta_store] ||= Moneta::SDBM + + @db = options[:moneta_store].new(:file => options[:path]) + end + + def transact(key, &block) + item = @db[key] || {} + @db[key] = yield(item) + end + end + end +end \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile/model/user.rb b/pkg/turnstile-0.0.5/lib/turnstile/model/user.rb new file mode 100644 index 0000000..35b5053 --- /dev/null +++ b/pkg/turnstile-0.0.5/lib/turnstile/model/user.rb @@ -0,0 +1,25 @@ +dir = File.dirname(__FILE__) + +require "#{dir}/modules/manageable" +require "#{dir}/modules/authenticable" +require "#{dir}/modules/authorizable" + +module Turnstile + module Model + class User + include Modules::Manageable + include Modules::Authenticable + include Modules::Authorizable + + attr_accessor :name + + def self.init + $t.db["uuids"] ||= {} + end + + def initialize(name = nil) + @name = name + end + end + end +end \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm.dir b/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm.dir new file mode 100644 index 0000000..fdcfd81 Binary files /dev/null and b/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm.dir differ diff --git a/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm.pag b/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm.pag new file mode 100644 index 0000000..ba4cbe4 Binary files /dev/null and b/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm.pag differ diff --git a/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm_expires.dir b/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm_expires.dir new file mode 100644 index 0000000..e69de29 diff --git a/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm_expires.pag b/pkg/turnstile-0.0.5/lib/turnstile/tmp/db.sdbm_expires.pag new file mode 100644 index 0000000..e69de29 diff --git a/pkg/turnstile-0.0.5/lib/turnstile/utils/generate.rb b/pkg/turnstile-0.0.5/lib/turnstile/utils/generate.rb new file mode 100644 index 0000000..b26a2ba --- /dev/null +++ b/pkg/turnstile-0.0.5/lib/turnstile/utils/generate.rb @@ -0,0 +1,18 @@ +require 'digest/sha2' +require 'uuid' + +class Generate + @@uuid = UUID.new + + def self.salt + [Array.new(6) { rand(256).chr }.join].pack('m').chomp + end + + def self.hash password, salt + Digest::SHA256.hexdigest password + salt + end + + def self.uuid + @@uuid.generate + end +end \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/spec/spec_helper.rb b/pkg/turnstile-0.0.5/spec/spec_helper.rb new file mode 100644 index 0000000..dd2ad9a --- /dev/null +++ b/pkg/turnstile-0.0.5/spec/spec_helper.rb @@ -0,0 +1,16 @@ + +require File.expand_path( + File.join(File.dirname(__FILE__), %w[.. lib turnstile])) + +Spec::Runner.configure do |config| + # == Mock Framework + # + # RSpec uses it's own mocking framework by default. If you prefer to + # use mocha, flexmock or RR, uncomment the appropriate line: + # + # config.mock_with :mocha + # config.mock_with :flexmock + # config.mock_with :rr +end + +include Turnstile::Model \ No newline at end of file diff --git a/pkg/turnstile-0.0.5/spec/turnstile_spec.rb b/pkg/turnstile-0.0.5/spec/turnstile_spec.rb new file mode 100644 index 0000000..9ff5a8c --- /dev/null +++ b/pkg/turnstile-0.0.5/spec/turnstile_spec.rb @@ -0,0 +1,7 @@ + +require File.join(File.dirname(__FILE__), %w[spec_helper]) + +describe Turnstile do +end + +# EOF diff --git a/pkg/turnstile-0.0.5/tasks/ann.rake b/pkg/turnstile-0.0.5/tasks/ann.rake new file mode 100644 index 0000000..d07084e --- /dev/null +++ b/pkg/turnstile-0.0.5/tasks/ann.rake @@ -0,0 +1,80 @@ + +begin + require 'bones/smtp_tls' +rescue LoadError + require 'net/smtp' +end +require 'time' + +namespace :ann do + + # A prerequisites task that all other tasks depend upon + task :prereqs + + file PROJ.ann.file do + ann = PROJ.ann + puts "Generating #{ann.file}" + File.open(ann.file,'w') do |fd| + fd.puts("#{PROJ.name} version #{PROJ.version}") + fd.puts(" by #{Array(PROJ.authors).first}") if PROJ.authors + fd.puts(" #{PROJ.url}") if PROJ.url.valid? + fd.puts(" (the \"#{PROJ.release_name}\" release)") if PROJ.release_name + fd.puts + fd.puts("== DESCRIPTION") + fd.puts + fd.puts(PROJ.description) + fd.puts + fd.puts(PROJ.changes.sub(%r/^.*$/, '== CHANGES')) + fd.puts + ann.paragraphs.each do |p| + fd.puts "== #{p.upcase}" + fd.puts + fd.puts paragraphs_of(PROJ.readme_file, p).join("\n\n") + fd.puts + end + fd.puts ann.text if ann.text + end + end + + desc "Create an announcement file" + task :announcement => ['ann:prereqs', PROJ.ann.file] + + desc "Send an email announcement" + task :email => ['ann:prereqs', PROJ.ann.file] do + ann = PROJ.ann + from = ann.email[:from] || Array(PROJ.authors).first || PROJ.email + to = Array(ann.email[:to]) + + ### build a mail header for RFC 822 + rfc822msg = "From: #{from}\n" + rfc822msg << "To: #{to.join(',')}\n" + rfc822msg << "Subject: [ANN] #{PROJ.name} #{PROJ.version}" + rfc822msg << " (#{PROJ.release_name})" if PROJ.release_name + rfc822msg << "\n" + rfc822msg << "Date: #{Time.new.rfc822}\n" + rfc822msg << "Message-Id: " + rfc822msg << "<#{"%.8f" % Time.now.to_f}@#{ann.email[:domain]}>\n\n" + rfc822msg << File.read(ann.file) + + params = [:server, :port, :domain, :acct, :passwd, :authtype].map do |key| + ann.email[key] + end + + params[3] = PROJ.email if params[3].nil? + + if params[4].nil? + STDOUT.write "Please enter your e-mail password (#{params[3]}): " + params[4] = STDIN.gets.chomp + end + + ### send email + Net::SMTP.start(*params) {|smtp| smtp.sendmail(rfc822msg, from, to)} + end +end # namespace :ann + +desc 'Alias to ann:announcement' +task :ann => 'ann:announcement' + +CLOBBER << PROJ.ann.file + +# EOF diff --git a/pkg/turnstile-0.0.5/tasks/bones.rake b/pkg/turnstile-0.0.5/tasks/bones.rake new file mode 100644 index 0000000..2093b03 --- /dev/null +++ b/pkg/turnstile-0.0.5/tasks/bones.rake @@ -0,0 +1,20 @@ + +if HAVE_BONES + +namespace :bones do + + desc 'Show the PROJ open struct' + task :debug do |t| + atr = if t.application.top_level_tasks.length == 2 + t.application.top_level_tasks.pop + end + + if atr then Bones::Debug.show_attr(PROJ, atr) + else Bones::Debug.show PROJ end + end + +end # namespace :bones + +end # HAVE_BONES + +# EOF diff --git a/pkg/turnstile-0.0.5/tasks/gem.rake b/pkg/turnstile-0.0.5/tasks/gem.rake new file mode 100644 index 0000000..ab68fc1 --- /dev/null +++ b/pkg/turnstile-0.0.5/tasks/gem.rake @@ -0,0 +1,201 @@ + +require 'find' +require 'rake/packagetask' +require 'rubygems/user_interaction' +require 'rubygems/builder' + +module Bones +class GemPackageTask < Rake::PackageTask + # Ruby GEM spec containing the metadata for this package. The + # name, version and package_files are automatically determined + # from the GEM spec and don't need to be explicitly provided. + # + attr_accessor :gem_spec + + # Tasks from the Bones gem directory + attr_reader :bones_files + + # Create a GEM Package task library. Automatically define the gem + # if a block is given. If no block is supplied, then +define+ + # needs to be called to define the task. + # + def initialize(gem_spec) + init(gem_spec) + yield self if block_given? + define if block_given? + end + + # Initialization tasks without the "yield self" or define + # operations. + # + def init(gem) + super(gem.name, gem.version) + @gem_spec = gem + @package_files += gem_spec.files if gem_spec.files + @bones_files = [] + + local_setup = File.join(Dir.pwd, %w[tasks setup.rb]) + if !test(?e, local_setup) + Dir.glob(::Bones.path(%w[lib bones tasks *])).each {|fn| bones_files << fn} + end + end + + # Create the Rake tasks and actions specified by this + # GemPackageTask. (+define+ is automatically called if a block is + # given to +new+). + # + def define + super + task :prereqs + task :package => ['gem:prereqs', "#{package_dir_path}/#{gem_file}"] + file "#{package_dir_path}/#{gem_file}" => [package_dir_path] + package_files + bones_files do + when_writing("Creating GEM") { + chdir(package_dir_path) do + Gem::Builder.new(gem_spec).build + verbose(true) { + mv gem_file, "../#{gem_file}" + } + end + } + end + + file package_dir_path => bones_files do + mkdir_p package_dir rescue nil + + gem_spec.files = (gem_spec.files + + bones_files.map {|fn| File.join('tasks', File.basename(fn))}).sort + + bones_files.each do |fn| + base_fn = File.join('tasks', File.basename(fn)) + f = File.join(package_dir_path, base_fn) + fdir = File.dirname(f) + mkdir_p(fdir) if !File.exist?(fdir) + if File.directory?(fn) + mkdir_p(f) + else + raise "file name conflict for '#{base_fn}' (conflicts with '#{fn}')" if test(?e, f) + safe_ln(fn, f) + end + end + end + end + + def gem_file + if @gem_spec.platform == Gem::Platform::RUBY + "#{package_name}.gem" + else + "#{package_name}-#{@gem_spec.platform}.gem" + end + end +end # class GemPackageTask +end # module Bones + +namespace :gem do + + PROJ.gem._spec = Gem::Specification.new do |s| + s.name = PROJ.name + s.version = PROJ.version + s.summary = PROJ.summary + s.authors = Array(PROJ.authors) + s.email = PROJ.email + s.homepage = Array(PROJ.url).first + s.rubyforge_project = PROJ.rubyforge.name + + s.description = PROJ.description + + PROJ.gem.dependencies.each do |dep| + s.add_dependency(*dep) + end + + PROJ.gem.development_dependencies.each do |dep| + s.add_development_dependency(*dep) + end + + s.files = PROJ.gem.files + s.executables = PROJ.gem.executables.map {|fn| File.basename(fn)} + s.extensions = PROJ.gem.files.grep %r/extconf\.rb$/ + + s.bindir = 'bin' + dirs = Dir["{#{PROJ.libs.join(',')}}"] + s.require_paths = dirs unless dirs.empty? + + incl = Regexp.new(PROJ.rdoc.include.join('|')) + excl = PROJ.rdoc.exclude.dup.concat %w[\.rb$ ^(\.\/|\/)?ext] + excl = Regexp.new(excl.join('|')) + rdoc_files = PROJ.gem.files.find_all do |fn| + case fn + when excl; false + when incl; true + else false end + end + s.rdoc_options = PROJ.rdoc.opts + ['--main', PROJ.rdoc.main] + s.extra_rdoc_files = rdoc_files + s.has_rdoc = true + + if test ?f, PROJ.test.file + s.test_file = PROJ.test.file + else + s.test_files = PROJ.test.files.to_a + end + + # Do any extra stuff the user wants + PROJ.gem.extras.each do |msg, val| + case val + when Proc + val.call(s.send(msg)) + else + s.send "#{msg}=", val + end + end + end # Gem::Specification.new + + Bones::GemPackageTask.new(PROJ.gem._spec) do |pkg| + pkg.need_tar = PROJ.gem.need_tar + pkg.need_zip = PROJ.gem.need_zip + end + + desc 'Show information about the gem' + task :debug => 'gem:prereqs' do + puts PROJ.gem._spec.to_ruby + end + + desc 'Write the gemspec ' + task :spec => 'gem:prereqs' do + File.open("#{PROJ.name}.gemspec", 'w') do |f| + f.write PROJ.gem._spec.to_ruby + end + end + + desc 'Install the gem' + task :install => [:clobber, 'gem:package'] do + sh "#{SUDO} #{GEM} install --local pkg/#{PROJ.gem._spec.full_name}" + + # use this version of the command for rubygems > 1.0.0 + #sh "#{SUDO} #{GEM} install --no-update-sources pkg/#{PROJ.gem._spec.full_name}" + end + + desc 'Uninstall the gem' + task :uninstall do + installed_list = Gem.source_index.find_name(PROJ.name) + if installed_list and installed_list.collect { |s| s.version.to_s}.include?(PROJ.version) then + sh "#{SUDO} #{GEM} uninstall --version '#{PROJ.version}' --ignore-dependencies --executables #{PROJ.name}" + end + end + + desc 'Reinstall the gem' + task :reinstall => [:uninstall, :install] + + desc 'Cleanup the gem' + task :cleanup do + sh "#{SUDO} #{GEM} cleanup #{PROJ.gem._spec.name}" + end +end # namespace :gem + + +desc 'Alias to gem:package' +task :gem => 'gem:package' + +task :clobber => 'gem:clobber_package' +remove_desc_for_task 'gem:clobber_package' + +# EOF diff --git a/pkg/turnstile-0.0.5/tasks/git.rake b/pkg/turnstile-0.0.5/tasks/git.rake new file mode 100644 index 0000000..4f9194b --- /dev/null +++ b/pkg/turnstile-0.0.5/tasks/git.rake @@ -0,0 +1,40 @@ + +if HAVE_GIT + +namespace :git do + + # A prerequisites task that all other tasks depend upon + task :prereqs + + desc 'Show tags from the Git repository' + task :show_tags => 'git:prereqs' do |t| + puts %x/git tag/ + end + + desc 'Create a new tag in the Git repository' + task :create_tag => 'git:prereqs' do |t| + v = ENV['VERSION'] or abort 'Must supply VERSION=x.y.z' + abort "Versions don't match #{v} vs #{PROJ.version}" if v != PROJ.version + + tag = "%s-%s" % [PROJ.name, PROJ.version] + msg = "Creating tag for #{PROJ.name} version #{PROJ.version}" + + puts "Creating Git tag '#{tag}'" + unless system "git tag -a -m '#{msg}' #{tag}" + abort "Tag creation failed" + end + + if %x/git remote/ =~ %r/^origin\s*$/ + unless system "git push origin #{tag}" + abort "Could not push tag to remote Git repository" + end + end + end + +end # namespace :git + +task 'gem:release' => 'git:create_tag' + +end # if HAVE_GIT + +# EOF diff --git a/pkg/turnstile-0.0.5/tasks/notes.rake b/pkg/turnstile-0.0.5/tasks/notes.rake new file mode 100644 index 0000000..5360dfa --- /dev/null +++ b/pkg/turnstile-0.0.5/tasks/notes.rake @@ -0,0 +1,27 @@ + +if HAVE_BONES + +desc "Enumerate all annotations" +task :notes do |t| + id = if t.application.top_level_tasks.length > 1 + t.application.top_level_tasks.slice!(1..-1).join(' ') + end + Bones::AnnotationExtractor.enumerate( + PROJ, PROJ.notes.tags.join('|'), id, :tag => true) +end + +namespace :notes do + PROJ.notes.tags.each do |tag| + desc "Enumerate all #{tag} annotations" + task tag.downcase.to_sym do |t| + id = if t.application.top_level_tasks.length > 1 + t.application.top_level_tasks.slice!(1..-1).join(' ') + end + Bones::AnnotationExtractor.enumerate(PROJ, tag, id) + end + end +end + +end # if HAVE_BONES + +# EOF diff --git a/pkg/turnstile-0.0.5/tasks/post_load.rake b/pkg/turnstile-0.0.5/tasks/post_load.rake new file mode 100644 index 0000000..3ec82d1 --- /dev/null +++ b/pkg/turnstile-0.0.5/tasks/post_load.rake @@ -0,0 +1,34 @@ + +# This file does not define any rake tasks. It is used to load some project +# settings if they are not defined by the user. + +PROJ.exclude << ["^#{Regexp.escape(PROJ.ann.file)}$", + "^#{Regexp.escape(PROJ.ignore_file)}$", + "^#{Regexp.escape(PROJ.rdoc.dir)}/", + "^#{Regexp.escape(PROJ.rcov.dir)}/"] + +flatten_arrays = lambda do |this,os| + os.instance_variable_get(:@table).each do |key,val| + next if key == :dependencies \ + or key == :development_dependencies + case val + when Array; val.flatten! + when OpenStruct; this.call(this,val) + end + end + end +flatten_arrays.call(flatten_arrays,PROJ) + +PROJ.changes ||= paragraphs_of(PROJ.history_file, 0..1).join("\n\n") + +PROJ.description ||= paragraphs_of(PROJ.readme_file, 'description').join("\n\n") + +PROJ.summary ||= PROJ.description.split('.').first + +PROJ.gem.files ||= manifest + +PROJ.gem.executables ||= PROJ.gem.files.find_all {|fn| fn =~ %r/^bin/} + +PROJ.rdoc.main ||= PROJ.readme_file + +# EOF diff --git a/pkg/turnstile-0.0.5/tasks/rdoc.rake b/pkg/turnstile-0.0.5/tasks/rdoc.rake new file mode 100644 index 0000000..edbb804 --- /dev/null +++ b/pkg/turnstile-0.0.5/tasks/rdoc.rake @@ -0,0 +1,51 @@ + +require 'rake/rdoctask' + +namespace :doc do + + desc 'Generate RDoc documentation' + Rake::RDocTask.new do |rd| + rdoc = PROJ.rdoc + rd.main = rdoc.main + rd.rdoc_dir = rdoc.dir + + incl = Regexp.new(rdoc.include.join('|')) + excl = Regexp.new(rdoc.exclude.join('|')) + files = PROJ.gem.files.find_all do |fn| + case fn + when excl; false + when incl; true + else false end + end + rd.rdoc_files.push(*files) + + name = PROJ.name + rf_name = PROJ.rubyforge.name + + title = "#{name}-#{PROJ.version} Documentation" + title = "#{rf_name}'s " + title if rf_name.valid? and rf_name != name + + rd.options << "-t #{title}" + rd.options.concat(rdoc.opts) + end + + desc 'Generate ri locally for testing' + task :ri => :clobber_ri do + sh "#{RDOC} --ri -o ri ." + end + + task :clobber_ri do + rm_r 'ri' rescue nil + end + +end # namespace :doc + +desc 'Alias to doc:rdoc' +task :doc => 'doc:rdoc' + +desc 'Remove all build products' +task :clobber => %w(doc:clobber_rdoc doc:clobber_ri) + +remove_desc_for_task %w(doc:clobber_rdoc) + +# EOF diff --git a/pkg/turnstile-0.0.5/tasks/rubyforge.rake b/pkg/turnstile-0.0.5/tasks/rubyforge.rake new file mode 100644 index 0000000..87b3d31 --- /dev/null +++ b/pkg/turnstile-0.0.5/tasks/rubyforge.rake @@ -0,0 +1,55 @@ + +if PROJ.rubyforge.name.valid? && HAVE_RUBYFORGE + +require 'rubyforge' +require 'rake/contrib/sshpublisher' + +namespace :gem do + desc 'Package and upload to RubyForge' + task :release => [:clobber, 'gem'] do |t| + v = ENV['VERSION'] or abort 'Must supply VERSION=x.y.z' + abort "Versions don't match #{v} vs #{PROJ.version}" if v != PROJ.version + pkg = "pkg/#{PROJ.gem._spec.full_name}" + + if $DEBUG then + puts "release_id = rf.add_release #{PROJ.rubyforge.name.inspect}, #{PROJ.name.inspect}, #{PROJ.version.inspect}, \"#{pkg}.tgz\"" + puts "rf.add_file #{PROJ.rubyforge.name.inspect}, #{PROJ.name.inspect}, release_id, \"#{pkg}.gem\"" + end + + rf = RubyForge.new + rf.configure rescue nil + puts 'Logging in' + rf.login + + c = rf.userconfig + c['release_notes'] = PROJ.description if PROJ.description + c['release_changes'] = PROJ.changes if PROJ.changes + c['preformatted'] = true + + files = Dir.glob("#{pkg}*.*") + + puts "Releasing #{PROJ.name} v. #{PROJ.version}" + rf.add_release PROJ.rubyforge.name, PROJ.name, PROJ.version, *files + end +end # namespace :gem + + +namespace :doc do + desc "Publish RDoc to RubyForge" + task :release => %w(doc:clobber_rdoc doc:rdoc) do + config = YAML.load( + File.read(File.expand_path('~/.rubyforge/user-config.yml')) + ) + + host = "#{config['username']}@rubyforge.org" + remote_dir = "/var/www/gforge-projects/#{PROJ.rubyforge.name}/" + remote_dir << PROJ.rdoc.remote_dir if PROJ.rdoc.remote_dir + local_dir = PROJ.rdoc.dir + + Rake::SshDirPublisher.new(host, remote_dir, local_dir).upload + end +end # namespace :doc + +end # if HAVE_RUBYFORGE + +# EOF diff --git a/pkg/turnstile-0.0.5/tasks/setup.rb b/pkg/turnstile-0.0.5/tasks/setup.rb new file mode 100644 index 0000000..a752385 --- /dev/null +++ b/pkg/turnstile-0.0.5/tasks/setup.rb @@ -0,0 +1,292 @@ + +require 'rubygems' +require 'rake' +require 'rake/clean' +require 'fileutils' +require 'ostruct' +require 'find' + +class OpenStruct; undef :gem if defined? :gem; end + +# TODO: make my own openstruct type object that includes descriptions +# TODO: use the descriptions to output help on the available bones options + +PROJ = OpenStruct.new( + # Project Defaults + :name => nil, + :summary => nil, + :description => nil, + :changes => nil, + :authors => nil, + :email => nil, + :url => "\000", + :version => ENV['VERSION'] || '0.0.0', + :exclude => %w(tmp$ bak$ ~$ CVS \.svn/ \.git/ ^pkg/), + :release_name => ENV['RELEASE'], + + # System Defaults + :ruby_opts => %w(-w), + :libs => [], + :history_file => 'History.txt', + :readme_file => 'README.txt', + :ignore_file => '.bnsignore', + + # Announce + :ann => OpenStruct.new( + :file => 'announcement.txt', + :text => nil, + :paragraphs => [], + :email => { + :from => nil, + :to => %w([email protected]), + :server => 'localhost', + :port => 25, + :domain => ENV['HOSTNAME'], + :acct => nil, + :passwd => nil, + :authtype => :plain + } + ), + + # Gem Packaging + :gem => OpenStruct.new( + :dependencies => [], + :development_dependencies => [], + :executables => nil, + :extensions => FileList['ext/**/extconf.rb'], + :files => nil, + :need_tar => true, + :need_zip => false, + :extras => {} + ), + + # File Annotations + :notes => OpenStruct.new( + :exclude => %w(^tasks/setup\.rb$), + :extensions => %w(.txt .rb .erb .rdoc) << '', + :tags => %w(FIXME OPTIMIZE TODO) + ), + + # Rcov + :rcov => OpenStruct.new( + :dir => 'coverage', + :opts => %w[--sort coverage -T], + :threshold => 90.0, + :threshold_exact => false + ), + + # Rdoc + :rdoc => OpenStruct.new( + :opts => [], + :include => %w(^lib/ ^bin/ ^ext/ \.txt$ \.rdoc$), + :exclude => %w(extconf\.rb$), + :main => nil, + :dir => 'doc', + :remote_dir => nil + ), + + # Rubyforge + :rubyforge => OpenStruct.new( + :name => "\000" + ), + + # Rspec + :spec => OpenStruct.new( + :files => FileList['spec/**/*_spec.rb'], + :opts => [] + ), + + # Subversion Repository + :svn => OpenStruct.new( + :root => nil, + :path => '', + :trunk => 'trunk', + :tags => 'tags', + :branches => 'branches' + ), + + # Test::Unit + :test => OpenStruct.new( + :files => FileList['test/**/test_*.rb'], + :file => 'test/all.rb', + :opts => [] + ) +) + +# Load the other rake files in the tasks folder +tasks_dir = File.expand_path(File.dirname(__FILE__)) +post_load_fn = File.join(tasks_dir, 'post_load.rake') +rakefiles = Dir.glob(File.join(tasks_dir, '*.rake')).sort +rakefiles.unshift(rakefiles.delete(post_load_fn)).compact! +import(*rakefiles) + +# Setup the project libraries +%w(lib ext).each {|dir| PROJ.libs << dir if test ?d, dir} + +# Setup some constants +DEV_NULL = File.exist?('/dev/null') ? '/dev/null' : 'NUL:' + +def quiet( &block ) + io = [STDOUT.dup, STDERR.dup] + STDOUT.reopen DEV_NULL + STDERR.reopen DEV_NULL + block.call +ensure + STDOUT.reopen io.first + STDERR.reopen io.last + $stdout, $stderr = STDOUT, STDERR +end + +DIFF = if system("gdiff '#{__FILE__}' '#{__FILE__}' > #{DEV_NULL} 2>&1") then 'gdiff' + else 'diff' end unless defined? DIFF + +SUDO = if system("which sudo > #{DEV_NULL} 2>&1") then 'sudo' + else '' end unless defined? SUDO + +RCOV = "#{RUBY} -S rcov" +RDOC = "#{RUBY} -S rdoc" +GEM = "#{RUBY} -S gem" + +%w(rcov spec/rake/spectask rubyforge bones facets/ansicode zentest).each do |lib| + begin + require lib + Object.instance_eval {const_set "HAVE_#{lib.tr('/','_').upcase}", true} + rescue LoadError + Object.instance_eval {const_set "HAVE_#{lib.tr('/','_').upcase}", false} + end +end +HAVE_SVN = (Dir.entries(Dir.pwd).include?('.svn') and + system("svn --version 2>&1 > #{DEV_NULL}")) +HAVE_GIT = (Dir.entries(Dir.pwd).include?('.git') and + system("git --version 2>&1 > #{DEV_NULL}")) + +# Add bones as a development dependency +# +if HAVE_BONES + PROJ.gem.development_dependencies << ['bones', ">= #{Bones::VERSION}"] +end + +# Reads a file at +path+ and spits out an array of the +paragraphs+ +# specified. +# +# changes = paragraphs_of('History.txt', 0..1).join("\n\n") +# summary, *description = paragraphs_of('README.txt', 3, 3..8) +# +def paragraphs_of( path, *paragraphs ) + title = String === paragraphs.first ? paragraphs.shift : nil + ary = File.read(path).delete("\r").split(/\n\n+/) + + result = if title + tmp, matching = [], false + rgxp = %r/^=+\s*#{Regexp.escape(title)}/i + paragraphs << (0..-1) if paragraphs.empty? + + ary.each do |val| + if val =~ rgxp + break if matching + matching = true + rgxp = %r/^=+/i + elsif matching + tmp << val + end + end + tmp + else ary end + + result.values_at(*paragraphs) +end + +# Adds the given gem _name_ to the current project's dependency list. An +# optional gem _version_ can be given. If omitted, the newest gem version +# will be used. +# +def depend_on( name, version = nil ) + spec = Gem.source_index.find_name(name).last + version = spec.version.to_s if version.nil? and !spec.nil? + + PROJ.gem.dependencies << case version + when nil; [name] + when %r/^\d/; [name, ">= #{version}"] + else [name, version] end +end + +# Adds the given arguments to the include path if they are not already there +# +def ensure_in_path( *args ) + args.each do |path| + path = File.expand_path(path) + $:.unshift(path) if test(?d, path) and not $:.include?(path) + end +end + +# Find a rake task using the task name and remove any description text. This +# will prevent the task from being displayed in the list of available tasks. +# +def remove_desc_for_task( names ) + Array(names).each do |task_name| + task = Rake.application.tasks.find {|t| t.name == task_name} + next if task.nil? + task.instance_variable_set :@comment, nil + end +end + +# Change working directories to _dir_, call the _block_ of code, and then +# change back to the original working directory (the current directory when +# this method was called). +# +def in_directory( dir, &block ) + curdir = pwd + begin + cd dir + return block.call + ensure + cd curdir + end +end + +# Scans the current working directory and creates a list of files that are +# candidates to be in the manifest. +# +def manifest + files = [] + exclude = PROJ.exclude.dup + comment = %r/^\s*#/ + + # process the ignore file and add the items there to the exclude list + if test(?f, PROJ.ignore_file) + ary = [] + File.readlines(PROJ.ignore_file).each do |line| + next if line =~ comment + line.chomp! + line.strip! + next if line.nil? or line.empty? + + glob = line =~ %r/\*\./ ? File.join('**', line) : line + Dir.glob(glob).each {|fn| ary << "^#{Regexp.escape(fn)}"} + end + exclude.concat ary + end + + # generate a regular expression from the exclude list + exclude = Regexp.new(exclude.join('|')) + + Find.find '.' do |path| + path.sub! %r/^(\.\/|\/)/o, '' + next unless test ?f, path + next if path =~ exclude + files << path + end + files.sort! +end + +# We need a "valid" method thtat determines if a string is suitable for use +# in the gem specification. +# +class Object + def valid? + return !(self.empty? or self == "\000") if self.respond_to?(:to_str) + return false + end +end + +# EOF diff --git a/pkg/turnstile-0.0.5/tasks/spec.rake b/pkg/turnstile-0.0.5/tasks/spec.rake new file mode 100644 index 0000000..103acf6 --- /dev/null +++ b/pkg/turnstile-0.0.5/tasks/spec.rake @@ -0,0 +1,54 @@ + +if HAVE_SPEC_RAKE_SPECTASK and not PROJ.spec.files.to_a.empty? +require 'spec/rake/verify_rcov' + +namespace :spec do + + desc 'Run all specs with basic output' + Spec::Rake::SpecTask.new(:run) do |t| + t.ruby_opts = PROJ.ruby_opts + t.spec_opts = PROJ.spec.opts + t.spec_files = PROJ.spec.files + t.libs += PROJ.libs + end + + desc 'Run all specs with text output' + Spec::Rake::SpecTask.new(:specdoc) do |t| + t.ruby_opts = PROJ.ruby_opts + t.spec_opts = PROJ.spec.opts + ['--format', 'specdoc'] + t.spec_files = PROJ.spec.files + t.libs += PROJ.libs + end + + if HAVE_RCOV + desc 'Run all specs with RCov' + Spec::Rake::SpecTask.new(:rcov) do |t| + t.ruby_opts = PROJ.ruby_opts + t.spec_opts = PROJ.spec.opts + t.spec_files = PROJ.spec.files + t.libs += PROJ.libs + t.rcov = true + t.rcov_dir = PROJ.rcov.dir + t.rcov_opts = PROJ.rcov.opts + ['--exclude', 'spec'] + end + + RCov::VerifyTask.new(:verify) do |t| + t.threshold = PROJ.rcov.threshold + t.index_html = File.join(PROJ.rcov.dir, 'index.html') + t.require_exact_threshold = PROJ.rcov.threshold_exact + end + + task :verify => :rcov + remove_desc_for_task %w(spec:clobber_rcov) + end + +end # namespace :spec + +desc 'Alias to spec:run' +task :spec => 'spec:run' + +task :clobber => 'spec:clobber_rcov' if HAVE_RCOV + +end # if HAVE_SPEC_RAKE_SPECTASK + +# EOF diff --git a/pkg/turnstile-0.0.5/tasks/svn.rake b/pkg/turnstile-0.0.5/tasks/svn.rake new file mode 100644 index 0000000..c186cc6 --- /dev/null +++ b/pkg/turnstile-0.0.5/tasks/svn.rake @@ -0,0 +1,47 @@ + +if HAVE_SVN + +unless PROJ.svn.root + info = %x/svn info ./ + m = %r/^Repository Root:\s+(.*)$/.match(info) + PROJ.svn.root = (m.nil? ? '' : m[1]) +end +PROJ.svn.root = File.join(PROJ.svn.root, PROJ.svn.path) unless PROJ.svn.path.empty? + +namespace :svn do + + # A prerequisites task that all other tasks depend upon + task :prereqs + + desc 'Show tags from the SVN repository' + task :show_tags => 'svn:prereqs' do |t| + tags = %x/svn list #{File.join(PROJ.svn.root, PROJ.svn.tags)}/ + tags.gsub!(%r/\/$/, '') + tags = tags.split("\n").sort {|a,b| b <=> a} + puts tags + end + + desc 'Create a new tag in the SVN repository' + task :create_tag => 'svn:prereqs' do |t| + v = ENV['VERSION'] or abort 'Must supply VERSION=x.y.z' + abort "Versions don't match #{v} vs #{PROJ.version}" if v != PROJ.version + + svn = PROJ.svn + trunk = File.join(svn.root, svn.trunk) + tag = "%s-%s" % [PROJ.name, PROJ.version] + tag = File.join(svn.root, svn.tags, tag) + msg = "Creating tag for #{PROJ.name} version #{PROJ.version}" + + puts "Creating SVN tag '#{tag}'" + unless system "svn cp -m '#{msg}' #{trunk} #{tag}" + abort "Tag creation failed" + end + end + +end # namespace :svn + +task 'gem:release' => 'svn:create_tag' + +end # if PROJ.svn.path + +# EOF diff --git a/pkg/turnstile-0.0.5/tasks/test.rake b/pkg/turnstile-0.0.5/tasks/test.rake new file mode 100644 index 0000000..4123f9a --- /dev/null +++ b/pkg/turnstile-0.0.5/tasks/test.rake @@ -0,0 +1,40 @@ + +if test(?e, PROJ.test.file) or not PROJ.test.files.to_a.empty? +require 'rake/testtask' + +namespace :test do + + Rake::TestTask.new(:run) do |t| + t.libs = PROJ.libs + t.test_files = if test(?f, PROJ.test.file) then [PROJ.test.file] + else PROJ.test.files end + t.ruby_opts += PROJ.ruby_opts + t.ruby_opts += PROJ.test.opts + end + + if HAVE_RCOV + desc 'Run rcov on the unit tests' + task :rcov => :clobber_rcov do + opts = PROJ.rcov.opts.dup << '-o' << PROJ.rcov.dir + opts = opts.join(' ') + files = if test(?f, PROJ.test.file) then [PROJ.test.file] + else PROJ.test.files end + files = files.join(' ') + sh "#{RCOV} #{files} #{opts}" + end + + task :clobber_rcov do + rm_r 'coverage' rescue nil + end + end + +end # namespace :test + +desc 'Alias to test:run' +task :test => 'test:run' + +task :clobber => 'test:clobber_rcov' if HAVE_RCOV + +end + +# EOF diff --git a/pkg/turnstile-0.0.5/tasks/zentest.rake b/pkg/turnstile-0.0.5/tasks/zentest.rake new file mode 100644 index 0000000..7ccfd82 --- /dev/null +++ b/pkg/turnstile-0.0.5/tasks/zentest.rake @@ -0,0 +1,36 @@ +if HAVE_ZENTEST + +# -------------------------------------------------------------------------- +if test(?e, PROJ.test.file) or not PROJ.test.files.to_a.empty? +require 'autotest' + +namespace :test do + task :autotest do + Autotest.run + end +end + +desc "Run the autotest loop" +task :autotest => 'test:autotest' + +end # if test + +# -------------------------------------------------------------------------- +if HAVE_SPEC_RAKE_SPECTASK and not PROJ.spec.files.to_a.empty? +require 'autotest/rspec' + +namespace :spec do + task :autotest do + load '.autotest' if test(?f, '.autotest') + Autotest::Rspec.run + end +end + +desc "Run the autotest loop" +task :autotest => 'spec:autotest' + +end # if rspec + +end # if HAVE_ZENTEST + +# EOF diff --git a/pkg/turnstile-0.0.5/test/test_turnstile.rb b/pkg/turnstile-0.0.5/test/test_turnstile.rb new file mode 100644 index 0000000..e69de29 diff --git a/spec/realm_spec.rb b/spec/realm_spec.rb new file mode 100644 index 0000000..5b44f10 --- /dev/null +++ b/spec/realm_spec.rb @@ -0,0 +1,28 @@ +require File.join(File.dirname(__FILE__), %w[spec_helper]) + +describe Realm do + it "Should allow for a new realm to be created." do + realm_name = "under_the_sea" + realm = Realm.create "under_the_sea", "narwhals", "mermaids", "fish" + realm.roles.should == ["narwhals", "mermaids", "fish"] + end + + it "Should allow for a realm to be found by name." do + realm = Realm.find "under_the_sea" + realm.name.should == "under_the_sea" + end + + it "Should allow for a new role to be added to a realm." do + Role.create "artisan" unless Role.exists? "artisan" + + realm = Realm.find("under_the_sea") + realm.add_role "artisan" + realm.roles.should == ["narwhals", "mermaids", "fish", "artisan"] + end + + it "Should allow for a role to be removed from the realm." do + realm = Realm.find("under_the_sea") + realm.remove_role "artisan" + realm.roles.should == ["narwhals", "mermaids", "fish"] + end +end \ No newline at end of file diff --git a/spec/role_spec.rb b/spec/role_spec.rb new file mode 100644 index 0000000..c70e639 --- /dev/null +++ b/spec/role_spec.rb @@ -0,0 +1,27 @@ +require File.join(File.dirname(__FILE__), %w[spec_helper]) + +describe Role do + it "Should allow a new role to be created." do + + end + + it "Should allow for a role to be found by name." do + + end + + it "Should allow for a role to be destroyed." do + + end + + it "Should be able to list all pertinent rights." do + + end + + it "Should allow for a new right to be added." do + + end + + it "Should allow for a right to be removed." do + + end +end \ No newline at end of file diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index ed0072c..dd2ad9a 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,16 +1,16 @@ require File.expand_path( File.join(File.dirname(__FILE__), %w[.. lib turnstile])) Spec::Runner.configure do |config| # == Mock Framework # # RSpec uses it's own mocking framework by default. If you prefer to # use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr end -# EOF +include Turnstile::Model \ No newline at end of file diff --git a/spec/user_spec.rb b/spec/user_spec.rb new file mode 100644 index 0000000..b558410 --- /dev/null +++ b/spec/user_spec.rb @@ -0,0 +1,43 @@ +require File.join(File.dirname(__FILE__), %w[spec_helper]) + +describe User do + it "Should allow for a new user to be created." do + name = "minnie" + + User.find(name).destroy if User.exists? name + + user = User.create name + user.name.should == name + end + + it "Should allow a created user to be found by name." do + user = User.find "minnie" + user.name.should == "minnie" + end + + it "Should allow a user to add a realm, with a password." do + realm_name = "magical_kingdom" + + Realm.find(realm_name).destroy if Realm.exists? realm_name + Realm.create realm_name + + user = User.find "minnie" + user.add_realm realm_name, "mouse" + user.realms.should == [realm_name] + end + + it "Should allow a user to signin." do + user = User.signin "magical_kingdom", "minnie", "mouse" + user.name.should == "minnie" + end + + it "Should allow a user to see if they're signedin." do + user = User.signin "magical_kingdom", "minnie", "mouse" + user.signedin?("magical_kingdom").should == user + end + + it "Should allow for a new user to be signed out." do + user = User.signin "magical_kingdom", "minnie", "mouse" + user.signout("magical_kingdom").should == nil + end +end \ No newline at end of file
rjungemann/turnstile
7b91ce13cc40dcd6755537591f07883971d086a8
Second commit. Haven't finished Rack middleware yet.
diff --git a/README b/README index e17b952..bcb57b8 100644 --- a/README +++ b/README @@ -1,98 +1,98 @@ turnstile by Roger Jungemann http://thefifthcircuit.com/ == DESCRIPTION: Turnstile is meant to be a flexible authentication and authorization system for Ruby. Currently it is merely a set of "model" classes, although I will shortly release a set of Rack middleware and an HTTP client library which will allow one to create providers, consumers, and clients which are available to Rails apps (or any Rack-compatible app for that matter), for a modest "single sign-on" solution. -Turnstile is built on Moneta, which is a hot-swappable interface for various key-value stores. Moneta uses SDBM as its data-store by default, but it can also use +Turnstile is built on Moneta, which is a hot-swappable interface for various key-value stores. Moneta uses SDBM as its data-store by default, but it can also use Tokyo Cabinet, Redis, or even SQL-based sources, thanks to the DataMapper Moneta wrapper. == FEATURES/PROBLEMS: * Tests are glaringly missing. * I need to add in my set of Rack middleware for creating providers, consumers, and clients. I have a mostly completed set of code for these. * I am considering OAuth and/or OpenID support for my provider, consumer, and client, which could be useful for different aspects of turnstile. == SYNOPSIS: To get started, try typing in `turnstile` in your terminal. This will open a prompt allowing one to interact with the turnstile database. Let's first try and create a role. A role is a collection of limited rights for a particular resource. For example, a web application with a "/treasures" url might want to limit access to that resource to only a small set of users. For example: Role.create "king", "/", "/treasures" Role.create "hero", "/" Role.create "damsel", "/" Next, let's create a realm. A realm is a collection of resources which need to be authorized and authenticated. Let's create a realm called `magical_kingdom` and associate some roles with it. realm = "magical_kingdom" Realm.create realm, "king", "hero", "damsel" Next, let's try actually creating a user. name, password = "mickey", "mouse" user = User.create "mickey" user.add_realm realm, password user.add_role realm, "hero" Now, the important part. How does one sign in a user? How does one keep track of signedin users? Here's how to signin a user: user.signin realm, password Once a user is signed in, the `uuid` method will give a value which can be freely given to the user. The user can later be looked up by turnstile just by using the uuid for that user's session. uuid = user.uuid realm user = User.from_uuid uuid You can also see if a user is signed into a realm, or sign them out. user.signedin? realm user.signout realm == REQUIREMENTS: * Moneta, uuid, and andand gems == INSTALL: gem sources -a http://gems.github.com sudo gem install thefifthcircuit-turnstile To use, either type `turnstile` into your terminal, or create a new text file, type in require 'rubygems' require 'turnstile' $t = Turnstile::Model::Turnstile.new # create and instantiate database Turnstile::Model::Turnstile.init # setup database with default values include Turnstile::Model User.create "minnie" == LICENSE: (The MIT License) Copyright (c) 2008 FIXME (different license?) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/pkg/turnstile-0.0.4/README.txt b/pkg/turnstile-0.0.4/README.txt index e17b952..bcb57b8 100644 --- a/pkg/turnstile-0.0.4/README.txt +++ b/pkg/turnstile-0.0.4/README.txt @@ -1,98 +1,98 @@ turnstile by Roger Jungemann http://thefifthcircuit.com/ == DESCRIPTION: Turnstile is meant to be a flexible authentication and authorization system for Ruby. Currently it is merely a set of "model" classes, although I will shortly release a set of Rack middleware and an HTTP client library which will allow one to create providers, consumers, and clients which are available to Rails apps (or any Rack-compatible app for that matter), for a modest "single sign-on" solution. -Turnstile is built on Moneta, which is a hot-swappable interface for various key-value stores. Moneta uses SDBM as its data-store by default, but it can also use +Turnstile is built on Moneta, which is a hot-swappable interface for various key-value stores. Moneta uses SDBM as its data-store by default, but it can also use Tokyo Cabinet, Redis, or even SQL-based sources, thanks to the DataMapper Moneta wrapper. == FEATURES/PROBLEMS: * Tests are glaringly missing. * I need to add in my set of Rack middleware for creating providers, consumers, and clients. I have a mostly completed set of code for these. * I am considering OAuth and/or OpenID support for my provider, consumer, and client, which could be useful for different aspects of turnstile. == SYNOPSIS: To get started, try typing in `turnstile` in your terminal. This will open a prompt allowing one to interact with the turnstile database. Let's first try and create a role. A role is a collection of limited rights for a particular resource. For example, a web application with a "/treasures" url might want to limit access to that resource to only a small set of users. For example: Role.create "king", "/", "/treasures" Role.create "hero", "/" Role.create "damsel", "/" Next, let's create a realm. A realm is a collection of resources which need to be authorized and authenticated. Let's create a realm called `magical_kingdom` and associate some roles with it. realm = "magical_kingdom" Realm.create realm, "king", "hero", "damsel" Next, let's try actually creating a user. name, password = "mickey", "mouse" user = User.create "mickey" user.add_realm realm, password user.add_role realm, "hero" Now, the important part. How does one sign in a user? How does one keep track of signedin users? Here's how to signin a user: user.signin realm, password Once a user is signed in, the `uuid` method will give a value which can be freely given to the user. The user can later be looked up by turnstile just by using the uuid for that user's session. uuid = user.uuid realm user = User.from_uuid uuid You can also see if a user is signed into a realm, or sign them out. user.signedin? realm user.signout realm == REQUIREMENTS: * Moneta, uuid, and andand gems == INSTALL: gem sources -a http://gems.github.com sudo gem install thefifthcircuit-turnstile To use, either type `turnstile` into your terminal, or create a new text file, type in require 'rubygems' require 'turnstile' $t = Turnstile::Model::Turnstile.new # create and instantiate database Turnstile::Model::Turnstile.init # setup database with default values include Turnstile::Model User.create "minnie" == LICENSE: (The MIT License) Copyright (c) 2008 FIXME (different license?) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
robrohan/coldfusion.tmbundle
55f2a9cc1a6403ba76db29983d78bff0d84ec591
Adding a bit of documentation to the build file
diff --git a/build.xml b/build.xml index edb444c..d744c30 100644 --- a/build.xml +++ b/build.xml @@ -1,74 +1,118 @@ -<project name="ColdFusion Textmate Bundle"> +<project name="ColdFusion Textmate Bundle" default="usage"> <!-- The xslt process needs an XSLT 2.0 processor, so I am using Saxon--> <property name="saxon.path" value="/Applications/saxonb9-1-0-8j/saxon9.jar" /> <!-- Probably wont need to change this unless you are going to try to use a different cfeclipse dictionary file. --> <property name="dictionary.file" value="Resources/cf9.xml" /> <property name="output.name" value="ColdFusion" /> <property name="output.bundle" value="${output.name}.tmbundle" /> <property name="bundle.uuid" value="1A09BE0B-E81A-4CB7-AF69-AFC845162D1F" /> <property name="snytax.uuid" value="97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14" /> <property name="cmddoc.uuid" value="9902B0A3-0523-4190-B541-374AC09CC72F" /> <property name="tagcomplete.uuid" value="A51C20E9-244A-4E9B-8150-B3D55F6CA839" /> <property name="attcomplete.uuid" value="C6F3F140-863E-442D-8ECA-830C4002884E" /> <property name="xsl.file" value="dictToBundle.xsl" /> <property name="doc.xsl.file" value="dictToAPI.xsl" /> <property name="base.bundle" value="ColdFusion.bun" /> + <!-- ///////////////////////////////////////////////////////////////// --> + <target name="usage" description="Basic usage of the ant script. Most useful from the terminal"> + <echo> ** Coldfusion tmbundle Ant Build Script. ** + +You probably want: $ant build + +=================================================================== +usage..................This + +clean..................Cleans up intermediate files, but leaves the +.......................build directory in tact. + +superclean.............Basically just removes the build directory. + +createSnippets.........Creates snippets for all the items in the +.......................dictionary. + +createAPIDoc...........Creates one big HTML file from the dictionary + +createBundle...........Copies all the files into the right structure +.......................for a textmate bundle. + +build..................Does pretty much all of the above (save the +.......................clean stuff). + +=================================================================== +Other general override properties include, but are not limited to + -Doutput.name="" + -Ddictionary.file="" + -Dbundle.uuid="" + -Dsyntax.uuid="" + -Dcmddoc.uuid="" + +For example, to build a Railo bundle you could do: + +ant -Doutput.name=Railo \ + -Ddictionary.file=Resources/railo1.xml \ + -Dbundle.uuid=2E937CBE-9B70-42C6-974A-987E8848251E \ + -Dsyntax.uuid=888FB6E0-4CBC-4521-A51C-3D03AAB85F01 \ + -Dcmddoc.uuid=632D2425-1F06-4944-9712-7EEA5FE7AE54 \ + build + </echo> + </target> + <target name="clean"> <delete dir="build/${output.bundle}" /> </target> <target name="superclean"> <delete dir="build" /> </target> <target name="createSnippets"> <java jar="${saxon.path}" fork="true"> <arg value="-o:build/${output.bundle}/info.plist" /> <arg value="${dictionary.file}" /> <arg value="${xsl.file}" /> <arg value="bundle-uuid=${bundle.uuid}" /> <arg value="bundle-name=${output.name}" /> <arg value="syntax-uuid=${snytax.uuid}" /> <arg value="cmddoc-uuid=${cmddoc.uuid}" /> <arg value="tagcomplete-uuid=${tagcomplete.uuid}" /> <arg value="attcomplete-uuid=${attcomplete.uuid}" /> </java> </target> <target name="createAPIDoc"> <java jar="${saxon.path}" fork="true"> <arg value="-o:doc/${output.name}.html" /> <arg value="${dictionary.file}" /> <arg value="${doc.xsl.file}" /> <!-- <arg value="bundle-uuid=${bundle.uuid}" /> <arg value="bundle-name=${output.name}" /> --> </java> </target> <target name="createBundle"> <copy todir="build/${output.bundle}"> <fileset dir="${base.bundle}"/> <filterset> <filter token="BUNDLE_NAME" value="${output.name}"/> <filter token="BUNDLE_UUID" value="${bundle.uuid}"/> <filter token="SYNTAX_UUID" value="${syntax.uuid}"/> <filter token="CMDDOC_UUID" value="${cmddoc.uuid}"/> <filter token="TAGCOMPLETE_UUID" value="${tagcomplete.uuid}"/> <filter token="ATTRCOMPLETE_UUID" value="${attcomplete.uuid}"/> </filterset> </copy> </target> <target name="build"> <mkdir dir="build" /> <antcall target="createBundle" /> <antcall target="createSnippets" /> <antcall target="createAPIDoc" /> </target> </project> \ No newline at end of file
robrohan/coldfusion.tmbundle
dacab23f3f521ef58c90aff74943f82392e6ca16
Updating the Readme a bit
diff --git a/README b/README index edb9cf8..2f5462a 100644 --- a/README +++ b/README @@ -1,29 +1,39 @@ Authors: Bill Duenskie Rob Rohan (sponsored by Daemon - http://daemon.com.au) -欢迎 -==== - 大家好!Welcome to the ColdFusion Textmate bundle. This bit of code will create a Textmate bundle that contains all the tags, functions, and a few basic templates for ColdFusion. +欢迎 - Welcome +============ - The input to this process is an XML dictionary file in the cfeclipse dictionary format. This means that if you happen to have a cfeclipse dictionary, you can use this code to create a compliant Textmate bundle (with a bit of tweaking of course). +大家好!Welcome to the ColdFusion Textmate bundle. This bit of code will create a [Textmate][textmate] bundle that contains all the tags, functions, and a few basic templates for the CFML language. -Usage -====== +The input to this process is an XML dictionary file in the [cfeclipse][cfeclipse] dictionary format. This means that if you happen to have a cfeclipse dictionary, you can use this code to create a compliant Textmate bundle (with a bit of tweaking of course). - There are a few things you'll need before you can compile the code. The first thing you need is Apache Ant (Free). Ant comes pre-installed on Mac OS 10.5 Leopard, so you should have that already. Type "ant" in the terminal to see if you have it. If you do not have it, you'll need to download and set it up before you can compile. +Building +======== + +There are a few things you'll need before you can compile the code. The first thing you need is [Apache Ant][ant] (Free). Ant comes pre-installed on Mac OS 10.5 Leopard, so you should have that already. Type "ant" in the terminal to see if you have it. If you do not have it, you'll need to [download][ant] and set it up before you can compile. - The second thing you'll need is Saxon 9 (Free). Saxon 9 is an XSLT 2.0 engine. You can use another XSLT 2.0 engine, but you'll need to do some tweaking. After you've downloaded and setup Saxon 9, edit the build.xml file to set the correct path to the Saxon jar file. +The second thing you'll need is [Saxon 9][saxon] (Free). [Saxon 9][saxon] is an XSLT 2.0 engine. You can use another XSLT 2.0 engine, but you'll need to do some tweaking. After you've [downloaded][saxon] and setup [Saxon 9][saxon], edit the build.xml file to set the correct path to the Saxon jar file. - Once both Ant and Saxon are in place, you can build the build with the following command: +Once both Ant and Saxon are in place, you can build the build with the following command: $ant build + +Additionally there are some bash scripts that show examples of how you can build releases using other grammars. - Build will break up the dictionary and create the FarCry.tmbundle. See the build.xml for more information. +The `build` task will break up the dictionary and create the Coldfusion.tmbundle. See the `build.xml` for more information. License ======== Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ + + +[saxon]: http://sourceforge.net/projects/saxon/files/Saxon-B/ "Saxon" +[ant]: http://ant.apache.org/ "Apache Ant" +[cfeclipse]: http://cfeclipse.org "CFEclipse" +[textmate]: http://macromates.com/ "Textmate" +
robrohan/coldfusion.tmbundle
5dcf85b39ced2c38e71248fd22eabe96424c707d
Changed default completion to on
diff --git a/dictToBundle.xsl b/dictToBundle.xsl index 13d3a5b..e9694b3 100644 --- a/dictToBundle.xsl +++ b/dictToBundle.xsl @@ -1,413 +1,413 @@ <?xml version="1.0" encoding="UTF-8" ?> <!-- dictToBundle Created by Rob Rohan on 2008-11-22. Copyright (c) 2008-2009 Rob Rohan. All rights reserved. The default output from this process is the info.plist file. However, this also generates the files for the tag completion and for the default snippets. The snippets wind up in the Snippets directory and the tag and attribute lists wind up in the Preferences folder. --> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:dic="http://www.cfeclipse.org/version1/dictionary" xmlns:util="java:java.util.UUID" version="2.0" exclude-result-prefixes="xsl dic util"> <xsl:output method="xml" indent="yes" /> <xsl:output method="xml" indent="yes" name="plistxml" exclude-result-prefixes="xsl dic util" /> <!-- <xsl:param name="bundle-dir" select="'ColdFusion.bun'" /> --> <xsl:param name="bundle-uuid" select="'1A09BE0B-E81A-4CB7-AF69-AFC845162D1F'" /> <xsl:param name="bundle-name" select="'ColdFusion'" /> <xsl:param name="syntax-uuid" select="''" /> <xsl:param name="cmddoc-uuid" select="''" /> <xsl:param name="tagcomplete-uuid" select="''" /> <xsl:param name="attcomplete-uuid" select="''" /> <xsl:variable name="NL"> <xsl:text> </xsl:text> </xsl:variable> <xsl:variable name="TAB"> <xsl:text> </xsl:text> </xsl:variable> <!-- writes out the plist, and kicks off the snippet writting --> <xsl:template match="/"> <plist version="1.0"> <dict> <key>contactEmailRot13</key> <string>[email protected]</string> <key>contactName</key> <string>Rob Rohan</string> <key>description</key> <string>Support for the CFML web development environment.</string> <key>mainMenu</key> <dict> <key>items</key> <array> <string>C8F9D7A6-D447-4C16-B566-BE46335B1067</string> <string>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</string> <string>------------------------------------</string> <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> <string>------------------------------------</string> <string>54C16A2E-3B74-41AC-BEB1-352F9E42B7EE</string> <string>FFDC5F11-5575-4C8C-9CAC-4DFC1163CFEA</string> <string>0DEA11CD-931E-4087-984A-784A2D825EF2</string> <string>7EC225A6-93C8-4A2E-906A-3ADA1FD3C172</string> <string>8D2B412E-56DF-4728-AB74-C1C674277E22</string> <string><xsl:value-of select="$cmddoc-uuid" /></string> <string><xsl:value-of select="$tagcomplete-uuid" /></string> <string><xsl:value-of select="$attcomplete-uuid" /></string> <!-- Now that we have written out the plist file and the snippets --> <!-- fire off the bit that does the tag and attribute completion --> <xsl:call-template name="write-tag-completion-list" /> <xsl:call-template name="write-attribute-completion-list" /> </array> <key>submenus</key> <dict> <key>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</key> <dict> <key>items</key> <array> <xsl:comment>FUNCTIONS</xsl:comment><xsl:value-of select="$NL" /> <xsl:apply-templates select="/dic:dictionary/dic:functions/dic:function" /> </array> <key>name</key> <string>ColdFusion Functions</string> </dict> <key>C8F9D7A6-D447-4C16-B566-BE46335B1067</key> <dict> <key>items</key> <array> <xsl:comment>TAGS</xsl:comment><xsl:value-of select="$NL" /> <xsl:apply-templates select="/dic:dictionary/dic:tags/dic:tag" /> </array> <key>name</key> <string>ColdFusion Tags</string> </dict> </dict> </dict> <key>name</key> <string><xsl:value-of select="$bundle-name" /></string> <key>ordering</key> <array> <!-- <string>00D00AD7-3C05-46E0-B8B9-0F5CCAC04F57</string> <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> --> </array> <key>uuid</key> <string><xsl:value-of select="$bundle-uuid" /></string> </dict> </plist> </xsl:template> <!-- Formats the functions. Writes the plist too. --> <xsl:template match="dic:function"> <xsl:variable name="filename" select="translate(@name,':','-')" /> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:value-of select="$NL" /> <!-- {$bundle-dir}/ --> <xsl:result-document href="Snippets/gen-{$filename}.tmSnippet" format="plistxml"> <plist version="1.0"> <dict> <key>content</key> <string><xsl:value-of select="@name" /> <xsl:text>(${1:</xsl:text> <xsl:for-each select="./dic:parameter"> <xsl:call-template name="param-with-placement"> <xsl:with-param name="placement" select="position()+1" /> <xsl:with-param name="separator" select="''" /> <xsl:with-param name="preparator" select="', '" /> <xsl:with-param name="use-equals" select="'false'" /> <xsl:with-param name="total-param-count" select="count(../dic:parameter)" /> </xsl:call-template> </xsl:for-each> <xsl:text>})</xsl:text></string> <key>name</key> <string><xsl:value-of select="@name"/></string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string><xsl:value-of select="@name"/></string> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <!-- Formats the tags. Writes out the plist file too --> <xsl:template match="dic:tag"> <xsl:variable name="filename" select="translate(@name,':','-')" /> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:value-of select="$NL" /> <!-- {$bundle-dir}/ --> <xsl:result-document href="Snippets/gen-{$filename}.tmSnippet" format="plistxml"> <plist version="1.0"> <dict> <key>content</key> <string><xsl:text>&lt;</xsl:text> <xsl:value-of select="@name" /> <xsl:text> ${1:</xsl:text> <xsl:for-each select="./dic:parameter"> <xsl:call-template name="param-with-placement"> <xsl:with-param name="placement" select="position()+position()" /> <xsl:with-param name="separator" select="' '" /> <xsl:with-param name="preparator" select="''" /> <xsl:with-param name="use-equals" select="'true'" /> <xsl:with-param name="total-param-count" select="count(../dic:parameter)" /> <!-- <xsl:with-param name="element" select="." /> --> </xsl:call-template> </xsl:for-each> <xsl:text>}</xsl:text> <xsl:choose> <xsl:when test="@single = 'true'"> <xsl:text> /&gt;$0</xsl:text> </xsl:when> <xsl:otherwise> <xsl:text>&gt;</xsl:text> <xsl:value-of select="$NL" /> <xsl:value-of select="$TAB" /> <xsl:text>$0</xsl:text> <xsl:value-of select="$NL" /> <xsl:text>&lt;/</xsl:text> <xsl:value-of select="@name" /> <xsl:text>&gt;</xsl:text> </xsl:otherwise> </xsl:choose></string> <key>name</key> <string><xsl:value-of select="@name"/></string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string> <xsl:choose> <xsl:when test="contains(@name,':')"> <xsl:value-of select="substring-before(@name,':')" /> </xsl:when> <xsl:otherwise> <xsl:value-of select="@name" /> </xsl:otherwise> </xsl:choose> </string> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <!-- handles doing the tag and function params. Takes 3 params. placement = where to start the textmate $N variables from separator = what to tack on to the end of each paramenter total-param-count = total number of params, so we don't add the separator to the last item. --> <xsl:template name="param-with-placement"> <xsl:param name="placement" /> <xsl:param name="separator" /> <xsl:param name="preparator" /> <xsl:param name="use-equals" /> <xsl:param name="total-param-count" /> <xsl:choose> <xsl:when test="$use-equals = 'true'"> <xsl:text>$</xsl:text> <xsl:text>{</xsl:text> <xsl:value-of select="$placement" /> <xsl:text>:</xsl:text> <xsl:value-of select="$preparator" /> <xsl:value-of select="@name" /><xsl:text>="$</xsl:text> <xsl:value-of select="$placement+1" /> <xsl:text>"</xsl:text> <xsl:if test="position() != $total-param-count"> <xsl:value-of select="$separator" /> </xsl:if> <xsl:text>}</xsl:text> </xsl:when> <xsl:otherwise> <xsl:if test="@required = 'true'"> <xsl:if test="position() != 1"> <xsl:value-of select="$preparator" /> </xsl:if> <xsl:if test="@type = 'String'"> <xsl:text>"</xsl:text> </xsl:if> </xsl:if> <xsl:text>${</xsl:text> <xsl:value-of select="$placement" /> <xsl:text>:</xsl:text> <xsl:if test="@required = 'false'"> <xsl:if test="position() != 1"> <xsl:value-of select="$preparator" /> </xsl:if> </xsl:if> <xsl:if test="@required = 'false'"><xsl:text>[</xsl:text></xsl:if> <xsl:value-of select="@name" /> <xsl:if test="@required = 'false'"><xsl:text>]</xsl:text></xsl:if> <xsl:text>}</xsl:text> <xsl:if test="@required = 'true'"> <xsl:if test="@type = 'String'"> <xsl:text>"</xsl:text> </xsl:if> </xsl:if> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- make a list of tags in the format textmate expects for code completion --> <xsl:template name="write-tag-completion-list"> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:result-document href="Preferences/Completion%20Tags.tmPreferences" format="plistxml"> <plist version="1.0"> <dict> <key>name</key> <string>Completions Tags</string> <key>scope</key> <!-- text.html.cfm, invalid.illegal.incomplete.html --> <string>text.html -(meta.tag | source), invalid.illegal.incomplete.html -source</string> <key>settings</key> <dict> <key>shellVariables</key> <array> <dict> <key>name</key> <string>TM_COMPLETION_split</string> <key>value</key> <string>,</string> </dict> <dict> <key>name</key> <string>TM_COMPLETIONS</string> <key>value</key> <string> <xsl:for-each select="//dic:tag"> <xsl:value-of select="replace(./@name,'^cf','')" /><xsl:text>,</xsl:text> </xsl:for-each> </string> </dict> </array> </dict> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> <!-- <string><xsl:value-of select="$tagcomplete-uuid" /></string> --> </dict> </plist> </xsl:result-document> </xsl:template> <xsl:template name="write-attribute-completion-list"> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:result-document href="Preferences/Completion%20Attributes.tmPreferences" format="plistxml"> <plist version="1.0"> <dict> <key>name</key> <string>Completions Attributes</string> <key>scope</key> <!-- text.html meta.tag -(entity.other.attribute-name | punctuation.definition.tag.begin | source | entity.name.tag | string | invalid.illegal.incomplete.html)--> <string>text.html.cfm meta.tag.other.html</string> <key>settings</key> <dict> <key>completions</key> <array> <xsl:for-each select="//dic:tag"> <string><xsl:value-of select="./@name" /></string> <string><xsl:value-of select="translate(@name,'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')" /></string> </xsl:for-each> </array> <key>disableDefaultCompletion</key> - <integer>1</integer> + <integer>0</integer> <key>shellVariables</key> <array> <dict> <key>name</key> <string>TM_COMPLETION_split</string> <key>value</key> <string>,</string> </dict> <dict> <key>name</key> <string>TM_COMPLETION_scope</string> <key>value</key> <string>html_attributes</string> </dict> <dict> <key>name</key> <string>TM_COMPLETIONS</string> <key>value</key> <string> <xsl:for-each select="//dic:tag/dic:parameter"> <xsl:text>&lt;</xsl:text> <xsl:value-of select="../@name" /><xsl:text> </xsl:text> <xsl:value-of select="./@name" /> <xsl:text>=&quot;&quot;</xsl:text> <xsl:text>,</xsl:text> </xsl:for-each> </string> </dict> </array> </dict> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <xsl:template match="text()" /> </xsl:stylesheet> \ No newline at end of file
robrohan/coldfusion.tmbundle
88cc1aadb34008a39b76740b2e4882e44eae52e5
Small patch for the miss coloured "id", bug 21eb0a; however this isn't a full fix just a small patch. Full fix will require a bit more work.
diff --git a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage index 0b7a85c..48d2fcb 100644 --- a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage +++ b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage @@ -204,672 +204,672 @@ <key>end</key> <string>&lt;/((?i:cfquery))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.sql.embedded.html</string> <key>patterns</key> <array> <!-- this is here to colour the cfquery tag's attributes --> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:cfquery))</string> <key>patterns</key> <array> <!-- <dict> <key>include</key> <string>#embedded-code</string> </dict> --> <dict> <key>include</key> <string>source.sql</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:script))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(script|SCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:script|SCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:script))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/script)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/script)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfscript))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(cfscript|CFSCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:cfscript|CFSCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:cfscript))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/cfscript)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/cfscript)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:body|head|html)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.structure.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.structure.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:address|blockquote|dd|div|dl|dt|fieldset|form|frame|frameset|h1|h2 |h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|menu|pre)\ b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.block.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.block.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite |code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|la bel|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script| select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot |th|thead|title|tr|tt|u|var)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.inline.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.inline.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?([a-zA-Z0-9:]+)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>include</key> <string>#entities</string> </dict> <dict> <key>match</key> <string>&lt;&gt;</string> <key>name</key> <string>invalid.illegal.incomplete.html</string> </dict> <dict> <key>match</key> <string>&lt;(?=\W)|&gt;</string> <key>name</key> <string>invalid.illegal.bad-angle-bracket.html</string> </dict> </array> <key>repository</key> <dict> <key>cfcomment</key> <dict> <key>begin</key> <string>&lt;!---</string> <key>end</key> <string>---\s*&gt;</string> <key>name</key> <!-- <string>comment.block.html</string> --> <string>comment.line</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#cfcomment</string> </dict> <!-- <dict> <key>match</key> <string>-=-=-</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> --> </array> </dict> <key>htmlcomment</key> <dict> <key>begin</key> <string>&lt;!--</string> <key>end</key> <string>--&gt;</string> <key>name</key> <string>comment.block.html</string> <key>patterns</key> <array> <dict> <key>match</key> <string>--</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> </array> </dict> <key>cffunction</key> <dict> <key>begin</key> <string>&lt;(cffunction)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>entity.other.attribute-name.html</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.string.begin</string> </dict> <key>4</key> <dict> <key>name</key> <string>entity.name.function.cfml</string> </dict> <key>5</key> <dict> <key>name</key> <string>punctuation.definition.string.end</string> </dict> </dict> <key>match</key> <string>\b([nN][aA][mM][Ee])\b\s*(=)\s*(["'])([A-Za-z$_0-9]+)(["'])</string> </dict> <dict> <key>include</key> <string>source.cfml</string> </dict> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <key>embedded-code</key> <dict> <key>patterns</key> <array> <!-- <dict> <key>include</key> <string>#php</string> </dict> <dict> <key>include</key> <string>#ruby</string> </dict> <dict> <key>include</key> <string>#smarty</string> </dict> <dict> <key>include</key> <string>#python</string> </dict> --> <dict> <key>include</key> <string>#javascript</string> </dict> </array> </dict> <key>entities</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>&amp;([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);</string> <key>name</key> <string>constant.character.entity.html</string> </dict> <dict> <key>match</key> <string>&amp;</string> <key>name</key> <string>invalid.illegal.bad-ampersand.html</string> </dict> </array> </dict> <key>string-double-quoted</key> <dict> <key>begin</key> <string>"</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <key>string-single-quoted</key> <dict> <key>begin</key> <string>'</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <!-- Does function calls. For example, the xmlparse in cfset x=xmlparse() --> <key>inline-function-stuff</key> <dict> <key>begin</key> <!-- [^\#"'] --> <string>[a-zA-Z0-9_\.]+\(</string> <key>contentName</key> <string>support.function.parameters</string> <key>end</key> <string>\)</string> <key>name</key> <string>support.function</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#inline-function-stuff</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> </array> </dict> <!-- the stuff between the ## --> <key>coldfusion-script</key> <dict> <key>begin</key> <string>#</string> <key>end</key> <string>\#</string> <key>name</key> <string>source.coldfusion.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#inline-function-stuff</string> </dict> <dict> <key>include</key> <string>#embedded-code</string> </dict> </array> </dict> <!-- normal attributes --> <key>tag-generic-attribute</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>\b([a-zA-Z0-9_\-:]+)</string> <key>name</key> <string>entity.other.attribute-name.html</string> </dict> </array> </dict> <!-- ID attributes on elements (shows up in the symbol list) --> <key>tag-id-attribute</key> <dict> <key>begin</key> - <string>\b(id)\b\s*=</string> + <string>[^\.]\b(id)\b\s*=</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.other.attribute-name.id.html</string> </dict> </dict> <key>end</key> <string>(?&lt;='|")</string> <key>name</key> <string>meta.attribute-with-value.id.html</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>"</string> <key>contentName</key> <string>meta.toc-list.id.html</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <dict> <key>begin</key> <string>'</string> <key>contentName</key> <string>meta.toc-list.id.html</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> </array> </dict> <!-- handles all the inner workings of the tags --> <key>tag-stuff</key> <dict> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-id-attribute</string> </dict> <dict> <key>include</key> <string>#inline-function-stuff</string> </dict> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> <dict> <key>include</key> <string>#coldfusion-script</string> </dict> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>match</key> <string>.var\s</string> <key>name</key> <string>variable.other</string> </dict> <dict> <key>begin</key> <string>.&lt;cffunction\sname=('|")1</string> <key>contentName</key> <string>entity.name.function</string> <key>end</key> <string>'|"1</string> <key>name</key> <string>meta.tag.other</string> </dict> </array> </dict> <key>tag-finder</key> <dict> <key>begin</key> <string>&lt;([a-zA-Z0-9:]+)(?=[^&gt;]*&gt;&lt;/\1&gt;)</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.html</string> </dict> </dict> <key>end</key> <string>&gt;(&lt;)/(\1)&gt;</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>meta.scope.between-tag-pair.html</string> </dict> <key>2</key> <dict> <key>name</key> <string>entity.name.tag.html</string> </dict> </dict> <key>name</key> <string>meta.tag.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> </dict> <key>scopeName</key> <string>text.html.cfm</string> <key>uuid</key> <string>@SYNTAX_UUID@</string> </dict> </plist>
robrohan/coldfusion.tmbundle
96c2f063248beddd972a0213a1a58debe690b1db
Added spell checking for comments
diff --git a/ColdFusion.bun/Preferences/Comment.tmPreferences b/ColdFusion.bun/Preferences/Comment.tmPreferences index 863cd58..601e41e 100644 --- a/ColdFusion.bun/Preferences/Comment.tmPreferences +++ b/ColdFusion.bun/Preferences/Comment.tmPreferences @@ -1,33 +1,32 @@ <?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>name</key> <string>Comments</string> - <key>scope</key> <string>text.html.cfm</string> - <key>settings</key> <dict> + <key>spellChecking</key> + <string>1</string> <key>shellVariables</key> <array> <dict> <key>name</key> <string>TM_COMMENT_START</string> <key>value</key> <string>&lt;!--- </string> </dict> <dict> <key>name</key> <string>TM_COMMENT_END</string> <key>value</key> <string> ---&gt;</string> </dict> </array> </dict> - <key>uuid</key> <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> </dict> </plist> diff --git a/dictToBundle.xsl b/dictToBundle.xsl index cfd8fd9..13d3a5b 100644 --- a/dictToBundle.xsl +++ b/dictToBundle.xsl @@ -1,413 +1,413 @@ <?xml version="1.0" encoding="UTF-8" ?> <!-- dictToBundle Created by Rob Rohan on 2008-11-22. Copyright (c) 2008-2009 Rob Rohan. All rights reserved. The default output from this process is the info.plist file. However, this also generates the files for the tag completion and for the default snippets. The snippets wind up in the Snippets directory and the tag and attribute lists wind up in the Preferences folder. --> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:dic="http://www.cfeclipse.org/version1/dictionary" xmlns:util="java:java.util.UUID" version="2.0" exclude-result-prefixes="xsl dic util"> <xsl:output method="xml" indent="yes" /> <xsl:output method="xml" indent="yes" name="plistxml" exclude-result-prefixes="xsl dic util" /> <!-- <xsl:param name="bundle-dir" select="'ColdFusion.bun'" /> --> <xsl:param name="bundle-uuid" select="'1A09BE0B-E81A-4CB7-AF69-AFC845162D1F'" /> <xsl:param name="bundle-name" select="'ColdFusion'" /> <xsl:param name="syntax-uuid" select="''" /> <xsl:param name="cmddoc-uuid" select="''" /> <xsl:param name="tagcomplete-uuid" select="''" /> <xsl:param name="attcomplete-uuid" select="''" /> <xsl:variable name="NL"> <xsl:text> </xsl:text> </xsl:variable> <xsl:variable name="TAB"> <xsl:text> </xsl:text> </xsl:variable> <!-- writes out the plist, and kicks off the snippet writting --> <xsl:template match="/"> <plist version="1.0"> <dict> <key>contactEmailRot13</key> <string>[email protected]</string> <key>contactName</key> <string>Rob Rohan</string> <key>description</key> - <string>Support for the ColdFusion web development environment.</string> + <string>Support for the CFML web development environment.</string> <key>mainMenu</key> <dict> <key>items</key> <array> <string>C8F9D7A6-D447-4C16-B566-BE46335B1067</string> <string>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</string> <string>------------------------------------</string> <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> <string>------------------------------------</string> <string>54C16A2E-3B74-41AC-BEB1-352F9E42B7EE</string> <string>FFDC5F11-5575-4C8C-9CAC-4DFC1163CFEA</string> <string>0DEA11CD-931E-4087-984A-784A2D825EF2</string> <string>7EC225A6-93C8-4A2E-906A-3ADA1FD3C172</string> <string>8D2B412E-56DF-4728-AB74-C1C674277E22</string> <string><xsl:value-of select="$cmddoc-uuid" /></string> <string><xsl:value-of select="$tagcomplete-uuid" /></string> <string><xsl:value-of select="$attcomplete-uuid" /></string> <!-- Now that we have written out the plist file and the snippets --> <!-- fire off the bit that does the tag and attribute completion --> <xsl:call-template name="write-tag-completion-list" /> <xsl:call-template name="write-attribute-completion-list" /> </array> <key>submenus</key> <dict> <key>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</key> <dict> <key>items</key> <array> <xsl:comment>FUNCTIONS</xsl:comment><xsl:value-of select="$NL" /> <xsl:apply-templates select="/dic:dictionary/dic:functions/dic:function" /> </array> <key>name</key> <string>ColdFusion Functions</string> </dict> <key>C8F9D7A6-D447-4C16-B566-BE46335B1067</key> <dict> <key>items</key> <array> <xsl:comment>TAGS</xsl:comment><xsl:value-of select="$NL" /> <xsl:apply-templates select="/dic:dictionary/dic:tags/dic:tag" /> </array> <key>name</key> <string>ColdFusion Tags</string> </dict> </dict> </dict> <key>name</key> <string><xsl:value-of select="$bundle-name" /></string> <key>ordering</key> <array> <!-- <string>00D00AD7-3C05-46E0-B8B9-0F5CCAC04F57</string> <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> --> </array> <key>uuid</key> <string><xsl:value-of select="$bundle-uuid" /></string> </dict> </plist> </xsl:template> <!-- Formats the functions. Writes the plist too. --> <xsl:template match="dic:function"> <xsl:variable name="filename" select="translate(@name,':','-')" /> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:value-of select="$NL" /> <!-- {$bundle-dir}/ --> <xsl:result-document href="Snippets/gen-{$filename}.tmSnippet" format="plistxml"> <plist version="1.0"> <dict> <key>content</key> <string><xsl:value-of select="@name" /> <xsl:text>(${1:</xsl:text> <xsl:for-each select="./dic:parameter"> <xsl:call-template name="param-with-placement"> <xsl:with-param name="placement" select="position()+1" /> <xsl:with-param name="separator" select="''" /> <xsl:with-param name="preparator" select="', '" /> <xsl:with-param name="use-equals" select="'false'" /> <xsl:with-param name="total-param-count" select="count(../dic:parameter)" /> </xsl:call-template> </xsl:for-each> <xsl:text>})</xsl:text></string> <key>name</key> <string><xsl:value-of select="@name"/></string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string><xsl:value-of select="@name"/></string> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <!-- Formats the tags. Writes out the plist file too --> <xsl:template match="dic:tag"> <xsl:variable name="filename" select="translate(@name,':','-')" /> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:value-of select="$NL" /> <!-- {$bundle-dir}/ --> <xsl:result-document href="Snippets/gen-{$filename}.tmSnippet" format="plistxml"> <plist version="1.0"> <dict> <key>content</key> <string><xsl:text>&lt;</xsl:text> <xsl:value-of select="@name" /> <xsl:text> ${1:</xsl:text> <xsl:for-each select="./dic:parameter"> <xsl:call-template name="param-with-placement"> <xsl:with-param name="placement" select="position()+position()" /> <xsl:with-param name="separator" select="' '" /> <xsl:with-param name="preparator" select="''" /> <xsl:with-param name="use-equals" select="'true'" /> <xsl:with-param name="total-param-count" select="count(../dic:parameter)" /> <!-- <xsl:with-param name="element" select="." /> --> </xsl:call-template> </xsl:for-each> <xsl:text>}</xsl:text> <xsl:choose> <xsl:when test="@single = 'true'"> <xsl:text> /&gt;$0</xsl:text> </xsl:when> <xsl:otherwise> <xsl:text>&gt;</xsl:text> <xsl:value-of select="$NL" /> <xsl:value-of select="$TAB" /> <xsl:text>$0</xsl:text> <xsl:value-of select="$NL" /> <xsl:text>&lt;/</xsl:text> <xsl:value-of select="@name" /> <xsl:text>&gt;</xsl:text> </xsl:otherwise> </xsl:choose></string> <key>name</key> <string><xsl:value-of select="@name"/></string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string> <xsl:choose> <xsl:when test="contains(@name,':')"> <xsl:value-of select="substring-before(@name,':')" /> </xsl:when> <xsl:otherwise> <xsl:value-of select="@name" /> </xsl:otherwise> </xsl:choose> </string> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <!-- handles doing the tag and function params. Takes 3 params. placement = where to start the textmate $N variables from separator = what to tack on to the end of each paramenter total-param-count = total number of params, so we don't add the separator to the last item. --> <xsl:template name="param-with-placement"> <xsl:param name="placement" /> <xsl:param name="separator" /> <xsl:param name="preparator" /> <xsl:param name="use-equals" /> <xsl:param name="total-param-count" /> <xsl:choose> <xsl:when test="$use-equals = 'true'"> <xsl:text>$</xsl:text> <xsl:text>{</xsl:text> <xsl:value-of select="$placement" /> <xsl:text>:</xsl:text> <xsl:value-of select="$preparator" /> <xsl:value-of select="@name" /><xsl:text>="$</xsl:text> <xsl:value-of select="$placement+1" /> <xsl:text>"</xsl:text> <xsl:if test="position() != $total-param-count"> <xsl:value-of select="$separator" /> </xsl:if> <xsl:text>}</xsl:text> </xsl:when> <xsl:otherwise> <xsl:if test="@required = 'true'"> <xsl:if test="position() != 1"> <xsl:value-of select="$preparator" /> </xsl:if> <xsl:if test="@type = 'String'"> <xsl:text>"</xsl:text> </xsl:if> </xsl:if> <xsl:text>${</xsl:text> <xsl:value-of select="$placement" /> <xsl:text>:</xsl:text> <xsl:if test="@required = 'false'"> <xsl:if test="position() != 1"> <xsl:value-of select="$preparator" /> </xsl:if> </xsl:if> <xsl:if test="@required = 'false'"><xsl:text>[</xsl:text></xsl:if> <xsl:value-of select="@name" /> <xsl:if test="@required = 'false'"><xsl:text>]</xsl:text></xsl:if> <xsl:text>}</xsl:text> <xsl:if test="@required = 'true'"> <xsl:if test="@type = 'String'"> <xsl:text>"</xsl:text> </xsl:if> </xsl:if> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- make a list of tags in the format textmate expects for code completion --> <xsl:template name="write-tag-completion-list"> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:result-document href="Preferences/Completion%20Tags.tmPreferences" format="plistxml"> <plist version="1.0"> <dict> <key>name</key> <string>Completions Tags</string> <key>scope</key> <!-- text.html.cfm, invalid.illegal.incomplete.html --> <string>text.html -(meta.tag | source), invalid.illegal.incomplete.html -source</string> <key>settings</key> <dict> <key>shellVariables</key> <array> <dict> <key>name</key> <string>TM_COMPLETION_split</string> <key>value</key> <string>,</string> </dict> <dict> <key>name</key> <string>TM_COMPLETIONS</string> <key>value</key> <string> <xsl:for-each select="//dic:tag"> <xsl:value-of select="replace(./@name,'^cf','')" /><xsl:text>,</xsl:text> </xsl:for-each> </string> </dict> </array> </dict> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> <!-- <string><xsl:value-of select="$tagcomplete-uuid" /></string> --> </dict> </plist> </xsl:result-document> </xsl:template> <xsl:template name="write-attribute-completion-list"> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:result-document href="Preferences/Completion%20Attributes.tmPreferences" format="plistxml"> <plist version="1.0"> <dict> <key>name</key> <string>Completions Attributes</string> <key>scope</key> <!-- text.html meta.tag -(entity.other.attribute-name | punctuation.definition.tag.begin | source | entity.name.tag | string | invalid.illegal.incomplete.html)--> <string>text.html.cfm meta.tag.other.html</string> <key>settings</key> <dict> <key>completions</key> <array> <xsl:for-each select="//dic:tag"> <string><xsl:value-of select="./@name" /></string> <string><xsl:value-of select="translate(@name,'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')" /></string> </xsl:for-each> </array> <key>disableDefaultCompletion</key> <integer>1</integer> <key>shellVariables</key> <array> <dict> <key>name</key> <string>TM_COMPLETION_split</string> <key>value</key> <string>,</string> </dict> <dict> <key>name</key> <string>TM_COMPLETION_scope</string> <key>value</key> <string>html_attributes</string> </dict> <dict> <key>name</key> <string>TM_COMPLETIONS</string> <key>value</key> <string> <xsl:for-each select="//dic:tag/dic:parameter"> <xsl:text>&lt;</xsl:text> <xsl:value-of select="../@name" /><xsl:text> </xsl:text> <xsl:value-of select="./@name" /> <xsl:text>=&quot;&quot;</xsl:text> <xsl:text>,</xsl:text> </xsl:for-each> </string> </dict> </array> </dict> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <xsl:template match="text()" /> </xsl:stylesheet> \ No newline at end of file
robrohan/coldfusion.tmbundle
abc0ebadb9c01af1d674c17f275d38f9dc0e3147
Added a "jump to function" feature
diff --git a/ColdFusion.bun/Commands/JumpToDeclaration.tmCommand b/ColdFusion.bun/Commands/JumpToDeclaration.tmCommand new file mode 100644 index 0000000..aeb49cc --- /dev/null +++ b/ColdFusion.bun/Commands/JumpToDeclaration.tmCommand @@ -0,0 +1,61 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>beforeRunningCommand</key> + <string>nop</string> + + <key>bundleUUID</key> + <string>@BUNDLE_UUID@</string> + + <key>command</key> + <string><![CDATA[#!/bin/sh + FUNC="${TM_CURRENT_WORD}" + DIR="${TM_PROJECT_DIRECTORY}" + OUTPUT='' + + FILES=(`find "${DIR}" -type f | egrep '\.(cfm|cfml|cfc)$'`) + + # Look for a function declaration within a files contents. + # <file> <function> + function lookup_function { + local line=`nl -b a "${1}" | grep "<cffunction.*name=[\"\']${2}[\"\']" | awk '{print $1}'` + if [[ "$line" -gt 0 ]]; then + mate "${1}" -l "$line" + exit 0 + fi + } + + # Iterate files + for (( i=0; i < ${#FILES[*]}; i++)); do + file="${FILES[${i}]}" + lookup_function "${file}" "${FUNC}" + done + + # Nothing found + echo 'Function '${FUNC}' was not found within the current project.' + ]]> + </string> + + <key>fallbackInput</key> + <string>line</string> + + <key>input</key> + <string>selection</string> + + <key>keyEquivalent</key> + <string>^~@j</string> + + <key>name</key> + <string>Jump To Function Declaration</string> + + <key>output</key> + <string>showAsTooltip</string> + + <key>scope</key> + <string>text.html invalid.illegal.incomplete.cfml, text.html.cfm</string> + + <key>uuid</key> + <string>54C16A2E-3B74-41AC-BEB1-352F9E42B7EE</string> +</dict> +</plist> diff --git a/dictToBundle.xsl b/dictToBundle.xsl index 6159bb9..cfd8fd9 100644 --- a/dictToBundle.xsl +++ b/dictToBundle.xsl @@ -1,412 +1,413 @@ <?xml version="1.0" encoding="UTF-8" ?> <!-- dictToBundle Created by Rob Rohan on 2008-11-22. Copyright (c) 2008-2009 Rob Rohan. All rights reserved. The default output from this process is the info.plist file. However, this also generates the files for the tag completion and for the default snippets. The snippets wind up in the Snippets directory and the tag and attribute lists wind up in the Preferences folder. --> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:dic="http://www.cfeclipse.org/version1/dictionary" xmlns:util="java:java.util.UUID" version="2.0" exclude-result-prefixes="xsl dic util"> <xsl:output method="xml" indent="yes" /> <xsl:output method="xml" indent="yes" name="plistxml" exclude-result-prefixes="xsl dic util" /> <!-- <xsl:param name="bundle-dir" select="'ColdFusion.bun'" /> --> <xsl:param name="bundle-uuid" select="'1A09BE0B-E81A-4CB7-AF69-AFC845162D1F'" /> <xsl:param name="bundle-name" select="'ColdFusion'" /> <xsl:param name="syntax-uuid" select="''" /> <xsl:param name="cmddoc-uuid" select="''" /> <xsl:param name="tagcomplete-uuid" select="''" /> <xsl:param name="attcomplete-uuid" select="''" /> <xsl:variable name="NL"> <xsl:text> </xsl:text> </xsl:variable> <xsl:variable name="TAB"> <xsl:text> </xsl:text> </xsl:variable> <!-- writes out the plist, and kicks off the snippet writting --> <xsl:template match="/"> <plist version="1.0"> <dict> <key>contactEmailRot13</key> <string>[email protected]</string> <key>contactName</key> <string>Rob Rohan</string> <key>description</key> <string>Support for the ColdFusion web development environment.</string> <key>mainMenu</key> <dict> <key>items</key> <array> <string>C8F9D7A6-D447-4C16-B566-BE46335B1067</string> <string>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</string> <string>------------------------------------</string> <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> <string>------------------------------------</string> + <string>54C16A2E-3B74-41AC-BEB1-352F9E42B7EE</string> <string>FFDC5F11-5575-4C8C-9CAC-4DFC1163CFEA</string> <string>0DEA11CD-931E-4087-984A-784A2D825EF2</string> <string>7EC225A6-93C8-4A2E-906A-3ADA1FD3C172</string> <string>8D2B412E-56DF-4728-AB74-C1C674277E22</string> <string><xsl:value-of select="$cmddoc-uuid" /></string> <string><xsl:value-of select="$tagcomplete-uuid" /></string> <string><xsl:value-of select="$attcomplete-uuid" /></string> <!-- Now that we have written out the plist file and the snippets --> <!-- fire off the bit that does the tag and attribute completion --> <xsl:call-template name="write-tag-completion-list" /> <xsl:call-template name="write-attribute-completion-list" /> </array> <key>submenus</key> <dict> <key>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</key> <dict> <key>items</key> <array> <xsl:comment>FUNCTIONS</xsl:comment><xsl:value-of select="$NL" /> <xsl:apply-templates select="/dic:dictionary/dic:functions/dic:function" /> </array> <key>name</key> <string>ColdFusion Functions</string> </dict> <key>C8F9D7A6-D447-4C16-B566-BE46335B1067</key> <dict> <key>items</key> <array> <xsl:comment>TAGS</xsl:comment><xsl:value-of select="$NL" /> <xsl:apply-templates select="/dic:dictionary/dic:tags/dic:tag" /> </array> <key>name</key> <string>ColdFusion Tags</string> </dict> </dict> </dict> <key>name</key> <string><xsl:value-of select="$bundle-name" /></string> <key>ordering</key> <array> <!-- <string>00D00AD7-3C05-46E0-B8B9-0F5CCAC04F57</string> <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> --> </array> <key>uuid</key> <string><xsl:value-of select="$bundle-uuid" /></string> </dict> </plist> </xsl:template> <!-- Formats the functions. Writes the plist too. --> <xsl:template match="dic:function"> <xsl:variable name="filename" select="translate(@name,':','-')" /> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:value-of select="$NL" /> <!-- {$bundle-dir}/ --> <xsl:result-document href="Snippets/gen-{$filename}.tmSnippet" format="plistxml"> <plist version="1.0"> <dict> <key>content</key> <string><xsl:value-of select="@name" /> <xsl:text>(${1:</xsl:text> <xsl:for-each select="./dic:parameter"> <xsl:call-template name="param-with-placement"> <xsl:with-param name="placement" select="position()+1" /> <xsl:with-param name="separator" select="''" /> <xsl:with-param name="preparator" select="', '" /> <xsl:with-param name="use-equals" select="'false'" /> <xsl:with-param name="total-param-count" select="count(../dic:parameter)" /> </xsl:call-template> </xsl:for-each> <xsl:text>})</xsl:text></string> <key>name</key> <string><xsl:value-of select="@name"/></string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string><xsl:value-of select="@name"/></string> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <!-- Formats the tags. Writes out the plist file too --> <xsl:template match="dic:tag"> <xsl:variable name="filename" select="translate(@name,':','-')" /> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:value-of select="$NL" /> <!-- {$bundle-dir}/ --> <xsl:result-document href="Snippets/gen-{$filename}.tmSnippet" format="plistxml"> <plist version="1.0"> <dict> <key>content</key> <string><xsl:text>&lt;</xsl:text> <xsl:value-of select="@name" /> <xsl:text> ${1:</xsl:text> <xsl:for-each select="./dic:parameter"> <xsl:call-template name="param-with-placement"> <xsl:with-param name="placement" select="position()+position()" /> <xsl:with-param name="separator" select="' '" /> <xsl:with-param name="preparator" select="''" /> <xsl:with-param name="use-equals" select="'true'" /> <xsl:with-param name="total-param-count" select="count(../dic:parameter)" /> <!-- <xsl:with-param name="element" select="." /> --> </xsl:call-template> </xsl:for-each> <xsl:text>}</xsl:text> <xsl:choose> <xsl:when test="@single = 'true'"> <xsl:text> /&gt;$0</xsl:text> </xsl:when> <xsl:otherwise> <xsl:text>&gt;</xsl:text> <xsl:value-of select="$NL" /> <xsl:value-of select="$TAB" /> <xsl:text>$0</xsl:text> <xsl:value-of select="$NL" /> <xsl:text>&lt;/</xsl:text> <xsl:value-of select="@name" /> <xsl:text>&gt;</xsl:text> </xsl:otherwise> </xsl:choose></string> <key>name</key> <string><xsl:value-of select="@name"/></string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string> <xsl:choose> <xsl:when test="contains(@name,':')"> <xsl:value-of select="substring-before(@name,':')" /> </xsl:when> <xsl:otherwise> <xsl:value-of select="@name" /> </xsl:otherwise> </xsl:choose> </string> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <!-- handles doing the tag and function params. Takes 3 params. placement = where to start the textmate $N variables from separator = what to tack on to the end of each paramenter total-param-count = total number of params, so we don't add the separator to the last item. --> <xsl:template name="param-with-placement"> <xsl:param name="placement" /> <xsl:param name="separator" /> <xsl:param name="preparator" /> <xsl:param name="use-equals" /> <xsl:param name="total-param-count" /> <xsl:choose> <xsl:when test="$use-equals = 'true'"> <xsl:text>$</xsl:text> <xsl:text>{</xsl:text> <xsl:value-of select="$placement" /> <xsl:text>:</xsl:text> <xsl:value-of select="$preparator" /> <xsl:value-of select="@name" /><xsl:text>="$</xsl:text> <xsl:value-of select="$placement+1" /> <xsl:text>"</xsl:text> <xsl:if test="position() != $total-param-count"> <xsl:value-of select="$separator" /> </xsl:if> <xsl:text>}</xsl:text> </xsl:when> <xsl:otherwise> <xsl:if test="@required = 'true'"> <xsl:if test="position() != 1"> <xsl:value-of select="$preparator" /> </xsl:if> <xsl:if test="@type = 'String'"> <xsl:text>"</xsl:text> </xsl:if> </xsl:if> <xsl:text>${</xsl:text> <xsl:value-of select="$placement" /> <xsl:text>:</xsl:text> <xsl:if test="@required = 'false'"> <xsl:if test="position() != 1"> <xsl:value-of select="$preparator" /> </xsl:if> </xsl:if> <xsl:if test="@required = 'false'"><xsl:text>[</xsl:text></xsl:if> <xsl:value-of select="@name" /> <xsl:if test="@required = 'false'"><xsl:text>]</xsl:text></xsl:if> <xsl:text>}</xsl:text> <xsl:if test="@required = 'true'"> <xsl:if test="@type = 'String'"> <xsl:text>"</xsl:text> </xsl:if> </xsl:if> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- make a list of tags in the format textmate expects for code completion --> <xsl:template name="write-tag-completion-list"> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:result-document href="Preferences/Completion%20Tags.tmPreferences" format="plistxml"> <plist version="1.0"> <dict> <key>name</key> <string>Completions Tags</string> <key>scope</key> <!-- text.html.cfm, invalid.illegal.incomplete.html --> <string>text.html -(meta.tag | source), invalid.illegal.incomplete.html -source</string> <key>settings</key> <dict> <key>shellVariables</key> <array> <dict> <key>name</key> <string>TM_COMPLETION_split</string> <key>value</key> <string>,</string> </dict> <dict> <key>name</key> <string>TM_COMPLETIONS</string> <key>value</key> <string> <xsl:for-each select="//dic:tag"> <xsl:value-of select="replace(./@name,'^cf','')" /><xsl:text>,</xsl:text> </xsl:for-each> </string> </dict> </array> </dict> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> <!-- <string><xsl:value-of select="$tagcomplete-uuid" /></string> --> </dict> </plist> </xsl:result-document> </xsl:template> <xsl:template name="write-attribute-completion-list"> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:result-document href="Preferences/Completion%20Attributes.tmPreferences" format="plistxml"> <plist version="1.0"> <dict> <key>name</key> <string>Completions Attributes</string> <key>scope</key> <!-- text.html meta.tag -(entity.other.attribute-name | punctuation.definition.tag.begin | source | entity.name.tag | string | invalid.illegal.incomplete.html)--> <string>text.html.cfm meta.tag.other.html</string> <key>settings</key> <dict> <key>completions</key> <array> <xsl:for-each select="//dic:tag"> <string><xsl:value-of select="./@name" /></string> <string><xsl:value-of select="translate(@name,'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')" /></string> </xsl:for-each> </array> <key>disableDefaultCompletion</key> <integer>1</integer> <key>shellVariables</key> <array> <dict> <key>name</key> <string>TM_COMPLETION_split</string> <key>value</key> <string>,</string> </dict> <dict> <key>name</key> <string>TM_COMPLETION_scope</string> <key>value</key> <string>html_attributes</string> </dict> <dict> <key>name</key> <string>TM_COMPLETIONS</string> <key>value</key> <string> <xsl:for-each select="//dic:tag/dic:parameter"> <xsl:text>&lt;</xsl:text> <xsl:value-of select="../@name" /><xsl:text> </xsl:text> <xsl:value-of select="./@name" /> <xsl:text>=&quot;&quot;</xsl:text> <xsl:text>,</xsl:text> </xsl:for-each> </string> </dict> </array> </dict> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <xsl:template match="text()" /> </xsl:stylesheet> \ No newline at end of file
robrohan/coldfusion.tmbundle
b8d4c43f50dd50eef4dc5763d7054ee02424923f
The UUID was not getting all the way to the Attribute command, and I added ^> to the cfoutput snippet to override the default behavior of <%= %> which is what is was doing.
diff --git a/ColdFusion.bun/Commands/CodeCompletion Attributes.tmCommand b/ColdFusion.bun/Commands/CodeCompletion Attributes.tmCommand index 1b04e9c..f33aef5 100644 --- a/ColdFusion.bun/Commands/CodeCompletion Attributes.tmCommand +++ b/ColdFusion.bun/Commands/CodeCompletion Attributes.tmCommand @@ -1,38 +1,38 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>beforeRunningCommand</key> <string>nop</string> <key>bundleUUID</key> <string>@BUNDLE_UUID@</string> <key>command</key> <string>#!/usr/bin/env ruby require &quot;#{ENV[&apos;TM_SUPPORT_PATH&apos;]}/lib/codecompletion&quot; TextmateCodeCompletion.go!</string> <key>fallbackInput</key> <string>line</string> <key>input</key> <string>selection</string> <key>keyEquivalent</key> <string>^ </string> <key>name</key> <string>CodeCompletion Attributes</string> <key>output</key> <string>insertAsSnippet</string> <key>scope</key> - <!-- text.html.cfml meta.tag --> - <string>text.html punctuation.definition.tag -source, text.html meta.tag -entity.other.attribute-name -source</string> + <!-- <string>text.html punctuation.definition.tag -source, text.html meta.tag -entity.other.attribute-name -source</string> --> + <string>meta.tag.other.html -string.quoted.double</string> <key>uuid</key> <string>@ATTRCOMPLETE_UUID@</string> </dict> </plist> diff --git a/ColdFusion.bun/Commands/CodeCompletion Tags.tmCommand b/ColdFusion.bun/Commands/CodeCompletion Tags.tmCommand index 5ec0975..ce7ad45 100644 --- a/ColdFusion.bun/Commands/CodeCompletion Tags.tmCommand +++ b/ColdFusion.bun/Commands/CodeCompletion Tags.tmCommand @@ -1,40 +1,41 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>beforeRunningCommand</key> <string>nop</string> <key>bundleUUID</key> <string>@BUNDLE_UUID@</string> <key>command</key> <string><![CDATA[#!/usr/bin/env ruby require "#{ENV["TM_SUPPORT_PATH"]}/lib/codecompletion"; ENV["TM_COMPLETION_characters"]="/cf/"; TextmateCodeCompletion.go! ]]></string> <key>fallbackInput</key> <string>line</string> <key>input</key> <string>selection</string> <key>keyEquivalent</key> <string>^ </string> <key>name</key> <string>CodeCompletion Tags</string> <key>output</key> <string>insertAsSnippet</string> <key>scope</key> <!-- text.html.cfml invalid.illegal.incomplete.html --> - <string>text.html text.html.cfml meta.tag.other.html -entity.other.attribute-name -string.quoted, invalid.illegal.incomplete.cfml</string> + <!-- <string>text.html text.html.cfml meta.tag.other.html -entity.other.attribute-name -string.quoted, invalid.illegal.incomplete.cfml</string> --> + <string>text.html invalid.illegal.incomplete.cfml</string> <key>uuid</key> <string>@TAGCOMPLETE_UUID@</string> </dict> </plist> diff --git a/ColdFusion.bun/Snippets/x_output.tmSnippet b/ColdFusion.bun/Snippets/x_output.tmSnippet index b518b52..87f61ce 100644 --- a/ColdFusion.bun/Snippets/x_output.tmSnippet +++ b/ColdFusion.bun/Snippets/x_output.tmSnippet @@ -1,18 +1,18 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>content</key> <string>&lt;cfoutput&gt;${TM_SELECTED_TEXT}$0&lt;/cfoutput&gt;</string> <key>keyEquivalent</key> - <string>^O</string> + <string>^O,^></string> <key>name</key> <string>output</string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string>output</string> <key>uuid</key> <string>C3F90629-A2AF-4C50-B812-1E9194E71B24</string> </dict> </plist> diff --git a/build.xml b/build.xml index c01307f..0535a2a 100644 --- a/build.xml +++ b/build.xml @@ -1,74 +1,74 @@ <project name="ColdFusion Textmate Bundle"> <!-- The xslt process needs an XSLT 2.0 processor, so I am using Saxon--> <property name="saxon.path" value="/Applications/saxonb9-0-0-4j/saxon9.jar" /> <!-- Probably wont need to change this unless you are going to try to use a different cfeclipse dictionary file. --> <property name="dictionary.file" value="Resources/cfml.xml" /> <property name="output.name" value="ColdFusion" /> <property name="output.bundle" value="${output.name}.tmbundle" /> <property name="bundle.uuid" value="1A09BE0B-E81A-4CB7-AF69-AFC845162D1F" /> <property name="snytax.uuid" value="97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14" /> <property name="cmddoc.uuid" value="9902B0A3-0523-4190-B541-374AC09CC72F" /> <property name="tagcomplete.uuid" value="A51C20E9-244A-4E9B-8150-B3D55F6CA839" /> <property name="attcomplete.uuid" value="C6F3F140-863E-442D-8ECA-830C4002884E" /> <property name="xsl.file" value="dictToBundle.xsl" /> <property name="doc.xsl.file" value="dictToAPI.xsl" /> <property name="base.bundle" value="ColdFusion.bun" /> <target name="clean"> <delete dir="build/${output.bundle}" /> </target> <target name="superclean"> <delete dir="build" /> </target> <target name="createSnippets"> <java jar="${saxon.path}" fork="true"> <arg value="-o:build/${output.bundle}/info.plist" /> <arg value="${dictionary.file}" /> <arg value="${xsl.file}" /> <arg value="bundle-uuid=${bundle.uuid}" /> <arg value="bundle-name=${output.name}" /> <arg value="syntax-uuid=${snytax.uuid}" /> <arg value="cmddoc-uuid=${cmddoc.uuid}" /> <arg value="tagcomplete-uuid=${tagcomplete.uuid}" /> <arg value="attcomplete-uuid=${attcomplete.uuid}" /> </java> </target> <target name="createAPIDoc"> <java jar="${saxon.path}" fork="true"> <arg value="-o:doc/${output.name}.html" /> <arg value="${dictionary.file}" /> <arg value="${doc.xsl.file}" /> <!-- <arg value="bundle-uuid=${bundle.uuid}" /> <arg value="bundle-name=${output.name}" /> --> </java> </target> <target name="createBundle"> <copy todir="build/${output.bundle}"> <fileset dir="${base.bundle}"/> <filterset> <filter token="BUNDLE_NAME" value="${output.name}"/> <filter token="BUNDLE_UUID" value="${bundle.uuid}"/> <filter token="SYNTAX_UUID" value="${syntax.uuid}"/> <filter token="CMDDOC_UUID" value="${cmddoc.uuid}"/> <filter token="TAGCOMPLETE_UUID" value="${tagcomplete.uuid}"/> - <filter token="ATTRCOMPLETE_UUID" value="${attrcomplete.uuid}"/> + <filter token="ATTRCOMPLETE_UUID" value="${attcomplete.uuid}"/> </filterset> </copy> </target> <target name="build"> <mkdir dir="build" /> <antcall target="createBundle" /> <antcall target="createSnippets" /> <antcall target="createAPIDoc" /> </target> </project> \ No newline at end of file
robrohan/coldfusion.tmbundle
5becdbdbbafb36508e74b382af04f6060c25f874
Just making sure the completion still works after mucking around with it.
diff --git a/ColdFusion.bun/Commands/CodeCompletion Tags.tmCommand b/ColdFusion.bun/Commands/CodeCompletion Tags.tmCommand index be42a7e..5ec0975 100644 --- a/ColdFusion.bun/Commands/CodeCompletion Tags.tmCommand +++ b/ColdFusion.bun/Commands/CodeCompletion Tags.tmCommand @@ -1,40 +1,40 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>beforeRunningCommand</key> <string>nop</string> <key>bundleUUID</key> <string>@BUNDLE_UUID@</string> <key>command</key> <string><![CDATA[#!/usr/bin/env ruby require "#{ENV["TM_SUPPORT_PATH"]}/lib/codecompletion"; ENV["TM_COMPLETION_characters"]="/cf/"; TextmateCodeCompletion.go! ]]></string> <key>fallbackInput</key> <string>line</string> <key>input</key> <string>selection</string> <key>keyEquivalent</key> <string>^ </string> <key>name</key> <string>CodeCompletion Tags</string> <key>output</key> <string>insertAsSnippet</string> <key>scope</key> <!-- text.html.cfml invalid.illegal.incomplete.html --> - <string>text.html text.html.cfml meta.tag.other.html -entity.other.attribute-name -string.quoted, invalid.illegal.incomplete.html</string> + <string>text.html text.html.cfml meta.tag.other.html -entity.other.attribute-name -string.quoted, invalid.illegal.incomplete.cfml</string> <key>uuid</key> <string>@TAGCOMPLETE_UUID@</string> </dict> </plist> diff --git a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage index f3086ca..0b7a85c 100644 --- a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage +++ b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage @@ -1,553 +1,553 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>bundleUUID</key> <string>@BUNDLE_UUID@</string> <key>fileTypes</key> <array> <string>cfm</string> <string>cfml</string> <string>cfc</string> </array> <key>firstLineMatch</key> <string>&lt;!DOCTYPE|&lt;(?i:html)</string> <key>foldingStartMarker</key> <string>(?x) (&lt;(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script |ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction|cfcase|cfdefaultcase|cfsavecontent)\b.*?&gt; |&lt;!---(?!.*---\s*&gt;) )</string> <key>foldingStopMarker</key> <string>(?x) (&lt;/(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|scrip t|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction|cfcase|cfdefaultcase|cfsavecontent)&gt; |^(?!.*?&lt;!---).*?---\s*&gt; )</string> <key>keyEquivalent</key> <string>^~@c</string> <key>name</key> <string>@BUNDLE_NAME@</string> <key>patterns</key> <array> <dict> <key>match</key> <string>&lt;(cf|CF)[\W]*&gt;</string> <key>name</key> - <string>invalid.illegal.incomplete.html</string> + <string>invalid.illegal.incomplete.cfml</string> </dict> <dict> <key>include</key> <string>#tag-finder</string> </dict> <dict> <key>begin</key> <string>&lt;\?(xml)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.xml.html</string> </dict> </dict> <key>end</key> <string>\?&gt;</string> <key>name</key> <string>meta.tag.preprocessor.xml.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> </array> </dict> <dict> <key>include</key> <string>#cfcomment</string> </dict> <dict> <key>include</key> <string>#htmlcomment</string> </dict> <dict> <key>begin</key> <string>&lt;!</string> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.sgml.html</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>(DOCTYPE)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.doctype.html</string> </dict> </dict> <key>end</key> <string>(?=&gt;)</string> <key>name</key> <string>meta.tag.sgml.doctype.html</string> <key>patterns</key> <array> <dict> <key>match</key> <string>"[^"&gt;]*"</string> <key>name</key> <string>string.quoted.double.doctype.identifiers-and-DTDs.html</string> </dict> </array> </dict> <dict> <key>begin</key> <string>\[CDATA\[</string> <key>end</key> <string>]](?=&gt;)</string> <key>name</key> <string>constant.other.inline-data.html</string> </dict> </array> </dict> <dict> <key>include</key> <string>#coldfusion-script</string> </dict> <dict> <key>include</key> <string>#cffunction</string> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:style))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.style.html</string> </dict> </dict> <key>end</key> <string>&lt;/((?i:style))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.css.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:style))</string> <key>patterns</key> <array> <!-- <dict> <key>include</key> <string>#embedded-code</string> </dict> --> <!-- <dict> <key>include</key> <string>#tag-finder</string> </dict> --> <dict> <key>include</key> <string>source.css</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfquery))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> <!-- <string>entity.name.tag.cfquery.html</string> --> </dict> </dict> <key>end</key> <string>&lt;/((?i:cfquery))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.sql.embedded.html</string> <key>patterns</key> <array> <!-- this is here to colour the cfquery tag's attributes --> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:cfquery))</string> <key>patterns</key> <array> <!-- <dict> <key>include</key> <string>#embedded-code</string> </dict> --> <dict> <key>include</key> <string>source.sql</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:script))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(script|SCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:script|SCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:script))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/script)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/script)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfscript))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(cfscript|CFSCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:cfscript|CFSCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:cfscript))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/cfscript)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/cfscript)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:body|head|html)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.structure.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.structure.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:address|blockquote|dd|div|dl|dt|fieldset|form|frame|frameset|h1|h2 |h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|menu|pre)\ b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.block.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.block.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite |code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|la bel|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script| select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot |th|thead|title|tr|tt|u|var)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.inline.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.inline.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?([a-zA-Z0-9:]+)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>include</key> <string>#entities</string> </dict> <dict> <key>match</key> <string>&lt;&gt;</string> <key>name</key> <string>invalid.illegal.incomplete.html</string> </dict> <dict> <key>match</key> <string>&lt;(?=\W)|&gt;</string> <key>name</key> <string>invalid.illegal.bad-angle-bracket.html</string> </dict> </array> <key>repository</key> <dict> <key>cfcomment</key> <dict> <key>begin</key> <string>&lt;!---</string> <key>end</key> <string>---\s*&gt;</string> <key>name</key> <!-- <string>comment.block.html</string> --> <string>comment.line</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#cfcomment</string> </dict> <!-- <dict> <key>match</key> <string>-=-=-</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> --> </array> </dict> <key>htmlcomment</key> <dict> <key>begin</key> <string>&lt;!--</string> <key>end</key> <string>--&gt;</string> <key>name</key> <string>comment.block.html</string> <key>patterns</key> <array> <dict> <key>match</key> <string>--</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> </array> </dict> <key>cffunction</key> <dict> <key>begin</key> <string>&lt;(cffunction)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>entity.other.attribute-name.html</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.string.begin</string> </dict> <key>4</key> <dict> <key>name</key> <string>entity.name.function.cfml</string> </dict> <key>5</key> <dict> <key>name</key> <string>punctuation.definition.string.end</string> </dict> </dict> <key>match</key> <string>\b([nN][aA][mM][Ee])\b\s*(=)\s*(["'])([A-Za-z$_0-9]+)(["'])</string> </dict> <dict> <key>include</key> <string>source.cfml</string> </dict> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict>
robrohan/coldfusion.tmbundle
77864fbf023ab47e105ba53c735f4a325d1d3939
Trying out a new way for code completion. This way seems to work much better.
diff --git a/ColdFusion.bun/Commands/CodeCompletion Tags.tmCommand b/ColdFusion.bun/Commands/CodeCompletion Tags.tmCommand index 6d25c19..be42a7e 100644 --- a/ColdFusion.bun/Commands/CodeCompletion Tags.tmCommand +++ b/ColdFusion.bun/Commands/CodeCompletion Tags.tmCommand @@ -1,39 +1,40 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>beforeRunningCommand</key> <string>nop</string> <key>bundleUUID</key> <string>@BUNDLE_UUID@</string> <key>command</key> - <string>#!/usr/bin/env ruby -require &quot;#{ENV[&apos;TM_SUPPORT_PATH&apos;]}/lib/codecompletion&quot; -TextmateCodeCompletion.go! -</string> + <string><![CDATA[#!/usr/bin/env ruby + require "#{ENV["TM_SUPPORT_PATH"]}/lib/codecompletion"; + ENV["TM_COMPLETION_characters"]="/cf/"; + TextmateCodeCompletion.go! + ]]></string> <key>fallbackInput</key> <string>line</string> <key>input</key> <string>selection</string> <key>keyEquivalent</key> <string>^ </string> <key>name</key> <string>CodeCompletion Tags</string> <key>output</key> <string>insertAsSnippet</string> <key>scope</key> <!-- text.html.cfml invalid.illegal.incomplete.html --> - <string>text.html -entity.other.attribute-name -string.quoted, invalid.illegal.incomplete.html</string> + <string>text.html text.html.cfml meta.tag.other.html -entity.other.attribute-name -string.quoted, invalid.illegal.incomplete.html</string> <key>uuid</key> <string>@TAGCOMPLETE_UUID@</string> </dict> </plist> diff --git a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage index 4deb203..f3086ca 100644 --- a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage +++ b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage @@ -1,641 +1,641 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>bundleUUID</key> <string>@BUNDLE_UUID@</string> <key>fileTypes</key> <array> <string>cfm</string> <string>cfml</string> <string>cfc</string> </array> <key>firstLineMatch</key> <string>&lt;!DOCTYPE|&lt;(?i:html)</string> <key>foldingStartMarker</key> <string>(?x) (&lt;(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script |ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction|cfcase|cfdefaultcase|cfsavecontent)\b.*?&gt; |&lt;!---(?!.*---\s*&gt;) )</string> <key>foldingStopMarker</key> <string>(?x) (&lt;/(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|scrip t|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction|cfcase|cfdefaultcase|cfsavecontent)&gt; |^(?!.*?&lt;!---).*?---\s*&gt; )</string> <key>keyEquivalent</key> <string>^~@c</string> <key>name</key> <string>@BUNDLE_NAME@</string> <key>patterns</key> <array> + <dict> + <key>match</key> + <string>&lt;(cf|CF)[\W]*&gt;</string> + <key>name</key> + <string>invalid.illegal.incomplete.html</string> + </dict> <dict> <key>include</key> <string>#tag-finder</string> </dict> <dict> <key>begin</key> <string>&lt;\?(xml)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.xml.html</string> </dict> </dict> <key>end</key> <string>\?&gt;</string> <key>name</key> <string>meta.tag.preprocessor.xml.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> </array> </dict> <dict> <key>include</key> <string>#cfcomment</string> </dict> <dict> <key>include</key> <string>#htmlcomment</string> </dict> <dict> <key>begin</key> <string>&lt;!</string> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.sgml.html</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>(DOCTYPE)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.doctype.html</string> </dict> </dict> <key>end</key> <string>(?=&gt;)</string> <key>name</key> <string>meta.tag.sgml.doctype.html</string> <key>patterns</key> <array> <dict> <key>match</key> <string>"[^"&gt;]*"</string> <key>name</key> <string>string.quoted.double.doctype.identifiers-and-DTDs.html</string> </dict> </array> </dict> <dict> <key>begin</key> <string>\[CDATA\[</string> <key>end</key> <string>]](?=&gt;)</string> <key>name</key> <string>constant.other.inline-data.html</string> </dict> - <!--<dict> - <key>match</key> - <string>(\s*)(?!-=-=-|&gt;)\S(\s*)</string> - <key>name</key> - <string>invalid.illegal.bad-comments-or-CDATA.html</string> - </dict> --> </array> </dict> <dict> <key>include</key> <string>#coldfusion-script</string> </dict> <dict> <key>include</key> <string>#cffunction</string> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:style))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.style.html</string> </dict> </dict> <key>end</key> <string>&lt;/((?i:style))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.css.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:style))</string> <key>patterns</key> <array> <!-- <dict> <key>include</key> <string>#embedded-code</string> </dict> --> <!-- <dict> <key>include</key> <string>#tag-finder</string> </dict> --> <dict> <key>include</key> <string>source.css</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfquery))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> <!-- <string>entity.name.tag.cfquery.html</string> --> </dict> </dict> <key>end</key> <string>&lt;/((?i:cfquery))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.sql.embedded.html</string> <key>patterns</key> <array> <!-- this is here to colour the cfquery tag's attributes --> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:cfquery))</string> <key>patterns</key> <array> <!-- <dict> <key>include</key> <string>#embedded-code</string> </dict> --> <dict> <key>include</key> <string>source.sql</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:script))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(script|SCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:script|SCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:script))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/script)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/script)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfscript))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(cfscript|CFSCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:cfscript|CFSCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:cfscript))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/cfscript)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/cfscript)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:body|head|html)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.structure.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.structure.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:address|blockquote|dd|div|dl|dt|fieldset|form|frame|frameset|h1|h2 |h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|menu|pre)\ b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.block.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.block.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite |code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|la bel|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script| select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot |th|thead|title|tr|tt|u|var)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.inline.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.inline.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?([a-zA-Z0-9:]+)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>include</key> <string>#entities</string> </dict> <dict> <key>match</key> <string>&lt;&gt;</string> <key>name</key> <string>invalid.illegal.incomplete.html</string> </dict> <dict> <key>match</key> <string>&lt;(?=\W)|&gt;</string> <key>name</key> <string>invalid.illegal.bad-angle-bracket.html</string> </dict> </array> <key>repository</key> <dict> <key>cfcomment</key> <dict> <key>begin</key> <string>&lt;!---</string> <key>end</key> <string>---\s*&gt;</string> <key>name</key> <!-- <string>comment.block.html</string> --> <string>comment.line</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#cfcomment</string> </dict> <!-- <dict> <key>match</key> <string>-=-=-</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> --> </array> </dict> <key>htmlcomment</key> <dict> <key>begin</key> <string>&lt;!--</string> <key>end</key> <string>--&gt;</string> <key>name</key> <string>comment.block.html</string> <key>patterns</key> <array> <dict> <key>match</key> <string>--</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> </array> </dict> <key>cffunction</key> <dict> <key>begin</key> <string>&lt;(cffunction)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>entity.other.attribute-name.html</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.string.begin</string> </dict> <key>4</key> <dict> <key>name</key> <string>entity.name.function.cfml</string> </dict> <key>5</key> <dict> <key>name</key> <string>punctuation.definition.string.end</string> </dict> </dict> <key>match</key> <string>\b([nN][aA][mM][Ee])\b\s*(=)\s*(["'])([A-Za-z$_0-9]+)(["'])</string> </dict> <dict> <key>include</key> <string>source.cfml</string> </dict> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <key>embedded-code</key> <dict> <key>patterns</key> <array> <!-- <dict> <key>include</key> <string>#php</string> </dict> <dict> <key>include</key> <string>#ruby</string> </dict> <dict> <key>include</key> <string>#smarty</string> </dict> <dict> <key>include</key> <string>#python</string> </dict> --> <dict> <key>include</key> <string>#javascript</string> </dict> </array> </dict> <key>entities</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>&amp;([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);</string> <key>name</key> <string>constant.character.entity.html</string> </dict> <dict> <key>match</key> <string>&amp;</string> <key>name</key> <string>invalid.illegal.bad-ampersand.html</string> </dict> </array> </dict> <key>string-double-quoted</key> <dict> <key>begin</key> <string>"</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <key>string-single-quoted</key> <dict> <key>begin</key> <string>'</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> diff --git a/dictToBundle.xsl b/dictToBundle.xsl index fcd505c..6159bb9 100644 --- a/dictToBundle.xsl +++ b/dictToBundle.xsl @@ -1,412 +1,412 @@ <?xml version="1.0" encoding="UTF-8" ?> <!-- dictToBundle Created by Rob Rohan on 2008-11-22. Copyright (c) 2008-2009 Rob Rohan. All rights reserved. The default output from this process is the info.plist file. However, this also generates the files for the tag completion and for the default snippets. The snippets wind up in the Snippets directory and the tag and attribute lists wind up in the Preferences folder. --> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:dic="http://www.cfeclipse.org/version1/dictionary" xmlns:util="java:java.util.UUID" version="2.0" exclude-result-prefixes="xsl dic util"> <xsl:output method="xml" indent="yes" /> <xsl:output method="xml" indent="yes" name="plistxml" exclude-result-prefixes="xsl dic util" /> <!-- <xsl:param name="bundle-dir" select="'ColdFusion.bun'" /> --> <xsl:param name="bundle-uuid" select="'1A09BE0B-E81A-4CB7-AF69-AFC845162D1F'" /> <xsl:param name="bundle-name" select="'ColdFusion'" /> <xsl:param name="syntax-uuid" select="''" /> <xsl:param name="cmddoc-uuid" select="''" /> <xsl:param name="tagcomplete-uuid" select="''" /> <xsl:param name="attcomplete-uuid" select="''" /> <xsl:variable name="NL"> <xsl:text> </xsl:text> </xsl:variable> <xsl:variable name="TAB"> <xsl:text> </xsl:text> </xsl:variable> <!-- writes out the plist, and kicks off the snippet writting --> <xsl:template match="/"> <plist version="1.0"> <dict> <key>contactEmailRot13</key> <string>[email protected]</string> <key>contactName</key> <string>Rob Rohan</string> <key>description</key> <string>Support for the ColdFusion web development environment.</string> <key>mainMenu</key> <dict> <key>items</key> <array> <string>C8F9D7A6-D447-4C16-B566-BE46335B1067</string> <string>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</string> <string>------------------------------------</string> <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> <string>------------------------------------</string> <string>FFDC5F11-5575-4C8C-9CAC-4DFC1163CFEA</string> <string>0DEA11CD-931E-4087-984A-784A2D825EF2</string> <string>7EC225A6-93C8-4A2E-906A-3ADA1FD3C172</string> <string>8D2B412E-56DF-4728-AB74-C1C674277E22</string> <string><xsl:value-of select="$cmddoc-uuid" /></string> <string><xsl:value-of select="$tagcomplete-uuid" /></string> <string><xsl:value-of select="$attcomplete-uuid" /></string> <!-- Now that we have written out the plist file and the snippets --> <!-- fire off the bit that does the tag and attribute completion --> <xsl:call-template name="write-tag-completion-list" /> <xsl:call-template name="write-attribute-completion-list" /> </array> <key>submenus</key> <dict> <key>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</key> <dict> <key>items</key> <array> <xsl:comment>FUNCTIONS</xsl:comment><xsl:value-of select="$NL" /> <xsl:apply-templates select="/dic:dictionary/dic:functions/dic:function" /> </array> <key>name</key> <string>ColdFusion Functions</string> </dict> <key>C8F9D7A6-D447-4C16-B566-BE46335B1067</key> <dict> <key>items</key> <array> <xsl:comment>TAGS</xsl:comment><xsl:value-of select="$NL" /> <xsl:apply-templates select="/dic:dictionary/dic:tags/dic:tag" /> </array> <key>name</key> <string>ColdFusion Tags</string> </dict> </dict> </dict> <key>name</key> <string><xsl:value-of select="$bundle-name" /></string> <key>ordering</key> <array> <!-- <string>00D00AD7-3C05-46E0-B8B9-0F5CCAC04F57</string> <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> --> </array> <key>uuid</key> <string><xsl:value-of select="$bundle-uuid" /></string> </dict> </plist> </xsl:template> <!-- Formats the functions. Writes the plist too. --> <xsl:template match="dic:function"> <xsl:variable name="filename" select="translate(@name,':','-')" /> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:value-of select="$NL" /> <!-- {$bundle-dir}/ --> <xsl:result-document href="Snippets/gen-{$filename}.tmSnippet" format="plistxml"> <plist version="1.0"> <dict> <key>content</key> <string><xsl:value-of select="@name" /> <xsl:text>(${1:</xsl:text> <xsl:for-each select="./dic:parameter"> <xsl:call-template name="param-with-placement"> <xsl:with-param name="placement" select="position()+1" /> <xsl:with-param name="separator" select="''" /> <xsl:with-param name="preparator" select="', '" /> <xsl:with-param name="use-equals" select="'false'" /> <xsl:with-param name="total-param-count" select="count(../dic:parameter)" /> </xsl:call-template> </xsl:for-each> <xsl:text>})</xsl:text></string> <key>name</key> <string><xsl:value-of select="@name"/></string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string><xsl:value-of select="@name"/></string> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <!-- Formats the tags. Writes out the plist file too --> <xsl:template match="dic:tag"> <xsl:variable name="filename" select="translate(@name,':','-')" /> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:value-of select="$NL" /> <!-- {$bundle-dir}/ --> <xsl:result-document href="Snippets/gen-{$filename}.tmSnippet" format="plistxml"> <plist version="1.0"> <dict> <key>content</key> <string><xsl:text>&lt;</xsl:text> <xsl:value-of select="@name" /> <xsl:text> ${1:</xsl:text> <xsl:for-each select="./dic:parameter"> <xsl:call-template name="param-with-placement"> <xsl:with-param name="placement" select="position()+position()" /> <xsl:with-param name="separator" select="' '" /> <xsl:with-param name="preparator" select="''" /> <xsl:with-param name="use-equals" select="'true'" /> <xsl:with-param name="total-param-count" select="count(../dic:parameter)" /> <!-- <xsl:with-param name="element" select="." /> --> </xsl:call-template> </xsl:for-each> <xsl:text>}</xsl:text> <xsl:choose> <xsl:when test="@single = 'true'"> <xsl:text> /&gt;$0</xsl:text> </xsl:when> <xsl:otherwise> <xsl:text>&gt;</xsl:text> <xsl:value-of select="$NL" /> <xsl:value-of select="$TAB" /> <xsl:text>$0</xsl:text> <xsl:value-of select="$NL" /> <xsl:text>&lt;/</xsl:text> <xsl:value-of select="@name" /> <xsl:text>&gt;</xsl:text> </xsl:otherwise> </xsl:choose></string> <key>name</key> <string><xsl:value-of select="@name"/></string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string> <xsl:choose> <xsl:when test="contains(@name,':')"> <xsl:value-of select="substring-before(@name,':')" /> </xsl:when> <xsl:otherwise> <xsl:value-of select="@name" /> </xsl:otherwise> </xsl:choose> </string> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <!-- handles doing the tag and function params. Takes 3 params. placement = where to start the textmate $N variables from separator = what to tack on to the end of each paramenter total-param-count = total number of params, so we don't add the separator to the last item. --> <xsl:template name="param-with-placement"> <xsl:param name="placement" /> <xsl:param name="separator" /> <xsl:param name="preparator" /> <xsl:param name="use-equals" /> <xsl:param name="total-param-count" /> <xsl:choose> <xsl:when test="$use-equals = 'true'"> <xsl:text>$</xsl:text> <xsl:text>{</xsl:text> <xsl:value-of select="$placement" /> <xsl:text>:</xsl:text> <xsl:value-of select="$preparator" /> <xsl:value-of select="@name" /><xsl:text>="$</xsl:text> <xsl:value-of select="$placement+1" /> <xsl:text>"</xsl:text> <xsl:if test="position() != $total-param-count"> <xsl:value-of select="$separator" /> </xsl:if> <xsl:text>}</xsl:text> </xsl:when> <xsl:otherwise> <xsl:if test="@required = 'true'"> <xsl:if test="position() != 1"> <xsl:value-of select="$preparator" /> </xsl:if> <xsl:if test="@type = 'String'"> <xsl:text>"</xsl:text> </xsl:if> </xsl:if> <xsl:text>${</xsl:text> <xsl:value-of select="$placement" /> <xsl:text>:</xsl:text> <xsl:if test="@required = 'false'"> <xsl:if test="position() != 1"> <xsl:value-of select="$preparator" /> </xsl:if> </xsl:if> <xsl:if test="@required = 'false'"><xsl:text>[</xsl:text></xsl:if> <xsl:value-of select="@name" /> <xsl:if test="@required = 'false'"><xsl:text>]</xsl:text></xsl:if> <xsl:text>}</xsl:text> <xsl:if test="@required = 'true'"> <xsl:if test="@type = 'String'"> <xsl:text>"</xsl:text> </xsl:if> </xsl:if> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- make a list of tags in the format textmate expects for code completion --> <xsl:template name="write-tag-completion-list"> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:result-document href="Preferences/Completion%20Tags.tmPreferences" format="plistxml"> <plist version="1.0"> <dict> <key>name</key> <string>Completions Tags</string> <key>scope</key> <!-- text.html.cfm, invalid.illegal.incomplete.html --> <string>text.html -(meta.tag | source), invalid.illegal.incomplete.html -source</string> <key>settings</key> <dict> <key>shellVariables</key> <array> <dict> <key>name</key> <string>TM_COMPLETION_split</string> <key>value</key> <string>,</string> </dict> <dict> <key>name</key> <string>TM_COMPLETIONS</string> <key>value</key> <string> <xsl:for-each select="//dic:tag"> - <xsl:value-of select="./@name" /><xsl:text>,</xsl:text> + <xsl:value-of select="replace(./@name,'^cf','')" /><xsl:text>,</xsl:text> </xsl:for-each> </string> </dict> </array> </dict> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> <!-- <string><xsl:value-of select="$tagcomplete-uuid" /></string> --> </dict> </plist> </xsl:result-document> </xsl:template> <xsl:template name="write-attribute-completion-list"> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:result-document href="Preferences/Completion%20Attributes.tmPreferences" format="plistxml"> <plist version="1.0"> <dict> <key>name</key> <string>Completions Attributes</string> <key>scope</key> <!-- text.html meta.tag -(entity.other.attribute-name | punctuation.definition.tag.begin | source | entity.name.tag | string | invalid.illegal.incomplete.html)--> <string>text.html.cfm meta.tag.other.html</string> <key>settings</key> <dict> <key>completions</key> <array> <xsl:for-each select="//dic:tag"> - <string><xsl:value-of select="@name" /></string> + <string><xsl:value-of select="./@name" /></string> <string><xsl:value-of select="translate(@name,'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')" /></string> </xsl:for-each> </array> <key>disableDefaultCompletion</key> <integer>1</integer> <key>shellVariables</key> <array> <dict> <key>name</key> <string>TM_COMPLETION_split</string> <key>value</key> <string>,</string> </dict> <dict> <key>name</key> <string>TM_COMPLETION_scope</string> <key>value</key> <string>html_attributes</string> </dict> <dict> <key>name</key> <string>TM_COMPLETIONS</string> <key>value</key> <string> <xsl:for-each select="//dic:tag/dic:parameter"> <xsl:text>&lt;</xsl:text> <xsl:value-of select="../@name" /><xsl:text> </xsl:text> <xsl:value-of select="./@name" /> <xsl:text>=&quot;&quot;</xsl:text> <xsl:text>,</xsl:text> </xsl:for-each> </string> </dict> </array> </dict> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <xsl:template match="text()" /> </xsl:stylesheet> \ No newline at end of file
robrohan/coldfusion.tmbundle
588c3494a3b19a9621fec10e0a1bb390271dadcb
Changed function names to not allow spaces. For example "getStuff ()" is no longer supported because it was coloring and ggroupings incorrectly. It's more common for <cfif x eq 1 and (z neq 12 or z neq 1234)>. Without this change the and () part was getting colored as a function.
diff --git a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage index f1ebb04..4deb203 100644 --- a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage +++ b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage @@ -136,740 +136,740 @@ <dict> <key>include</key> <string>#cffunction</string> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:style))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.style.html</string> </dict> </dict> <key>end</key> <string>&lt;/((?i:style))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.css.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:style))</string> <key>patterns</key> <array> <!-- <dict> <key>include</key> <string>#embedded-code</string> </dict> --> <!-- <dict> <key>include</key> <string>#tag-finder</string> </dict> --> <dict> <key>include</key> <string>source.css</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfquery))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> <!-- <string>entity.name.tag.cfquery.html</string> --> </dict> </dict> <key>end</key> <string>&lt;/((?i:cfquery))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.sql.embedded.html</string> <key>patterns</key> <array> <!-- this is here to colour the cfquery tag's attributes --> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:cfquery))</string> <key>patterns</key> <array> <!-- <dict> <key>include</key> <string>#embedded-code</string> </dict> --> <dict> <key>include</key> <string>source.sql</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:script))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(script|SCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:script|SCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:script))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/script)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/script)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfscript))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(cfscript|CFSCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:cfscript|CFSCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:cfscript))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/cfscript)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/cfscript)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:body|head|html)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.structure.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.structure.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:address|blockquote|dd|div|dl|dt|fieldset|form|frame|frameset|h1|h2 |h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|menu|pre)\ b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.block.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.block.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite |code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|la bel|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script| select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot |th|thead|title|tr|tt|u|var)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.inline.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.inline.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?([a-zA-Z0-9:]+)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>include</key> <string>#entities</string> </dict> <dict> <key>match</key> <string>&lt;&gt;</string> <key>name</key> <string>invalid.illegal.incomplete.html</string> </dict> <dict> <key>match</key> <string>&lt;(?=\W)|&gt;</string> <key>name</key> <string>invalid.illegal.bad-angle-bracket.html</string> </dict> </array> <key>repository</key> <dict> <key>cfcomment</key> <dict> <key>begin</key> <string>&lt;!---</string> <key>end</key> <string>---\s*&gt;</string> <key>name</key> <!-- <string>comment.block.html</string> --> <string>comment.line</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#cfcomment</string> </dict> <!-- <dict> <key>match</key> <string>-=-=-</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> --> </array> </dict> <key>htmlcomment</key> <dict> <key>begin</key> <string>&lt;!--</string> <key>end</key> <string>--&gt;</string> <key>name</key> <string>comment.block.html</string> <key>patterns</key> <array> <dict> <key>match</key> <string>--</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> </array> </dict> <key>cffunction</key> <dict> <key>begin</key> <string>&lt;(cffunction)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>entity.other.attribute-name.html</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.string.begin</string> </dict> <key>4</key> <dict> <key>name</key> <string>entity.name.function.cfml</string> </dict> <key>5</key> <dict> <key>name</key> <string>punctuation.definition.string.end</string> </dict> </dict> <key>match</key> <string>\b([nN][aA][mM][Ee])\b\s*(=)\s*(["'])([A-Za-z$_0-9]+)(["'])</string> </dict> <dict> <key>include</key> <string>source.cfml</string> </dict> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <key>embedded-code</key> <dict> <key>patterns</key> <array> <!-- <dict> <key>include</key> <string>#php</string> </dict> <dict> <key>include</key> <string>#ruby</string> </dict> <dict> <key>include</key> <string>#smarty</string> </dict> <dict> <key>include</key> <string>#python</string> </dict> --> <dict> <key>include</key> <string>#javascript</string> </dict> </array> </dict> <key>entities</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>&amp;([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);</string> <key>name</key> <string>constant.character.entity.html</string> </dict> <dict> <key>match</key> <string>&amp;</string> <key>name</key> <string>invalid.illegal.bad-ampersand.html</string> </dict> </array> </dict> <key>string-double-quoted</key> <dict> <key>begin</key> <string>"</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <key>string-single-quoted</key> <dict> <key>begin</key> <string>'</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <!-- Does function calls. For example, the xmlparse in cfset x=xmlparse() --> <key>inline-function-stuff</key> <dict> <key>begin</key> <!-- [^\#"'] --> - <string>[a-zA-Z0-9_\.]+\s*\(</string> + <string>[a-zA-Z0-9_\.]+\(</string> <key>contentName</key> <string>support.function.parameters</string> <key>end</key> <string>\)</string> <key>name</key> <string>support.function</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#inline-function-stuff</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> </array> </dict> <!-- the stuff between the ## --> <key>coldfusion-script</key> <dict> <key>begin</key> <string>#</string> <key>end</key> <string>\#</string> <key>name</key> <string>source.coldfusion.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#inline-function-stuff</string> </dict> <dict> <key>include</key> <string>#embedded-code</string> </dict> </array> </dict> <!-- normal attributes --> <key>tag-generic-attribute</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>\b([a-zA-Z0-9_\-:]+)</string> <key>name</key> <string>entity.other.attribute-name.html</string> </dict> </array> </dict> <!-- ID attributes on elements (shows up in the symbol list) --> <key>tag-id-attribute</key> <dict> <key>begin</key> <string>\b(id)\b\s*=</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.other.attribute-name.id.html</string> </dict> </dict> <key>end</key> <string>(?&lt;='|")</string> <key>name</key> <string>meta.attribute-with-value.id.html</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>"</string> <key>contentName</key> <string>meta.toc-list.id.html</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <dict> <key>begin</key> <string>'</string> <key>contentName</key> <string>meta.toc-list.id.html</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> </array> </dict> <!-- handles all the inner workings of the tags --> <key>tag-stuff</key> <dict> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-id-attribute</string> </dict> <dict> <key>include</key> <string>#inline-function-stuff</string> </dict> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> <dict> <key>include</key> <string>#coldfusion-script</string> </dict> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>match</key> <string>.var\s</string> <key>name</key> <string>variable.other</string> </dict> <dict> <key>begin</key> <string>.&lt;cffunction\sname=('|")1</string> <key>contentName</key> <string>entity.name.function</string> <key>end</key> <string>'|"1</string> <key>name</key> <string>meta.tag.other</string> </dict> </array> </dict> <key>tag-finder</key> <dict> <key>begin</key> <string>&lt;([a-zA-Z0-9:]+)(?=[^&gt;]*&gt;&lt;/\1&gt;)</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.html</string> </dict> </dict> <key>end</key> <string>&gt;(&lt;)/(\1)&gt;</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>meta.scope.between-tag-pair.html</string> </dict> <key>2</key> <dict> <key>name</key> <string>entity.name.tag.html</string> </dict> </dict> <key>name</key> <string>meta.tag.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> </dict> <key>scopeName</key> <string>text.html.cfm</string> <key>uuid</key> <string>@SYNTAX_UUID@</string> </dict> </plist>
robrohan/coldfusion.tmbundle
7840d5923032cee07291d4b0fb71e6dc1b8f84ed
Fixed the attribute regex to support numbers and the underscore character
diff --git a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage index cca20c1..f1ebb04 100644 --- a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage +++ b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage @@ -1,875 +1,875 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>bundleUUID</key> <string>@BUNDLE_UUID@</string> <key>fileTypes</key> <array> <string>cfm</string> <string>cfml</string> <string>cfc</string> </array> <key>firstLineMatch</key> <string>&lt;!DOCTYPE|&lt;(?i:html)</string> <key>foldingStartMarker</key> <string>(?x) -(&lt;(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script |ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction|cfcase|cfdefaultcase)\b.*?&gt; +(&lt;(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script |ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction|cfcase|cfdefaultcase|cfsavecontent)\b.*?&gt; |&lt;!---(?!.*---\s*&gt;) )</string> <key>foldingStopMarker</key> <string>(?x) -(&lt;/(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|scrip t|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction|cfcase|cfdefaultcase)&gt; +(&lt;/(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|scrip t|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction|cfcase|cfdefaultcase|cfsavecontent)&gt; |^(?!.*?&lt;!---).*?---\s*&gt; )</string> <key>keyEquivalent</key> <string>^~@c</string> <key>name</key> <string>@BUNDLE_NAME@</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-finder</string> </dict> <dict> <key>begin</key> <string>&lt;\?(xml)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.xml.html</string> </dict> </dict> <key>end</key> <string>\?&gt;</string> <key>name</key> <string>meta.tag.preprocessor.xml.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> </array> </dict> <dict> <key>include</key> <string>#cfcomment</string> </dict> <dict> <key>include</key> <string>#htmlcomment</string> </dict> <dict> <key>begin</key> <string>&lt;!</string> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.sgml.html</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>(DOCTYPE)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.doctype.html</string> </dict> </dict> <key>end</key> <string>(?=&gt;)</string> <key>name</key> <string>meta.tag.sgml.doctype.html</string> <key>patterns</key> <array> <dict> <key>match</key> <string>"[^"&gt;]*"</string> <key>name</key> <string>string.quoted.double.doctype.identifiers-and-DTDs.html</string> </dict> </array> </dict> <dict> <key>begin</key> <string>\[CDATA\[</string> <key>end</key> <string>]](?=&gt;)</string> <key>name</key> <string>constant.other.inline-data.html</string> </dict> <!--<dict> <key>match</key> <string>(\s*)(?!-=-=-|&gt;)\S(\s*)</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> --> </array> </dict> <dict> <key>include</key> <string>#coldfusion-script</string> </dict> <dict> <key>include</key> <string>#cffunction</string> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:style))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.style.html</string> </dict> </dict> <key>end</key> <string>&lt;/((?i:style))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.css.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:style))</string> <key>patterns</key> <array> <!-- <dict> <key>include</key> <string>#embedded-code</string> </dict> --> <!-- <dict> <key>include</key> <string>#tag-finder</string> </dict> --> <dict> <key>include</key> <string>source.css</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfquery))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> <!-- <string>entity.name.tag.cfquery.html</string> --> </dict> </dict> <key>end</key> <string>&lt;/((?i:cfquery))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.sql.embedded.html</string> <key>patterns</key> <array> <!-- this is here to colour the cfquery tag's attributes --> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:cfquery))</string> <key>patterns</key> <array> <!-- <dict> <key>include</key> <string>#embedded-code</string> </dict> --> <dict> <key>include</key> <string>source.sql</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:script))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(script|SCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:script|SCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:script))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/script)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/script)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfscript))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(cfscript|CFSCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:cfscript|CFSCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:cfscript))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/cfscript)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/cfscript)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:body|head|html)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.structure.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.structure.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:address|blockquote|dd|div|dl|dt|fieldset|form|frame|frameset|h1|h2 |h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|menu|pre)\ b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.block.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.block.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite |code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|la bel|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script| select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot |th|thead|title|tr|tt|u|var)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.inline.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.inline.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?([a-zA-Z0-9:]+)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>include</key> <string>#entities</string> </dict> <dict> <key>match</key> <string>&lt;&gt;</string> <key>name</key> <string>invalid.illegal.incomplete.html</string> </dict> <dict> <key>match</key> <string>&lt;(?=\W)|&gt;</string> <key>name</key> <string>invalid.illegal.bad-angle-bracket.html</string> </dict> </array> <key>repository</key> <dict> <key>cfcomment</key> <dict> <key>begin</key> <string>&lt;!---</string> <key>end</key> <string>---\s*&gt;</string> <key>name</key> <!-- <string>comment.block.html</string> --> <string>comment.line</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#cfcomment</string> </dict> <!-- <dict> <key>match</key> <string>-=-=-</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> --> </array> </dict> <key>htmlcomment</key> <dict> <key>begin</key> <string>&lt;!--</string> <key>end</key> <string>--&gt;</string> <key>name</key> <string>comment.block.html</string> <key>patterns</key> <array> <dict> <key>match</key> <string>--</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> </array> </dict> <key>cffunction</key> <dict> <key>begin</key> <string>&lt;(cffunction)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>entity.other.attribute-name.html</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.string.begin</string> </dict> <key>4</key> <dict> <key>name</key> <string>entity.name.function.cfml</string> </dict> <key>5</key> <dict> <key>name</key> <string>punctuation.definition.string.end</string> </dict> </dict> <key>match</key> <string>\b([nN][aA][mM][Ee])\b\s*(=)\s*(["'])([A-Za-z$_0-9]+)(["'])</string> </dict> <dict> <key>include</key> <string>source.cfml</string> </dict> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <key>embedded-code</key> <dict> <key>patterns</key> <array> <!-- <dict> <key>include</key> <string>#php</string> </dict> <dict> <key>include</key> <string>#ruby</string> </dict> <dict> <key>include</key> <string>#smarty</string> </dict> <dict> <key>include</key> <string>#python</string> </dict> --> <dict> <key>include</key> <string>#javascript</string> </dict> </array> </dict> <key>entities</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>&amp;([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);</string> <key>name</key> <string>constant.character.entity.html</string> </dict> <dict> <key>match</key> <string>&amp;</string> <key>name</key> <string>invalid.illegal.bad-ampersand.html</string> </dict> </array> </dict> <key>string-double-quoted</key> <dict> <key>begin</key> <string>"</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <key>string-single-quoted</key> <dict> <key>begin</key> <string>'</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <!-- Does function calls. For example, the xmlparse in cfset x=xmlparse() --> <key>inline-function-stuff</key> <dict> <key>begin</key> <!-- [^\#"'] --> <string>[a-zA-Z0-9_\.]+\s*\(</string> <key>contentName</key> <string>support.function.parameters</string> <key>end</key> <string>\)</string> <key>name</key> <string>support.function</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#inline-function-stuff</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> </array> </dict> <!-- the stuff between the ## --> <key>coldfusion-script</key> <dict> <key>begin</key> <string>#</string> <key>end</key> <string>\#</string> <key>name</key> <string>source.coldfusion.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#inline-function-stuff</string> </dict> <dict> <key>include</key> <string>#embedded-code</string> </dict> </array> </dict> <!-- normal attributes --> <key>tag-generic-attribute</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> - <string>\b([a-zA-Z\-:]+)</string> + <string>\b([a-zA-Z0-9_\-:]+)</string> <key>name</key> <string>entity.other.attribute-name.html</string> </dict> </array> </dict> <!-- ID attributes on elements (shows up in the symbol list) --> <key>tag-id-attribute</key> <dict> <key>begin</key> <string>\b(id)\b\s*=</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.other.attribute-name.id.html</string> </dict> </dict> <key>end</key> <string>(?&lt;='|")</string> <key>name</key> <string>meta.attribute-with-value.id.html</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>"</string> <key>contentName</key> <string>meta.toc-list.id.html</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <dict> <key>begin</key> <string>'</string> <key>contentName</key> <string>meta.toc-list.id.html</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> </array> </dict> <!-- handles all the inner workings of the tags --> <key>tag-stuff</key> <dict> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-id-attribute</string> </dict> <dict> <key>include</key> <string>#inline-function-stuff</string> </dict> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> <dict> <key>include</key> <string>#coldfusion-script</string> </dict> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>match</key> <string>.var\s</string> <key>name</key> <string>variable.other</string> </dict> <dict> <key>begin</key> <string>.&lt;cffunction\sname=('|")1</string> <key>contentName</key> <string>entity.name.function</string> <key>end</key> <string>'|"1</string> <key>name</key> <string>meta.tag.other</string> </dict> </array> </dict> <key>tag-finder</key> <dict> <key>begin</key> <string>&lt;([a-zA-Z0-9:]+)(?=[^&gt;]*&gt;&lt;/\1&gt;)</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.html</string> </dict> </dict> <key>end</key> <string>&gt;(&lt;)/(\1)&gt;</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>meta.scope.between-tag-pair.html</string> </dict> <key>2</key> <dict> <key>name</key> <string>entity.name.tag.html</string> </dict> </dict> <key>name</key> <string>meta.tag.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> </dict> <key>scopeName</key> <string>text.html.cfm</string> <key>uuid</key> <string>@SYNTAX_UUID@</string> </dict> </plist>
robrohan/coldfusion.tmbundle
b7d7e9fbff4d38462d91c614d7505e2c04c66846
Got the # to auto double when in just a cfoutput tag. Also tried tweaking the syntax file a bit to get it a bit less random
diff --git a/ColdFusion.bun/Preferences/ColdFusion Preferences.plist b/ColdFusion.bun/Preferences/ColdFusion Preferences.plist index 3c57317..fbff176 100644 Binary files a/ColdFusion.bun/Preferences/ColdFusion Preferences.plist and b/ColdFusion.bun/Preferences/ColdFusion Preferences.plist differ diff --git a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage index a867c39..cca20c1 100644 --- a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage +++ b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage @@ -1,865 +1,875 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>bundleUUID</key> <string>@BUNDLE_UUID@</string> <key>fileTypes</key> <array> <string>cfm</string> <string>cfml</string> <string>cfc</string> </array> <key>firstLineMatch</key> <string>&lt;!DOCTYPE|&lt;(?i:html)</string> <key>foldingStartMarker</key> <string>(?x) (&lt;(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script |ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction|cfcase|cfdefaultcase)\b.*?&gt; |&lt;!---(?!.*---\s*&gt;) )</string> <key>foldingStopMarker</key> <string>(?x) (&lt;/(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|scrip t|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction|cfcase|cfdefaultcase)&gt; |^(?!.*?&lt;!---).*?---\s*&gt; )</string> <key>keyEquivalent</key> <string>^~@c</string> <key>name</key> <string>@BUNDLE_NAME@</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-finder</string> </dict> <dict> <key>begin</key> <string>&lt;\?(xml)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.xml.html</string> </dict> </dict> <key>end</key> <string>\?&gt;</string> <key>name</key> <string>meta.tag.preprocessor.xml.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> </array> </dict> <dict> <key>include</key> <string>#cfcomment</string> </dict> - <dict> <key>include</key> <string>#htmlcomment</string> </dict> - <dict> <key>begin</key> <string>&lt;!</string> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.sgml.html</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>(DOCTYPE)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.doctype.html</string> </dict> </dict> <key>end</key> <string>(?=&gt;)</string> <key>name</key> <string>meta.tag.sgml.doctype.html</string> <key>patterns</key> <array> <dict> <key>match</key> <string>"[^"&gt;]*"</string> <key>name</key> <string>string.quoted.double.doctype.identifiers-and-DTDs.html</string> </dict> </array> </dict> <dict> <key>begin</key> <string>\[CDATA\[</string> <key>end</key> <string>]](?=&gt;)</string> <key>name</key> <string>constant.other.inline-data.html</string> </dict> <!--<dict> <key>match</key> <string>(\s*)(?!-=-=-|&gt;)\S(\s*)</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> --> </array> </dict> <dict> <key>include</key> <string>#coldfusion-script</string> </dict> <dict> <key>include</key> <string>#cffunction</string> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:style))\b(?![^&gt;]*/&gt;)</string> + <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.style.html</string> </dict> </dict> + <key>end</key> <string>&lt;/((?i:style))&gt;(?:\s*\n)?</string> + <key>name</key> <string>source.css.embedded.html</string> + <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> + <key>end</key> <string>(?=&lt;/(?i:style))</string> + <key>patterns</key> <array> - <dict> + <!-- <dict> <key>include</key> <string>#embedded-code</string> - </dict> + </dict> --> + <!-- <dict> + <key>include</key> + <string>#tag-finder</string> + </dict> --> <dict> <key>include</key> <string>source.css</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfquery))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> - <string>entity.name.tag.cfquery.html</string> + <string>entity.name.tag.script.html</string> + <!-- <string>entity.name.tag.cfquery.html</string> --> </dict> </dict> <key>end</key> <string>&lt;/((?i:cfquery))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.sql.embedded.html</string> + <key>patterns</key> <array> - <!-- this is here to colour the cfquery tag itself--> + <!-- this is here to colour the cfquery tag's attributes --> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:cfquery))</string> <key>patterns</key> <array> <!-- <dict> <key>include</key> <string>#embedded-code</string> </dict> --> <dict> <key>include</key> <string>source.sql</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:script))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(script|SCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:script|SCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:script))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/script)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/script)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfscript))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(cfscript|CFSCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:cfscript|CFSCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:cfscript))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/cfscript)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/cfscript)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:body|head|html)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.structure.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.structure.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:address|blockquote|dd|div|dl|dt|fieldset|form|frame|frameset|h1|h2 |h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|menu|pre)\ b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.block.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.block.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite |code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|la bel|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script| select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot |th|thead|title|tr|tt|u|var)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.inline.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.inline.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?([a-zA-Z0-9:]+)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>include</key> <string>#entities</string> </dict> <dict> <key>match</key> <string>&lt;&gt;</string> <key>name</key> <string>invalid.illegal.incomplete.html</string> </dict> <dict> <key>match</key> <string>&lt;(?=\W)|&gt;</string> <key>name</key> <string>invalid.illegal.bad-angle-bracket.html</string> </dict> </array> <key>repository</key> <dict> <key>cfcomment</key> <dict> <key>begin</key> <string>&lt;!---</string> <key>end</key> <string>---\s*&gt;</string> <key>name</key> <!-- <string>comment.block.html</string> --> <string>comment.line</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#cfcomment</string> </dict> <!-- <dict> <key>match</key> <string>-=-=-</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> --> </array> </dict> <key>htmlcomment</key> <dict> <key>begin</key> <string>&lt;!--</string> <key>end</key> <string>--&gt;</string> <key>name</key> <string>comment.block.html</string> <key>patterns</key> <array> <dict> <key>match</key> <string>--</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> </array> </dict> <key>cffunction</key> <dict> <key>begin</key> <string>&lt;(cffunction)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>entity.other.attribute-name.html</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.string.begin</string> </dict> <key>4</key> <dict> <key>name</key> <string>entity.name.function.cfml</string> </dict> <key>5</key> <dict> <key>name</key> <string>punctuation.definition.string.end</string> </dict> </dict> <key>match</key> <string>\b([nN][aA][mM][Ee])\b\s*(=)\s*(["'])([A-Za-z$_0-9]+)(["'])</string> </dict> <dict> <key>include</key> <string>source.cfml</string> </dict> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <key>embedded-code</key> <dict> <key>patterns</key> <array> <!-- <dict> <key>include</key> <string>#php</string> </dict> <dict> <key>include</key> <string>#ruby</string> </dict> <dict> <key>include</key> <string>#smarty</string> </dict> <dict> <key>include</key> <string>#python</string> </dict> --> <dict> <key>include</key> <string>#javascript</string> </dict> </array> </dict> <key>entities</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>&amp;([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);</string> <key>name</key> <string>constant.character.entity.html</string> </dict> <dict> <key>match</key> <string>&amp;</string> <key>name</key> <string>invalid.illegal.bad-ampersand.html</string> </dict> </array> </dict> <key>string-double-quoted</key> <dict> <key>begin</key> <string>"</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <key>string-single-quoted</key> <dict> <key>begin</key> <string>'</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <!-- Does function calls. For example, the xmlparse in cfset x=xmlparse() --> <key>inline-function-stuff</key> <dict> <key>begin</key> <!-- [^\#"'] --> <string>[a-zA-Z0-9_\.]+\s*\(</string> <key>contentName</key> <string>support.function.parameters</string> <key>end</key> <string>\)</string> <key>name</key> <string>support.function</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#inline-function-stuff</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> </array> </dict> <!-- the stuff between the ## --> <key>coldfusion-script</key> <dict> <key>begin</key> <string>#</string> <key>end</key> <string>\#</string> <key>name</key> <string>source.coldfusion.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#inline-function-stuff</string> </dict> <dict> <key>include</key> <string>#embedded-code</string> </dict> </array> </dict> - <!-- normal attributes --> <key>tag-generic-attribute</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>\b([a-zA-Z\-:]+)</string> <key>name</key> <string>entity.other.attribute-name.html</string> </dict> </array> </dict> <!-- ID attributes on elements (shows up in the symbol list) --> <key>tag-id-attribute</key> <dict> <key>begin</key> <string>\b(id)\b\s*=</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.other.attribute-name.id.html</string> </dict> </dict> <key>end</key> <string>(?&lt;='|")</string> <key>name</key> <string>meta.attribute-with-value.id.html</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>"</string> <key>contentName</key> <string>meta.toc-list.id.html</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <dict> <key>begin</key> <string>'</string> <key>contentName</key> <string>meta.toc-list.id.html</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> </array> </dict> <!-- handles all the inner workings of the tags --> <key>tag-stuff</key> <dict> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-id-attribute</string> </dict> <dict> <key>include</key> <string>#inline-function-stuff</string> </dict> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> <dict> <key>include</key> <string>#coldfusion-script</string> </dict> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>match</key> <string>.var\s</string> <key>name</key> <string>variable.other</string> </dict> <dict> <key>begin</key> <string>.&lt;cffunction\sname=('|")1</string> <key>contentName</key> <string>entity.name.function</string> <key>end</key> <string>'|"1</string> <key>name</key> <string>meta.tag.other</string> </dict> </array> </dict> <key>tag-finder</key> <dict> <key>begin</key> <string>&lt;([a-zA-Z0-9:]+)(?=[^&gt;]*&gt;&lt;/\1&gt;)</string> + <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.html</string> </dict> </dict> <key>end</key> <string>&gt;(&lt;)/(\1)&gt;</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>meta.scope.between-tag-pair.html</string> </dict> <key>2</key> <dict> <key>name</key> <string>entity.name.tag.html</string> </dict> </dict> <key>name</key> <string>meta.tag.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> </dict> <key>scopeName</key> <string>text.html.cfm</string> <key>uuid</key> <string>@SYNTAX_UUID@</string> </dict> </plist>
robrohan/coldfusion.tmbundle
d59da7727b5e88ce7ce5eef12d02b7d35c05fe1d
Adding in some default templates
diff --git a/ColdFusion.bun/.DS_Store b/ColdFusion.bun/.DS_Store index d83c5c5..24cb197 100644 Binary files a/ColdFusion.bun/.DS_Store and b/ColdFusion.bun/.DS_Store differ diff --git a/ColdFusion.bun/Templates/.DS_Store b/ColdFusion.bun/Templates/.DS_Store new file mode 100644 index 0000000..42f25b2 Binary files /dev/null and b/ColdFusion.bun/Templates/.DS_Store differ diff --git a/ColdFusion.bun/Templates/Application Component/info.plist b/ColdFusion.bun/Templates/Application Component/info.plist new file mode 100644 index 0000000..ec132ee Binary files /dev/null and b/ColdFusion.bun/Templates/Application Component/info.plist differ diff --git a/ColdFusion.bun/Templates/Application Component/template.cfm b/ColdFusion.bun/Templates/Application Component/template.cfm new file mode 100644 index 0000000..66f0186 --- /dev/null +++ b/ColdFusion.bun/Templates/Application Component/template.cfm @@ -0,0 +1,91 @@ +<!--- @@Copyright: Copyright (c) ${TM_YEAR} ${TM_ORGANIZATION_NAME}. All rights reserved. ---> +<!--- @@License: ---> +<cfcomponent output="false"> + + <!--- Application name, should be unique ---> + <cfset this.name = "ApplicationName"> + <!--- How long application vars persist ---> + <cfset this.applicationTimeout = createTimeSpan(0,2,0,0)> + <!--- Should client vars be enabled? ---> + <cfset this.clientManagement = false> + <!--- Where should we store them, if enable? ---> + <cfset this.clientStorage = "registry"> + <!--- Where should cflogin stuff persist ---> + <cfset this.loginStorage = "session"> + <!--- Should we even use sessions? ---> + <cfset this.sessionManagement = true> + <!--- How long do session vars persist? ---> + <cfset this.sessionTimeout = createTimeSpan(0,0,20,0)> + <!--- Should we set cookies on the browser? ---> + <cfset this.setClientCookies = true> + <!--- should cookies be domain specific, ie, *.foo.com or www.foo.com ---> + <cfset this.setDomainCookies = false> + <!--- should we try to block 'bad' input from users ---> + <cfset this.scriptProtect = "none"> + <!--- should we secure our JSON calls? ---> + <cfset this.secureJSON = false> + <!--- Should we use a prefix in front of JSON strings? ---> + <cfset this.secureJSONPrefix = ""> + <!--- Used to help CF work with missing files and dir indexes ---> + <cfset this.welcomeFileList = ""> + + <!--- define custom coldfusion mappings. Keys are mapping names, values are full paths ---> + <cfset this.mappings = structNew()> + <!--- define a list of custom tag paths. ---> + <cfset this.customtagpaths = ""> + + <!--- Run when application starts up ---> + <cffunction name="onApplicationStart" returnType="boolean" output="false"> + <cfreturn true> + </cffunction> + + <!--- Run when application stops ---> + <cffunction name="onApplicationEnd" returnType="void" output="false"> + <cfargument name="applicationScope" required="true"> + </cffunction> + + <!--- Fired when user requests a CFM that doesn't exist. ---> + <cffunction name="onMissingTemplate" returnType="boolean" output="false"> + <cfargument name="targetpage" required="true" type="string"> + <cfreturn true> + </cffunction> + + <!--- Run before the request is processed ---> + <cffunction name="onRequestStart" returnType="boolean" output="false"> + <cfargument name="thePage" type="string" required="true"> + <cfreturn true> + </cffunction> + + <!--- Runs before request as well, after onRequestStart ---> + <!--- + WARNING!!!!! THE USE OF THIS METHOD WILL BREAK FLASH REMOTING, WEB SERVICES, AND AJAX CALLS. + DO NOT USE THIS METHOD UNLESS YOU KNOW THIS AND KNOW HOW TO WORK AROUND IT! + EXAMPLE: http://www.coldfusionjedi.com/index.cfm?mode=entry&entry=ED9D4058-E661-02E9-E70A41706CD89724 + ---> + <cffunction name="onRequest" returnType="void"> + <cfargument name="thePage" type="string" required="true"> + <cfinclude template="#arguments.thePage#"> + </cffunction> + + <!--- Runs at end of request ---> + <cffunction name="onRequestEnd" returnType="void" output="false"> + <cfargument name="thePage" type="string" required="true"> + </cffunction> + + <!--- Runs on error ---> + <cffunction name="onError" returnType="void" output="false"> + <cfargument name="exception" required="true"> + <cfargument name="eventname" type="string" required="true"> + <cfdump var="#arguments#"><cfabort> + </cffunction> + + <!--- Runs when your session starts ---> + <cffunction name="onSessionStart" returnType="void" output="false"> + </cffunction> + + <!--- Runs when session ends ---> + <cffunction name="onSessionEnd" returnType="void" output="false"> + <cfargument name="sessionScope" type="struct" required="true"> + <cfargument name="appScope" type="struct" required="false"> + </cffunction> +</cfcomponent> \ No newline at end of file diff --git a/ColdFusion.bun/Templates/ColdFusion Component/info.plist b/ColdFusion.bun/Templates/ColdFusion Component/info.plist new file mode 100644 index 0000000..37b5384 Binary files /dev/null and b/ColdFusion.bun/Templates/ColdFusion Component/info.plist differ diff --git a/ColdFusion.bun/Templates/ColdFusion Component/template.cfm b/ColdFusion.bun/Templates/ColdFusion Component/template.cfm new file mode 100644 index 0000000..c0e748e --- /dev/null +++ b/ColdFusion.bun/Templates/ColdFusion Component/template.cfm @@ -0,0 +1,9 @@ +<!--- @@Copyright: Copyright (c) ${TM_YEAR} ${TM_ORGANIZATION_NAME}. All rights reserved. ---> +<!--- @@License: ---> +<cfcomponent output="false"> + + <cffunction access="public" returntype="void" name="init"> + + </cffunction> + +</cfcomponent> \ No newline at end of file diff --git a/ColdFusion.bun/Templates/ColdFusion Page/info.plist b/ColdFusion.bun/Templates/ColdFusion Page/info.plist new file mode 100644 index 0000000..380420c Binary files /dev/null and b/ColdFusion.bun/Templates/ColdFusion Page/info.plist differ diff --git a/ColdFusion.bun/Templates/ColdFusion Page/template.cfm b/ColdFusion.bun/Templates/ColdFusion Page/template.cfm new file mode 100644 index 0000000..66d6452 --- /dev/null +++ b/ColdFusion.bun/Templates/ColdFusion Page/template.cfm @@ -0,0 +1,4 @@ +<!--- @@Copyright: Copyright (c) ${TM_YEAR} ${TM_ORGANIZATION_NAME}. All rights reserved. ---> +<!--- @@License: ---> + + diff --git a/ColdFusion.bun/Templates/Custom Tag/info.plist b/ColdFusion.bun/Templates/Custom Tag/info.plist new file mode 100644 index 0000000..e49dbae Binary files /dev/null and b/ColdFusion.bun/Templates/Custom Tag/info.plist differ diff --git a/ColdFusion.bun/Templates/Custom Tag/template.cfm b/ColdFusion.bun/Templates/Custom Tag/template.cfm new file mode 100644 index 0000000..7d611b4 --- /dev/null +++ b/ColdFusion.bun/Templates/Custom Tag/template.cfm @@ -0,0 +1,13 @@ +<cfsetting enablecfoutputonly="Yes"> +<!--- @@Copyright: Copyright (c) ${TM_YEAR} ${TM_ORGANIZATION_NAME}. All rights reserved. ---> +<!--- @@License: ---> + +<cfif thistag.executionMode eq "Start"> + +</cfif> + +<cfif thistag.executionmode eq "End"> + <cfexit method="exittag" /> +</cfif> + +<cfsetting enablecfoutputonly="No"> \ No newline at end of file diff --git a/dictToBundle.xsl b/dictToBundle.xsl index ee65401..fcd505c 100644 --- a/dictToBundle.xsl +++ b/dictToBundle.xsl @@ -1,407 +1,412 @@ <?xml version="1.0" encoding="UTF-8" ?> <!-- dictToBundle Created by Rob Rohan on 2008-11-22. Copyright (c) 2008-2009 Rob Rohan. All rights reserved. The default output from this process is the info.plist file. However, this also generates the files for the tag completion and for the default snippets. The snippets wind up in the Snippets directory and the tag and attribute lists wind up in the Preferences folder. --> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:dic="http://www.cfeclipse.org/version1/dictionary" xmlns:util="java:java.util.UUID" version="2.0" exclude-result-prefixes="xsl dic util"> <xsl:output method="xml" indent="yes" /> <xsl:output method="xml" indent="yes" name="plistxml" exclude-result-prefixes="xsl dic util" /> <!-- <xsl:param name="bundle-dir" select="'ColdFusion.bun'" /> --> <xsl:param name="bundle-uuid" select="'1A09BE0B-E81A-4CB7-AF69-AFC845162D1F'" /> <xsl:param name="bundle-name" select="'ColdFusion'" /> <xsl:param name="syntax-uuid" select="''" /> <xsl:param name="cmddoc-uuid" select="''" /> <xsl:param name="tagcomplete-uuid" select="''" /> <xsl:param name="attcomplete-uuid" select="''" /> <xsl:variable name="NL"> <xsl:text> </xsl:text> </xsl:variable> <xsl:variable name="TAB"> <xsl:text> </xsl:text> </xsl:variable> <!-- writes out the plist, and kicks off the snippet writting --> <xsl:template match="/"> <plist version="1.0"> <dict> <key>contactEmailRot13</key> <string>[email protected]</string> <key>contactName</key> <string>Rob Rohan</string> <key>description</key> <string>Support for the ColdFusion web development environment.</string> <key>mainMenu</key> <dict> <key>items</key> <array> <string>C8F9D7A6-D447-4C16-B566-BE46335B1067</string> <string>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</string> <string>------------------------------------</string> <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> + <string>------------------------------------</string> + <string>FFDC5F11-5575-4C8C-9CAC-4DFC1163CFEA</string> + <string>0DEA11CD-931E-4087-984A-784A2D825EF2</string> + <string>7EC225A6-93C8-4A2E-906A-3ADA1FD3C172</string> + <string>8D2B412E-56DF-4728-AB74-C1C674277E22</string> <string><xsl:value-of select="$cmddoc-uuid" /></string> <string><xsl:value-of select="$tagcomplete-uuid" /></string> <string><xsl:value-of select="$attcomplete-uuid" /></string> <!-- Now that we have written out the plist file and the snippets --> <!-- fire off the bit that does the tag and attribute completion --> <xsl:call-template name="write-tag-completion-list" /> <xsl:call-template name="write-attribute-completion-list" /> </array> <key>submenus</key> <dict> <key>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</key> <dict> <key>items</key> <array> <xsl:comment>FUNCTIONS</xsl:comment><xsl:value-of select="$NL" /> <xsl:apply-templates select="/dic:dictionary/dic:functions/dic:function" /> </array> <key>name</key> <string>ColdFusion Functions</string> </dict> <key>C8F9D7A6-D447-4C16-B566-BE46335B1067</key> <dict> <key>items</key> <array> <xsl:comment>TAGS</xsl:comment><xsl:value-of select="$NL" /> <xsl:apply-templates select="/dic:dictionary/dic:tags/dic:tag" /> </array> <key>name</key> <string>ColdFusion Tags</string> </dict> </dict> </dict> <key>name</key> <string><xsl:value-of select="$bundle-name" /></string> <key>ordering</key> <array> <!-- <string>00D00AD7-3C05-46E0-B8B9-0F5CCAC04F57</string> <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> --> </array> <key>uuid</key> <string><xsl:value-of select="$bundle-uuid" /></string> </dict> </plist> </xsl:template> <!-- Formats the functions. Writes the plist too. --> <xsl:template match="dic:function"> <xsl:variable name="filename" select="translate(@name,':','-')" /> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:value-of select="$NL" /> <!-- {$bundle-dir}/ --> <xsl:result-document href="Snippets/gen-{$filename}.tmSnippet" format="plistxml"> <plist version="1.0"> <dict> <key>content</key> <string><xsl:value-of select="@name" /> <xsl:text>(${1:</xsl:text> <xsl:for-each select="./dic:parameter"> <xsl:call-template name="param-with-placement"> <xsl:with-param name="placement" select="position()+1" /> <xsl:with-param name="separator" select="''" /> <xsl:with-param name="preparator" select="', '" /> <xsl:with-param name="use-equals" select="'false'" /> <xsl:with-param name="total-param-count" select="count(../dic:parameter)" /> </xsl:call-template> </xsl:for-each> <xsl:text>})</xsl:text></string> <key>name</key> <string><xsl:value-of select="@name"/></string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string><xsl:value-of select="@name"/></string> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <!-- Formats the tags. Writes out the plist file too --> <xsl:template match="dic:tag"> <xsl:variable name="filename" select="translate(@name,':','-')" /> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:value-of select="$NL" /> <!-- {$bundle-dir}/ --> <xsl:result-document href="Snippets/gen-{$filename}.tmSnippet" format="plistxml"> <plist version="1.0"> <dict> <key>content</key> <string><xsl:text>&lt;</xsl:text> <xsl:value-of select="@name" /> <xsl:text> ${1:</xsl:text> <xsl:for-each select="./dic:parameter"> <xsl:call-template name="param-with-placement"> <xsl:with-param name="placement" select="position()+position()" /> <xsl:with-param name="separator" select="' '" /> <xsl:with-param name="preparator" select="''" /> <xsl:with-param name="use-equals" select="'true'" /> <xsl:with-param name="total-param-count" select="count(../dic:parameter)" /> <!-- <xsl:with-param name="element" select="." /> --> </xsl:call-template> </xsl:for-each> <xsl:text>}</xsl:text> <xsl:choose> <xsl:when test="@single = 'true'"> <xsl:text> /&gt;$0</xsl:text> </xsl:when> <xsl:otherwise> <xsl:text>&gt;</xsl:text> <xsl:value-of select="$NL" /> <xsl:value-of select="$TAB" /> <xsl:text>$0</xsl:text> <xsl:value-of select="$NL" /> <xsl:text>&lt;/</xsl:text> <xsl:value-of select="@name" /> <xsl:text>&gt;</xsl:text> </xsl:otherwise> </xsl:choose></string> <key>name</key> <string><xsl:value-of select="@name"/></string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string> <xsl:choose> <xsl:when test="contains(@name,':')"> <xsl:value-of select="substring-before(@name,':')" /> </xsl:when> <xsl:otherwise> <xsl:value-of select="@name" /> </xsl:otherwise> </xsl:choose> </string> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <!-- handles doing the tag and function params. Takes 3 params. placement = where to start the textmate $N variables from separator = what to tack on to the end of each paramenter total-param-count = total number of params, so we don't add the separator to the last item. --> <xsl:template name="param-with-placement"> <xsl:param name="placement" /> <xsl:param name="separator" /> <xsl:param name="preparator" /> <xsl:param name="use-equals" /> <xsl:param name="total-param-count" /> <xsl:choose> <xsl:when test="$use-equals = 'true'"> <xsl:text>$</xsl:text> <xsl:text>{</xsl:text> <xsl:value-of select="$placement" /> <xsl:text>:</xsl:text> <xsl:value-of select="$preparator" /> <xsl:value-of select="@name" /><xsl:text>="$</xsl:text> <xsl:value-of select="$placement+1" /> <xsl:text>"</xsl:text> <xsl:if test="position() != $total-param-count"> <xsl:value-of select="$separator" /> </xsl:if> <xsl:text>}</xsl:text> </xsl:when> <xsl:otherwise> <xsl:if test="@required = 'true'"> <xsl:if test="position() != 1"> <xsl:value-of select="$preparator" /> </xsl:if> <xsl:if test="@type = 'String'"> <xsl:text>"</xsl:text> </xsl:if> </xsl:if> <xsl:text>${</xsl:text> <xsl:value-of select="$placement" /> <xsl:text>:</xsl:text> <xsl:if test="@required = 'false'"> <xsl:if test="position() != 1"> <xsl:value-of select="$preparator" /> </xsl:if> </xsl:if> <xsl:if test="@required = 'false'"><xsl:text>[</xsl:text></xsl:if> <xsl:value-of select="@name" /> <xsl:if test="@required = 'false'"><xsl:text>]</xsl:text></xsl:if> <xsl:text>}</xsl:text> <xsl:if test="@required = 'true'"> <xsl:if test="@type = 'String'"> <xsl:text>"</xsl:text> </xsl:if> </xsl:if> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- make a list of tags in the format textmate expects for code completion --> <xsl:template name="write-tag-completion-list"> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:result-document href="Preferences/Completion%20Tags.tmPreferences" format="plistxml"> <plist version="1.0"> <dict> <key>name</key> <string>Completions Tags</string> <key>scope</key> <!-- text.html.cfm, invalid.illegal.incomplete.html --> <string>text.html -(meta.tag | source), invalid.illegal.incomplete.html -source</string> <key>settings</key> <dict> <key>shellVariables</key> <array> <dict> <key>name</key> <string>TM_COMPLETION_split</string> <key>value</key> <string>,</string> </dict> <dict> <key>name</key> <string>TM_COMPLETIONS</string> <key>value</key> <string> <xsl:for-each select="//dic:tag"> <xsl:value-of select="./@name" /><xsl:text>,</xsl:text> </xsl:for-each> </string> </dict> </array> </dict> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> <!-- <string><xsl:value-of select="$tagcomplete-uuid" /></string> --> </dict> </plist> </xsl:result-document> </xsl:template> <xsl:template name="write-attribute-completion-list"> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:result-document href="Preferences/Completion%20Attributes.tmPreferences" format="plistxml"> <plist version="1.0"> <dict> <key>name</key> <string>Completions Attributes</string> <key>scope</key> <!-- text.html meta.tag -(entity.other.attribute-name | punctuation.definition.tag.begin | source | entity.name.tag | string | invalid.illegal.incomplete.html)--> <string>text.html.cfm meta.tag.other.html</string> <key>settings</key> <dict> <key>completions</key> <array> <xsl:for-each select="//dic:tag"> <string><xsl:value-of select="@name" /></string> <string><xsl:value-of select="translate(@name,'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')" /></string> </xsl:for-each> </array> <key>disableDefaultCompletion</key> <integer>1</integer> <key>shellVariables</key> <array> <dict> <key>name</key> <string>TM_COMPLETION_split</string> <key>value</key> <string>,</string> </dict> <dict> <key>name</key> <string>TM_COMPLETION_scope</string> <key>value</key> <string>html_attributes</string> </dict> <dict> <key>name</key> <string>TM_COMPLETIONS</string> <key>value</key> <string> <xsl:for-each select="//dic:tag/dic:parameter"> <xsl:text>&lt;</xsl:text> <xsl:value-of select="../@name" /><xsl:text> </xsl:text> <xsl:value-of select="./@name" /> <xsl:text>=&quot;&quot;</xsl:text> <xsl:text>,</xsl:text> </xsl:for-each> </string> </dict> </array> </dict> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <xsl:template match="text()" /> </xsl:stylesheet> \ No newline at end of file
robrohan/coldfusion.tmbundle
42ac27fd40ab76bba2cd295d676bad3062a6a2fd
Fixed comment in a comment and added a new rule for html comment
diff --git a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage index 81406bb..a867c39 100644 --- a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage +++ b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage @@ -1,819 +1,865 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>bundleUUID</key> <string>@BUNDLE_UUID@</string> <key>fileTypes</key> <array> <string>cfm</string> <string>cfml</string> <string>cfc</string> </array> <key>firstLineMatch</key> <string>&lt;!DOCTYPE|&lt;(?i:html)</string> <key>foldingStartMarker</key> <string>(?x) (&lt;(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script |ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction|cfcase|cfdefaultcase)\b.*?&gt; |&lt;!---(?!.*---\s*&gt;) )</string> <key>foldingStopMarker</key> <string>(?x) (&lt;/(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|scrip t|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction|cfcase|cfdefaultcase)&gt; |^(?!.*?&lt;!---).*?---\s*&gt; )</string> <key>keyEquivalent</key> <string>^~@c</string> <key>name</key> <string>@BUNDLE_NAME@</string> <key>patterns</key> <array> <dict> - <key>begin</key> - <string>&lt;([a-zA-Z0-9:]+)(?=[^&gt;]*&gt;&lt;/\1&gt;)</string> - <key>beginCaptures</key> - <dict> - <key>1</key> - <dict> - <key>name</key> - <string>entity.name.tag.html</string> - </dict> - </dict> - <key>end</key> - <string>&gt;(&lt;)/(\1)&gt;</string> - <key>endCaptures</key> - <dict> - <key>1</key> - <dict> - <key>name</key> - <string>meta.scope.between-tag-pair.html</string> - </dict> - <key>2</key> - <dict> - <key>name</key> - <string>entity.name.tag.html</string> - </dict> - </dict> - <key>name</key> - <string>meta.tag.any.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#tag-stuff</string> - </dict> - </array> + <key>include</key> + <string>#tag-finder</string> </dict> <dict> <key>begin</key> <string>&lt;\?(xml)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.xml.html</string> </dict> </dict> <key>end</key> <string>\?&gt;</string> <key>name</key> <string>meta.tag.preprocessor.xml.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> </array> </dict> <dict> - <key>begin</key> - <string>&lt;!---</string> - <key>end</key> - <string>---\s*&gt;</string> - <key>name</key> - <string>comment.block.html</string> - <key>patterns</key> - <array> - <dict> - <key>match</key> - <string>---</string> - <key>name</key> - <string>invalid.illegal.bad-comments-or-CDATA.html</string> - </dict> - </array> + <key>include</key> + <string>#cfcomment</string> + </dict> + + <dict> + <key>include</key> + <string>#htmlcomment</string> </dict> + <dict> <key>begin</key> <string>&lt;!</string> <key>end</key> <string>&gt;</string> <key>name</key> + <string>meta.tag.sgml.html</string> + <key>patterns</key> <array> <dict> <key>begin</key> <string>(DOCTYPE)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.doctype.html</string> </dict> </dict> <key>end</key> <string>(?=&gt;)</string> <key>name</key> <string>meta.tag.sgml.doctype.html</string> <key>patterns</key> <array> <dict> <key>match</key> <string>"[^"&gt;]*"</string> <key>name</key> <string>string.quoted.double.doctype.identifiers-and-DTDs.html</string> </dict> </array> </dict> <dict> <key>begin</key> <string>\[CDATA\[</string> <key>end</key> <string>]](?=&gt;)</string> <key>name</key> <string>constant.other.inline-data.html</string> </dict> - <dict> + <!--<dict> <key>match</key> - <string>(\s*)(?!---|&gt;)\S(\s*)</string> + <string>(\s*)(?!-=-=-|&gt;)\S(\s*)</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> - </dict> + </dict> --> </array> </dict> <dict> <key>include</key> <string>#coldfusion-script</string> </dict> <dict> <key>include</key> <string>#cffunction</string> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:style))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.style.html</string> </dict> </dict> <key>end</key> <string>&lt;/((?i:style))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.css.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:style))</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>source.css</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfquery))\b(?![^&gt;]*/&gt;)</string> + <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.cfquery.html</string> </dict> </dict> + <key>end</key> <string>&lt;/((?i:cfquery))&gt;(?:\s*\n)?</string> + <key>name</key> <string>source.sql.embedded.html</string> <key>patterns</key> <array> + <!-- this is here to colour the cfquery tag itself--> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:cfquery))</string> <key>patterns</key> <array> - <dict> + <!-- <dict> <key>include</key> <string>#embedded-code</string> - </dict> + </dict> --> <dict> <key>include</key> <string>source.sql</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:script))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(script|SCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:script|SCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:script))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/script)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/script)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfscript))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(cfscript|CFSCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:cfscript|CFSCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:cfscript))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/cfscript)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/cfscript)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:body|head|html)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.structure.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.structure.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:address|blockquote|dd|div|dl|dt|fieldset|form|frame|frameset|h1|h2 |h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|menu|pre)\ b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.block.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.block.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite |code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|la bel|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script| select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot |th|thead|title|tr|tt|u|var)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.inline.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.inline.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?([a-zA-Z0-9:]+)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>include</key> <string>#entities</string> </dict> <dict> <key>match</key> <string>&lt;&gt;</string> <key>name</key> <string>invalid.illegal.incomplete.html</string> </dict> <dict> <key>match</key> <string>&lt;(?=\W)|&gt;</string> <key>name</key> <string>invalid.illegal.bad-angle-bracket.html</string> </dict> </array> <key>repository</key> <dict> + <key>cfcomment</key> + <dict> + <key>begin</key> + <string>&lt;!---</string> + <key>end</key> + <string>---\s*&gt;</string> + <key>name</key> + <!-- <string>comment.block.html</string> --> + <string>comment.line</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#cfcomment</string> + </dict> + <!-- <dict> + <key>match</key> + <string>-=-=-</string> + <key>name</key> + <string>invalid.illegal.bad-comments-or-CDATA.html</string> + </dict> --> + </array> + </dict> + + <key>htmlcomment</key> + <dict> + <key>begin</key> + <string>&lt;!--</string> + <key>end</key> + <string>--&gt;</string> + <key>name</key> + <string>comment.block.html</string> + <key>patterns</key> + <array> + <dict> + <key>match</key> + <string>--</string> + <key>name</key> + <string>invalid.illegal.bad-comments-or-CDATA.html</string> + </dict> + </array> + </dict> + <key>cffunction</key> <dict> <key>begin</key> <string>&lt;(cffunction)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> - <!-- <string>meta.tag.language.cfml.function</string> --> <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> - <!-- <string>meta.tag.language.cfml.function</string> --> <string>entity.other.attribute-name.html</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.string.begin</string> </dict> <key>4</key> <dict> <key>name</key> <string>entity.name.function.cfml</string> </dict> <key>5</key> <dict> <key>name</key> <string>punctuation.definition.string.end</string> </dict> </dict> <key>match</key> <string>\b([nN][aA][mM][Ee])\b\s*(=)\s*(["'])([A-Za-z$_0-9]+)(["'])</string> </dict> <dict> <key>include</key> <string>source.cfml</string> </dict> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <key>embedded-code</key> <dict> <key>patterns</key> <array> <!-- <dict> <key>include</key> <string>#php</string> </dict> <dict> <key>include</key> <string>#ruby</string> </dict> <dict> <key>include</key> <string>#smarty</string> </dict> <dict> <key>include</key> <string>#python</string> </dict> --> <dict> <key>include</key> <string>#javascript</string> </dict> </array> </dict> <key>entities</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>&amp;([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);</string> <key>name</key> <string>constant.character.entity.html</string> </dict> <dict> <key>match</key> <string>&amp;</string> <key>name</key> <string>invalid.illegal.bad-ampersand.html</string> </dict> </array> </dict> <key>string-double-quoted</key> <dict> <key>begin</key> <string>"</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <key>string-single-quoted</key> <dict> <key>begin</key> <string>'</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <!-- Does function calls. For example, the xmlparse in cfset x=xmlparse() --> <key>inline-function-stuff</key> <dict> <key>begin</key> <!-- [^\#"'] --> <string>[a-zA-Z0-9_\.]+\s*\(</string> <key>contentName</key> <string>support.function.parameters</string> <key>end</key> <string>\)</string> <key>name</key> <string>support.function</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#inline-function-stuff</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> </array> </dict> <!-- the stuff between the ## --> <key>coldfusion-script</key> <dict> <key>begin</key> <string>#</string> <key>end</key> <string>\#</string> <key>name</key> <string>source.coldfusion.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#inline-function-stuff</string> </dict> <dict> <key>include</key> <string>#embedded-code</string> </dict> </array> </dict> <!-- normal attributes --> <key>tag-generic-attribute</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>\b([a-zA-Z\-:]+)</string> <key>name</key> <string>entity.other.attribute-name.html</string> </dict> </array> </dict> <!-- ID attributes on elements (shows up in the symbol list) --> <key>tag-id-attribute</key> <dict> <key>begin</key> <string>\b(id)\b\s*=</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.other.attribute-name.id.html</string> </dict> </dict> <key>end</key> <string>(?&lt;='|")</string> <key>name</key> <string>meta.attribute-with-value.id.html</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>"</string> <key>contentName</key> <string>meta.toc-list.id.html</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <dict> <key>begin</key> <string>'</string> <key>contentName</key> <string>meta.toc-list.id.html</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> </array> </dict> - <!-- handles all tags --> + <!-- handles all the inner workings of the tags --> <key>tag-stuff</key> <dict> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-id-attribute</string> </dict> <dict> <key>include</key> <string>#inline-function-stuff</string> </dict> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> <dict> <key>include</key> <string>#coldfusion-script</string> </dict> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>match</key> <string>.var\s</string> <key>name</key> <string>variable.other</string> </dict> <dict> <key>begin</key> <string>.&lt;cffunction\sname=('|")1</string> <key>contentName</key> <string>entity.name.function</string> <key>end</key> <string>'|"1</string> <key>name</key> <string>meta.tag.other</string> </dict> </array> </dict> + + <key>tag-finder</key> + <dict> + <key>begin</key> + <string>&lt;([a-zA-Z0-9:]+)(?=[^&gt;]*&gt;&lt;/\1&gt;)</string> + <key>beginCaptures</key> + <dict> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.html</string> + </dict> + </dict> + <key>end</key> + <string>&gt;(&lt;)/(\1)&gt;</string> + <key>endCaptures</key> + <dict> + <key>1</key> + <dict> + <key>name</key> + <string>meta.scope.between-tag-pair.html</string> + </dict> + <key>2</key> + <dict> + <key>name</key> + <string>entity.name.tag.html</string> + </dict> + </dict> + <key>name</key> + <string>meta.tag.any.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + </array> + </dict> </dict> <key>scopeName</key> <string>text.html.cfm</string> <key>uuid</key> <string>@SYNTAX_UUID@</string> </dict> </plist>
robrohan/coldfusion.tmbundle
bd82c15fa0550a4822f16678904eabe232e0cd09
Made some syntax improvements, and added in basic snippets
diff --git a/ColdFusion.bun/.DS_Store b/ColdFusion.bun/.DS_Store index 6e9e6d8..d83c5c5 100644 Binary files a/ColdFusion.bun/.DS_Store and b/ColdFusion.bun/.DS_Store differ diff --git a/ColdFusion.bun/Snippets/x_abort.tmSnippet b/ColdFusion.bun/Snippets/x_abort.tmSnippet new file mode 100644 index 0000000..a471275 --- /dev/null +++ b/ColdFusion.bun/Snippets/x_abort.tmSnippet @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>content</key> + <string>&lt;cfabort /&gt;$0</string> + <key>name</key> + <string>abort</string> + <key>scope</key> + <string>text.html.cfm</string> + <key>tabTrigger</key> + <string>abort</string> + <key>uuid</key> + <string>151D9D1B-48D8-405A-8E7B-64B548EC9F9C</string> +</dict> +</plist> diff --git a/ColdFusion.bun/Snippets/x_dump.tmSnippet b/ColdFusion.bun/Snippets/x_dump.tmSnippet new file mode 100644 index 0000000..e9bcada --- /dev/null +++ b/ColdFusion.bun/Snippets/x_dump.tmSnippet @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>content</key> + <string>&lt;cfdump var="#${TM_SELECTED_TEXT}$1#" /&gt;$0</string> + <key>keyEquivalent</key> + <string>^D</string> + <key>name</key> + <string>dump</string> + <key>scope</key> + <string>text.html.cfm</string> + <key>tabTrigger</key> + <string>dump</string> + <key>uuid</key> + <string>C0FF2DEC-99D6-45AE-AF68-049D0DFD6E98</string> +</dict> +</plist> diff --git a/ColdFusion.bun/Snippets/x_output.tmSnippet b/ColdFusion.bun/Snippets/x_output.tmSnippet new file mode 100644 index 0000000..b518b52 --- /dev/null +++ b/ColdFusion.bun/Snippets/x_output.tmSnippet @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>content</key> + <string>&lt;cfoutput&gt;${TM_SELECTED_TEXT}$0&lt;/cfoutput&gt;</string> + <key>keyEquivalent</key> + <string>^O</string> + <key>name</key> + <string>output</string> + <key>scope</key> + <string>text.html.cfm</string> + <key>tabTrigger</key> + <string>output</string> + <key>uuid</key> + <string>C3F90629-A2AF-4C50-B812-1E9194E71B24</string> +</dict> +</plist> diff --git a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage index ca0a678..81406bb 100644 --- a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage +++ b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage @@ -1,790 +1,819 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>bundleUUID</key> <string>@BUNDLE_UUID@</string> <key>fileTypes</key> <array> <string>cfm</string> <string>cfml</string> <string>cfc</string> </array> <key>firstLineMatch</key> <string>&lt;!DOCTYPE|&lt;(?i:html)</string> <key>foldingStartMarker</key> <string>(?x) -(&lt;(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script |ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction)\b.*?&gt; +(&lt;(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script |ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction|cfcase|cfdefaultcase)\b.*?&gt; |&lt;!---(?!.*---\s*&gt;) )</string> <key>foldingStopMarker</key> <string>(?x) -(&lt;/(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|scrip t|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction)&gt; +(&lt;/(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|scrip t|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction|cfcase|cfdefaultcase)&gt; |^(?!.*?&lt;!---).*?---\s*&gt; )</string> <key>keyEquivalent</key> <string>^~@c</string> <key>name</key> <string>@BUNDLE_NAME@</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>&lt;([a-zA-Z0-9:]+)(?=[^&gt;]*&gt;&lt;/\1&gt;)</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.html</string> </dict> </dict> <key>end</key> <string>&gt;(&lt;)/(\1)&gt;</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>meta.scope.between-tag-pair.html</string> </dict> <key>2</key> <dict> <key>name</key> <string>entity.name.tag.html</string> </dict> </dict> <key>name</key> <string>meta.tag.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;\?(xml)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.xml.html</string> </dict> </dict> <key>end</key> <string>\?&gt;</string> <key>name</key> <string>meta.tag.preprocessor.xml.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;!---</string> <key>end</key> <string>---\s*&gt;</string> <key>name</key> <string>comment.block.html</string> <key>patterns</key> <array> <dict> <key>match</key> <string>---</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;!</string> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.sgml.html</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>(DOCTYPE)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.doctype.html</string> </dict> </dict> <key>end</key> <string>(?=&gt;)</string> <key>name</key> <string>meta.tag.sgml.doctype.html</string> <key>patterns</key> <array> <dict> <key>match</key> <string>"[^"&gt;]*"</string> <key>name</key> <string>string.quoted.double.doctype.identifiers-and-DTDs.html</string> </dict> </array> </dict> <dict> <key>begin</key> <string>\[CDATA\[</string> <key>end</key> <string>]](?=&gt;)</string> <key>name</key> <string>constant.other.inline-data.html</string> </dict> <dict> <key>match</key> <string>(\s*)(?!---|&gt;)\S(\s*)</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> </array> </dict> <dict> <key>include</key> <string>#coldfusion-script</string> </dict> <dict> <key>include</key> <string>#cffunction</string> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:style))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.style.html</string> </dict> </dict> <key>end</key> <string>&lt;/((?i:style))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.css.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:style))</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>source.css</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfquery))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.cfquery.html</string> </dict> </dict> <key>end</key> <string>&lt;/((?i:cfquery))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.sql.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:cfquery))</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>source.sql</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:script))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(script|SCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:script|SCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:script))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/script)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/script)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfscript))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(cfscript|CFSCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:cfscript|CFSCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:cfscript))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/cfscript)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/cfscript)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:body|head|html)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.structure.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.structure.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:address|blockquote|dd|div|dl|dt|fieldset|form|frame|frameset|h1|h2 |h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|menu|pre)\ b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.block.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.block.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite |code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|la bel|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script| select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot |th|thead|title|tr|tt|u|var)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.inline.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.inline.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?([a-zA-Z0-9:]+)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>include</key> <string>#entities</string> </dict> <dict> <key>match</key> <string>&lt;&gt;</string> <key>name</key> <string>invalid.illegal.incomplete.html</string> </dict> <dict> <key>match</key> <string>&lt;(?=\W)|&gt;</string> <key>name</key> <string>invalid.illegal.bad-angle-bracket.html</string> </dict> </array> <key>repository</key> <dict> <key>cffunction</key> <dict> <key>begin</key> <string>&lt;(cffunction)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> - <string>entity.name.tag.cfml</string> + <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> - <string>meta.tag.language.cfml.function</string> + <!-- <string>meta.tag.language.cfml.function</string> --> + <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> - <string>meta.tag.language.cfml.function</string> + <!-- <string>meta.tag.language.cfml.function</string> --> + <string>entity.other.attribute-name.html</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.string.begin</string> </dict> <key>4</key> <dict> <key>name</key> <string>entity.name.function.cfml</string> </dict> <key>5</key> <dict> <key>name</key> <string>punctuation.definition.string.end</string> </dict> </dict> <key>match</key> <string>\b([nN][aA][mM][Ee])\b\s*(=)\s*(["'])([A-Za-z$_0-9]+)(["'])</string> </dict> <dict> <key>include</key> <string>source.cfml</string> </dict> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> - <key>coldfusion-script</key> - <dict> - <key>begin</key> - <string>#</string> - <key>end</key> - <string>\#</string> - <key>name</key> - <string>source.coldfusion.embedded.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#embedded-code</string> - </dict> - </array> - </dict> - <key>embedded-code</key> <dict> <key>patterns</key> <array> - <dict> + <!-- <dict> <key>include</key> <string>#php</string> </dict> <dict> <key>include</key> <string>#ruby</string> </dict> <dict> <key>include</key> <string>#smarty</string> </dict> <dict> <key>include</key> <string>#python</string> - </dict> + </dict> --> <dict> <key>include</key> <string>#javascript</string> </dict> </array> </dict> <key>entities</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>&amp;([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);</string> <key>name</key> <string>constant.character.entity.html</string> </dict> <dict> <key>match</key> <string>&amp;</string> <key>name</key> <string>invalid.illegal.bad-ampersand.html</string> </dict> </array> </dict> <key>string-double-quoted</key> <dict> <key>begin</key> <string>"</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <key>string-single-quoted</key> <dict> <key>begin</key> <string>'</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> - <key>tag-generic-attribute</key> + <!-- Does function calls. For example, the xmlparse in cfset x=xmlparse() --> + <key>inline-function-stuff</key> <dict> - <key>match</key> - <string>\b([a-zA-Z\-:]+)</string> + <key>begin</key> + <!-- [^\#"'] --> + <string>[a-zA-Z0-9_\.]+\s*\(</string> + + <key>contentName</key> + <string>support.function.parameters</string> + + <key>end</key> + <string>\)</string> + + <key>name</key> + <string>support.function</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#inline-function-stuff</string> + </dict> + <dict> + <key>include</key> + <string>#string-double-quoted</string> + </dict> + <dict> + <key>include</key> + <string>#string-single-quoted</string> + </dict> + </array> + </dict> + + <!-- the stuff between the ## --> + <key>coldfusion-script</key> + <dict> + <key>begin</key> + <string>#</string> + <key>end</key> + <string>\#</string> <key>name</key> - <string>entity.other.attribute-name.html</string> + <string>source.coldfusion.embedded.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#inline-function-stuff</string> + </dict> + <dict> + <key>include</key> + <string>#embedded-code</string> + </dict> + </array> + </dict> + + + <!-- normal attributes --> + <key>tag-generic-attribute</key> + <dict> + <key>patterns</key> + <array> + <dict> + <key>match</key> + <string>\b([a-zA-Z\-:]+)</string> + + <key>name</key> + <string>entity.other.attribute-name.html</string> + </dict> + </array> </dict> + <!-- ID attributes on elements (shows up in the symbol list) --> <key>tag-id-attribute</key> <dict> <key>begin</key> <string>\b(id)\b\s*=</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.other.attribute-name.id.html</string> </dict> </dict> <key>end</key> <string>(?&lt;='|")</string> <key>name</key> <string>meta.attribute-with-value.id.html</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>"</string> <key>contentName</key> <string>meta.toc-list.id.html</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <dict> <key>begin</key> <string>'</string> <key>contentName</key> <string>meta.toc-list.id.html</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> </array> </dict> + <!-- handles all tags --> <key>tag-stuff</key> <dict> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-id-attribute</string> </dict> + <dict> + <key>include</key> + <string>#inline-function-stuff</string> + </dict> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> <dict> <key>include</key> <string>#coldfusion-script</string> </dict> <dict> <key>include</key> <string>#embedded-code</string> </dict> + <dict> <key>match</key> <string>.var\s</string> <key>name</key> <string>variable.other</string> </dict> <dict> <key>begin</key> <string>.&lt;cffunction\sname=('|")1</string> <key>contentName</key> <string>entity.name.function</string> <key>end</key> <string>'|"1</string> <key>name</key> <string>meta.tag.other</string> </dict> - <dict> - <key>begin</key> - <string>[^\#"'][a-zA-Z0-9\.]*.\(</string> - <key>contentName</key> - <string>support.function</string> - <key>end</key> - <string>\)+</string> - <key>name</key> - <string>support.function</string> - <key>patterns</key> - <array> - <dict> - <key>match</key> - <string>("|')[^\.].+("|')</string> - <key>name</key> - <string>string</string> - </dict> - <dict> - <key>match</key> - <string>,</string> - <key>name</key> - <string>meta.tag</string> - </dict> - </array> - </dict> </array> </dict> </dict> <key>scopeName</key> <string>text.html.cfm</string> <key>uuid</key> <string>@SYNTAX_UUID@</string> </dict> </plist>
robrohan/coldfusion.tmbundle
6df89c5954b56b8672a646b6fbfcac8ab891081a
Adding in code completion (prett rough right now, but works mildly well.)
diff --git a/ColdFusion.bun/.DS_Store b/ColdFusion.bun/.DS_Store index 4f00c0d..6e9e6d8 100644 Binary files a/ColdFusion.bun/.DS_Store and b/ColdFusion.bun/.DS_Store differ diff --git a/ColdFusion.bun/Commands/CodeCompletion Attributes.tmCommand b/ColdFusion.bun/Commands/CodeCompletion Attributes.tmCommand new file mode 100644 index 0000000..1b04e9c --- /dev/null +++ b/ColdFusion.bun/Commands/CodeCompletion Attributes.tmCommand @@ -0,0 +1,38 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>beforeRunningCommand</key> + <string>nop</string> + + <key>bundleUUID</key> + <string>@BUNDLE_UUID@</string> + + <key>command</key> + <string>#!/usr/bin/env ruby +require &quot;#{ENV[&apos;TM_SUPPORT_PATH&apos;]}/lib/codecompletion&quot; +TextmateCodeCompletion.go!</string> + + <key>fallbackInput</key> + <string>line</string> + + <key>input</key> + <string>selection</string> + + <key>keyEquivalent</key> + <string>^ </string> + + <key>name</key> + <string>CodeCompletion Attributes</string> + + <key>output</key> + <string>insertAsSnippet</string> + + <key>scope</key> + <!-- text.html.cfml meta.tag --> + <string>text.html punctuation.definition.tag -source, text.html meta.tag -entity.other.attribute-name -source</string> + + <key>uuid</key> + <string>@ATTRCOMPLETE_UUID@</string> +</dict> +</plist> diff --git a/ColdFusion.bun/Commands/CodeCompletion Tags.tmCommand b/ColdFusion.bun/Commands/CodeCompletion Tags.tmCommand new file mode 100644 index 0000000..6d25c19 --- /dev/null +++ b/ColdFusion.bun/Commands/CodeCompletion Tags.tmCommand @@ -0,0 +1,39 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>beforeRunningCommand</key> + <string>nop</string> + + <key>bundleUUID</key> + <string>@BUNDLE_UUID@</string> + + <key>command</key> + <string>#!/usr/bin/env ruby +require &quot;#{ENV[&apos;TM_SUPPORT_PATH&apos;]}/lib/codecompletion&quot; +TextmateCodeCompletion.go! +</string> + + <key>fallbackInput</key> + <string>line</string> + + <key>input</key> + <string>selection</string> + + <key>keyEquivalent</key> + <string>^ </string> + + <key>name</key> + <string>CodeCompletion Tags</string> + + <key>output</key> + <string>insertAsSnippet</string> + + <key>scope</key> + <!-- text.html.cfml invalid.illegal.incomplete.html --> + <string>text.html -entity.other.attribute-name -string.quoted, invalid.illegal.incomplete.html</string> + + <key>uuid</key> + <string>@TAGCOMPLETE_UUID@</string> +</dict> +</plist> diff --git a/ColdFusion.bun/info.plist b/ColdFusion.bun/info.plist deleted file mode 100644 index 1c9390e..0000000 --- a/ColdFusion.bun/info.plist +++ /dev/null @@ -1,71 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - NOTE: This file is here for reference only. The real plist file is generated by the dictToBundle.xsl file (in order for the UUIDs to work properly). If you want your changes to show up in the generated bundle, edit that file. ---> -<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> -<plist version="1.0"> -<dict> - <key>contactEmailRot13</key> - <string>[email protected]</string> - - <key>contactName</key> - <string>Rob Rohan</string> - - <key>description</key> - <string>Support for the ColdFusion web development environment.</string> - - <key>mainMenu</key> - <dict> - <key>items</key> - <array> - <!-- <string>C8F9D7A6-D447-4C16-B566-BE46335B1067</string> - <string>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</string> --> - <string>------------------------------------</string> - <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> - <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> - <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> - <string>------------------------------------</string> - <string>@CMDDOC_UUID@</string> - </array> - - - <key>submenus</key> - <dict> - <key>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</key> - <dict> - <key>items</key> - <array> - <string>0AF4E3E4-8638-4EAD-B182-A4FE571E9974</string> - <string>38EB1CC2-4A1A-4C37-9D69-19D81129C5DC</string> - <!-- etc, etc all the uuids for functions --> - </array> - <key>name</key> - <string>ColdFusion Functions</string> - </dict> - <key>C8F9D7A6-D447-4C16-B566-BE46335B1067</key> - <dict> - <key>items</key> - <array> - <string>97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14</string> - <string>862EDD04-D606-4EDB-8D01-425D8024CF1B</string> - <!-- etc, etc all the uuids for tags --> - </array> - <key>name</key> - <string>ColdFusion Tags</string> - </dict> - </dict> - </dict> - - <key>name</key> - <string>ColdFusion</string> - - <key>ordering</key> - <array> - <!-- <string>00D00AD7-3C05-46E0-B8B9-0F5CCAC04F57</string> - <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> --> - </array> - - <key>uuid</key> - <string>1A09BE0B-E81A-4CB7-AF69-AFC845162D1F</string> -</dict> -</plist> diff --git a/build.xml b/build.xml index d69d518..c01307f 100644 --- a/build.xml +++ b/build.xml @@ -1,65 +1,74 @@ <project name="ColdFusion Textmate Bundle"> <!-- The xslt process needs an XSLT 2.0 processor, so I am using Saxon--> <property name="saxon.path" value="/Applications/saxonb9-0-0-4j/saxon9.jar" /> <!-- Probably wont need to change this unless you are going to try to use a different cfeclipse dictionary file. --> <property name="dictionary.file" value="Resources/cfml.xml" /> <property name="output.name" value="ColdFusion" /> <property name="output.bundle" value="${output.name}.tmbundle" /> <property name="bundle.uuid" value="1A09BE0B-E81A-4CB7-AF69-AFC845162D1F" /> <property name="snytax.uuid" value="97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14" /> <property name="cmddoc.uuid" value="9902B0A3-0523-4190-B541-374AC09CC72F" /> + <property name="tagcomplete.uuid" value="A51C20E9-244A-4E9B-8150-B3D55F6CA839" /> + <property name="attcomplete.uuid" value="C6F3F140-863E-442D-8ECA-830C4002884E" /> <property name="xsl.file" value="dictToBundle.xsl" /> <property name="doc.xsl.file" value="dictToAPI.xsl" /> <property name="base.bundle" value="ColdFusion.bun" /> <target name="clean"> <delete dir="build/${output.bundle}" /> </target> <target name="superclean"> <delete dir="build" /> </target> <target name="createSnippets"> <java jar="${saxon.path}" fork="true"> <arg value="-o:build/${output.bundle}/info.plist" /> <arg value="${dictionary.file}" /> <arg value="${xsl.file}" /> <arg value="bundle-uuid=${bundle.uuid}" /> <arg value="bundle-name=${output.name}" /> + + <arg value="syntax-uuid=${snytax.uuid}" /> + <arg value="cmddoc-uuid=${cmddoc.uuid}" /> + <arg value="tagcomplete-uuid=${tagcomplete.uuid}" /> + <arg value="attcomplete-uuid=${attcomplete.uuid}" /> </java> </target> <target name="createAPIDoc"> <java jar="${saxon.path}" fork="true"> <arg value="-o:doc/${output.name}.html" /> <arg value="${dictionary.file}" /> <arg value="${doc.xsl.file}" /> <!-- <arg value="bundle-uuid=${bundle.uuid}" /> <arg value="bundle-name=${output.name}" /> --> </java> </target> <target name="createBundle"> <copy todir="build/${output.bundle}"> <fileset dir="${base.bundle}"/> <filterset> <filter token="BUNDLE_NAME" value="${output.name}"/> <filter token="BUNDLE_UUID" value="${bundle.uuid}"/> <filter token="SYNTAX_UUID" value="${syntax.uuid}"/> <filter token="CMDDOC_UUID" value="${cmddoc.uuid}"/> + <filter token="TAGCOMPLETE_UUID" value="${tagcomplete.uuid}"/> + <filter token="ATTRCOMPLETE_UUID" value="${attrcomplete.uuid}"/> </filterset> </copy> </target> <target name="build"> <mkdir dir="build" /> <antcall target="createBundle" /> <antcall target="createSnippets" /> <antcall target="createAPIDoc" /> </target> </project> \ No newline at end of file diff --git a/dictToBundle.xsl b/dictToBundle.xsl index 6ca76fb..ee65401 100644 --- a/dictToBundle.xsl +++ b/dictToBundle.xsl @@ -1,278 +1,407 @@ <?xml version="1.0" encoding="UTF-8" ?> <!-- dictToBundle Created by Rob Rohan on 2008-11-22. Copyright (c) 2008-2009 Rob Rohan. All rights reserved. + + The default output from this process is the info.plist file. However, this also + generates the files for the tag completion and for the default snippets. + The snippets wind up in the Snippets directory and the tag and attribute lists wind + up in the Preferences folder. --> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:dic="http://www.cfeclipse.org/version1/dictionary" xmlns:util="java:java.util.UUID" version="2.0" exclude-result-prefixes="xsl dic util"> <xsl:output method="xml" indent="yes" /> <xsl:output method="xml" indent="yes" name="plistxml" exclude-result-prefixes="xsl dic util" /> <!-- <xsl:param name="bundle-dir" select="'ColdFusion.bun'" /> --> - - <!-- The uuid that will be set in the plist file. I think this needs to be unique per bundle --> <xsl:param name="bundle-uuid" select="'1A09BE0B-E81A-4CB7-AF69-AFC845162D1F'" /> <xsl:param name="bundle-name" select="'ColdFusion'" /> + <xsl:param name="syntax-uuid" select="''" /> + <xsl:param name="cmddoc-uuid" select="''" /> + <xsl:param name="tagcomplete-uuid" select="''" /> + <xsl:param name="attcomplete-uuid" select="''" /> + <xsl:variable name="NL"> <xsl:text> </xsl:text> </xsl:variable> <xsl:variable name="TAB"> <xsl:text> </xsl:text> </xsl:variable> + <!-- writes out the plist, and kicks off the snippet writting --> <xsl:template match="/"> <plist version="1.0"> <dict> <key>contactEmailRot13</key> <string>[email protected]</string> <key>contactName</key> <string>Rob Rohan</string> <key>description</key> <string>Support for the ColdFusion web development environment.</string> <key>mainMenu</key> <dict> <key>items</key> <array> <string>C8F9D7A6-D447-4C16-B566-BE46335B1067</string> <string>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</string> <string>------------------------------------</string> <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> + <string><xsl:value-of select="$cmddoc-uuid" /></string> + <string><xsl:value-of select="$tagcomplete-uuid" /></string> + <string><xsl:value-of select="$attcomplete-uuid" /></string> + <!-- Now that we have written out the plist file and the snippets --> + <!-- fire off the bit that does the tag and attribute completion --> + <xsl:call-template name="write-tag-completion-list" /> + <xsl:call-template name="write-attribute-completion-list" /> </array> <key>submenus</key> <dict> <key>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</key> <dict> <key>items</key> <array> <xsl:comment>FUNCTIONS</xsl:comment><xsl:value-of select="$NL" /> <xsl:apply-templates select="/dic:dictionary/dic:functions/dic:function" /> </array> <key>name</key> <string>ColdFusion Functions</string> </dict> <key>C8F9D7A6-D447-4C16-B566-BE46335B1067</key> <dict> <key>items</key> <array> <xsl:comment>TAGS</xsl:comment><xsl:value-of select="$NL" /> <xsl:apply-templates select="/dic:dictionary/dic:tags/dic:tag" /> </array> <key>name</key> <string>ColdFusion Tags</string> </dict> </dict> </dict> <key>name</key> <string><xsl:value-of select="$bundle-name" /></string> <key>ordering</key> <array> <!-- <string>00D00AD7-3C05-46E0-B8B9-0F5CCAC04F57</string> <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> --> </array> <key>uuid</key> <string><xsl:value-of select="$bundle-uuid" /></string> </dict> </plist> </xsl:template> <!-- Formats the functions. Writes the plist too. --> <xsl:template match="dic:function"> <xsl:variable name="filename" select="translate(@name,':','-')" /> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:value-of select="$NL" /> <!-- {$bundle-dir}/ --> <xsl:result-document href="Snippets/gen-{$filename}.tmSnippet" format="plistxml"> <plist version="1.0"> <dict> <key>content</key> <string><xsl:value-of select="@name" /> <xsl:text>(${1:</xsl:text> <xsl:for-each select="./dic:parameter"> <xsl:call-template name="param-with-placement"> <xsl:with-param name="placement" select="position()+1" /> <xsl:with-param name="separator" select="''" /> <xsl:with-param name="preparator" select="', '" /> <xsl:with-param name="use-equals" select="'false'" /> <xsl:with-param name="total-param-count" select="count(../dic:parameter)" /> </xsl:call-template> </xsl:for-each> <xsl:text>})</xsl:text></string> <key>name</key> <string><xsl:value-of select="@name"/></string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string><xsl:value-of select="@name"/></string> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <!-- Formats the tags. Writes out the plist file too --> <xsl:template match="dic:tag"> <xsl:variable name="filename" select="translate(@name,':','-')" /> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:value-of select="$NL" /> <!-- {$bundle-dir}/ --> <xsl:result-document href="Snippets/gen-{$filename}.tmSnippet" format="plistxml"> <plist version="1.0"> <dict> <key>content</key> <string><xsl:text>&lt;</xsl:text> <xsl:value-of select="@name" /> <xsl:text> ${1:</xsl:text> <xsl:for-each select="./dic:parameter"> <xsl:call-template name="param-with-placement"> <xsl:with-param name="placement" select="position()+position()" /> <xsl:with-param name="separator" select="' '" /> <xsl:with-param name="preparator" select="''" /> <xsl:with-param name="use-equals" select="'true'" /> <xsl:with-param name="total-param-count" select="count(../dic:parameter)" /> <!-- <xsl:with-param name="element" select="." /> --> </xsl:call-template> </xsl:for-each> <xsl:text>}</xsl:text> <xsl:choose> <xsl:when test="@single = 'true'"> <xsl:text> /&gt;$0</xsl:text> </xsl:when> <xsl:otherwise> <xsl:text>&gt;</xsl:text> <xsl:value-of select="$NL" /> <xsl:value-of select="$TAB" /> <xsl:text>$0</xsl:text> <xsl:value-of select="$NL" /> - <xsl:text>&lt;</xsl:text> + <xsl:text>&lt;/</xsl:text> <xsl:value-of select="@name" /> <xsl:text>&gt;</xsl:text> </xsl:otherwise> </xsl:choose></string> <key>name</key> <string><xsl:value-of select="@name"/></string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string> <xsl:choose> <xsl:when test="contains(@name,':')"> <xsl:value-of select="substring-before(@name,':')" /> </xsl:when> <xsl:otherwise> <xsl:value-of select="@name" /> </xsl:otherwise> </xsl:choose> </string> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <!-- handles doing the tag and function params. Takes 3 params. placement = where to start the textmate $N variables from separator = what to tack on to the end of each paramenter total-param-count = total number of params, so we don't add the separator to the last item. --> <xsl:template name="param-with-placement"> <xsl:param name="placement" /> <xsl:param name="separator" /> <xsl:param name="preparator" /> <xsl:param name="use-equals" /> <xsl:param name="total-param-count" /> <xsl:choose> <xsl:when test="$use-equals = 'true'"> <xsl:text>$</xsl:text> <xsl:text>{</xsl:text> <xsl:value-of select="$placement" /> <xsl:text>:</xsl:text> <xsl:value-of select="$preparator" /> <xsl:value-of select="@name" /><xsl:text>="$</xsl:text> <xsl:value-of select="$placement+1" /> <xsl:text>"</xsl:text> <xsl:if test="position() != $total-param-count"> <xsl:value-of select="$separator" /> </xsl:if> <xsl:text>}</xsl:text> </xsl:when> <xsl:otherwise> <xsl:if test="@required = 'true'"> <xsl:if test="position() != 1"> <xsl:value-of select="$preparator" /> </xsl:if> <xsl:if test="@type = 'String'"> <xsl:text>"</xsl:text> </xsl:if> </xsl:if> <xsl:text>${</xsl:text> <xsl:value-of select="$placement" /> <xsl:text>:</xsl:text> <xsl:if test="@required = 'false'"> <xsl:if test="position() != 1"> <xsl:value-of select="$preparator" /> </xsl:if> </xsl:if> <xsl:if test="@required = 'false'"><xsl:text>[</xsl:text></xsl:if> <xsl:value-of select="@name" /> <xsl:if test="@required = 'false'"><xsl:text>]</xsl:text></xsl:if> <xsl:text>}</xsl:text> <xsl:if test="@required = 'true'"> <xsl:if test="@type = 'String'"> <xsl:text>"</xsl:text> </xsl:if> </xsl:if> </xsl:otherwise> </xsl:choose> </xsl:template> + <!-- make a list of tags in the format textmate expects for code completion --> + <xsl:template name="write-tag-completion-list"> + <xsl:variable name="uid" select="util:randomUUID()"/> + <string><xsl:value-of select="util:toString($uid)"/></string> + + <xsl:result-document + href="Preferences/Completion%20Tags.tmPreferences" format="plistxml"> + <plist version="1.0"> + <dict> + <key>name</key> + <string>Completions Tags</string> + + <key>scope</key> + <!-- text.html.cfm, invalid.illegal.incomplete.html --> + <string>text.html -(meta.tag | source), invalid.illegal.incomplete.html -source</string> + + <key>settings</key> + <dict> + <key>shellVariables</key> + <array> + <dict> + <key>name</key> + <string>TM_COMPLETION_split</string> + <key>value</key> + <string>,</string> + </dict> + + <dict> + <key>name</key> + <string>TM_COMPLETIONS</string> + <key>value</key> + <string> + <xsl:for-each select="//dic:tag"> + <xsl:value-of select="./@name" /><xsl:text>,</xsl:text> + </xsl:for-each> + </string> + </dict> + </array> + </dict> + + <key>uuid</key> + <string><xsl:value-of select="util:toString($uid)"/></string> + <!-- <string><xsl:value-of select="$tagcomplete-uuid" /></string> --> + </dict> + </plist> + </xsl:result-document> + </xsl:template> + + <xsl:template name="write-attribute-completion-list"> + <xsl:variable name="uid" select="util:randomUUID()"/> + <string><xsl:value-of select="util:toString($uid)"/></string> + + <xsl:result-document + href="Preferences/Completion%20Attributes.tmPreferences" format="plistxml"> + <plist version="1.0"> + <dict> + <key>name</key> + <string>Completions Attributes</string> + + <key>scope</key> + <!-- text.html meta.tag -(entity.other.attribute-name | punctuation.definition.tag.begin | source | entity.name.tag | string | invalid.illegal.incomplete.html)--> + <string>text.html.cfm meta.tag.other.html</string> + + <key>settings</key> + <dict> + <key>completions</key> + <array> + <xsl:for-each select="//dic:tag"> + <string><xsl:value-of select="@name" /></string> + <string><xsl:value-of select="translate(@name,'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')" /></string> + </xsl:for-each> + </array> + <key>disableDefaultCompletion</key> + <integer>1</integer> + <key>shellVariables</key> + <array> + <dict> + <key>name</key> + <string>TM_COMPLETION_split</string> + <key>value</key> + <string>,</string> + </dict> + <dict> + <key>name</key> + <string>TM_COMPLETION_scope</string> + <key>value</key> + <string>html_attributes</string> + </dict> + <dict> + <key>name</key> + <string>TM_COMPLETIONS</string> + <key>value</key> + <string> + <xsl:for-each select="//dic:tag/dic:parameter"> + <xsl:text>&lt;</xsl:text> + <xsl:value-of select="../@name" /><xsl:text> </xsl:text> + <xsl:value-of select="./@name" /> + <xsl:text>=&quot;&quot;</xsl:text> + <xsl:text>,</xsl:text> + </xsl:for-each> + </string> + </dict> + </array> + </dict> + + <key>uuid</key> + <string><xsl:value-of select="util:toString($uid)"/></string> + </dict> + </plist> + </xsl:result-document> + </xsl:template> + + <xsl:template match="text()" /> </xsl:stylesheet> \ No newline at end of file
robrohan/coldfusion.tmbundle
eb46d3d712fbce1629a0e7f682a81f3076c1d6eb
Adding in a process to build all the types of coldfusion engines and adding in the lookup tag command for each language
diff --git a/ColdFusion.bun/Commands/Documentation for Tag.plist b/ColdFusion.bun/Commands/Documentation for Tag.plist new file mode 100644 index 0000000..344e229 --- /dev/null +++ b/ColdFusion.bun/Commands/Documentation for Tag.plist @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>beforeRunningCommand</key> + <string>nop</string> + + <key>command</key> + <string>#!/usr/bin/env ruby +line, col = ENV[&quot;TM_CURRENT_LINE&quot;].to_s, ENV[&quot;TM_LINE_INDEX&quot;].to_i +tag = line =~ /\A.{0,#{col}}&lt;\s*([\w:]+)/ ? $1 : ENV[&quot;TM_CURRENT_WORD&quot;].to_s +url = &quot;http://robrohan.com/farcrystuff/@[email protected]#&quot; + tag +puts &quot;&lt;meta http-equiv=&apos;Refresh&apos; content=&apos;0;URL=#{url}&apos;&gt;&quot;</string> + + <key>input</key> + <string>none</string> + + <key>keyEquivalent</key> + <string>^h</string> + + <key>name</key> + <string>Documentation for Tag</string> + + <key>output</key> + <string>showAsHTML</string> + + <key>scope</key> + <string>entity.name.tag.cfml,entity.name.tag.cfquery.html, entity.name.tag.other.html,meta.tag.other.html,text.html.cfm</string> + + <key>uuid</key> + <string>@CMDDOC_UUID@</string> +</dict> +</plist> diff --git a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage index 1abff67..ca0a678 100644 --- a/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage +++ b/ColdFusion.bun/Syntaxes/ColdFusion.tmLanguage @@ -1,817 +1,790 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>bundleUUID</key> - <string>1A09BE0B-E81A-4CB7-AF69-AFC845162D1F</string> + <string>@BUNDLE_UUID@</string> + <key>fileTypes</key> <array> <string>cfm</string> <string>cfml</string> <string>cfc</string> </array> + <key>firstLineMatch</key> <string>&lt;!DOCTYPE|&lt;(?i:html)</string> + <key>foldingStartMarker</key> <string>(?x) (&lt;(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script |ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction)\b.*?&gt; |&lt;!---(?!.*---\s*&gt;) )</string> <key>foldingStopMarker</key> <string>(?x) (&lt;/(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|scrip t|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction)&gt; |^(?!.*?&lt;!---).*?---\s*&gt; )</string> + <key>keyEquivalent</key> <string>^~@c</string> + <key>name</key> + <string>@BUNDLE_NAME@</string> - <string>ColdFusion</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>&lt;([a-zA-Z0-9:]+)(?=[^&gt;]*&gt;&lt;/\1&gt;)</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.html</string> </dict> </dict> <key>end</key> <string>&gt;(&lt;)/(\1)&gt;</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>meta.scope.between-tag-pair.html</string> </dict> <key>2</key> <dict> <key>name</key> <string>entity.name.tag.html</string> </dict> </dict> <key>name</key> <string>meta.tag.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;\?(xml)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.xml.html</string> </dict> </dict> <key>end</key> <string>\?&gt;</string> <key>name</key> <string>meta.tag.preprocessor.xml.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;!---</string> <key>end</key> <string>---\s*&gt;</string> <key>name</key> <string>comment.block.html</string> <key>patterns</key> <array> <dict> <key>match</key> <string>---</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;!</string> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.sgml.html</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>(DOCTYPE)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.doctype.html</string> </dict> </dict> <key>end</key> <string>(?=&gt;)</string> <key>name</key> <string>meta.tag.sgml.doctype.html</string> <key>patterns</key> <array> <dict> <key>match</key> <string>"[^"&gt;]*"</string> <key>name</key> <string>string.quoted.double.doctype.identifiers-and-DTDs.html</string> </dict> </array> </dict> <dict> <key>begin</key> <string>\[CDATA\[</string> <key>end</key> <string>]](?=&gt;)</string> <key>name</key> <string>constant.other.inline-data.html</string> </dict> <dict> <key>match</key> <string>(\s*)(?!---|&gt;)\S(\s*)</string> <key>name</key> <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> </array> </dict> <dict> <key>include</key> <string>#coldfusion-script</string> </dict> <dict> <key>include</key> <string>#cffunction</string> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:style))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.style.html</string> </dict> </dict> <key>end</key> <string>&lt;/((?i:style))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.css.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:style))</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>source.css</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfquery))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.cfquery.html</string> </dict> </dict> <key>end</key> <string>&lt;/((?i:cfquery))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.sql.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:cfquery))</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>source.sql</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:script))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(script|SCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:script|SCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:script))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/script)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/script)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfscript))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> <string>(?&lt;=&lt;/(cfscript|CFSCRIPT))&gt;(?:\s*\n)?</string> <key>name</key> <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;!&lt;/(?:cfscript|CFSCRIPT))&gt;</string> <key>end</key> <string>&lt;/((?i:cfscript))</string> <key>patterns</key> <array> <dict> <key>match</key> <string>//.*?((?=&lt;/cfscript)|$\n?)</string> <key>name</key> <string>comment.line.double-slash.js</string> </dict> <dict> <key>begin</key> <string>/\*</string> <key>end</key> <string>\*/|(?=&lt;/cfscript)</string> <key>name</key> <string>comment.block.js</string> </dict> <dict> <key>include</key> <string>source.js</string> </dict> </array> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:body|head|html)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.structure.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.structure.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:address|blockquote|dd|div|dl|dt|fieldset|form|frame|frameset|h1|h2 |h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|menu|pre)\ b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.block.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.block.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite |code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|la bel|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script| select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot |th|thead|title|tr|tt|u|var)\b)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.inline.any.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.inline.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>begin</key> <string>&lt;/?([a-zA-Z0-9:]+)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.other.html</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.other.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <dict> <key>include</key> <string>#entities</string> </dict> <dict> <key>match</key> <string>&lt;&gt;</string> <key>name</key> <string>invalid.illegal.incomplete.html</string> </dict> <dict> <key>match</key> <string>&lt;(?=\W)|&gt;</string> <key>name</key> <string>invalid.illegal.bad-angle-bracket.html</string> </dict> </array> <key>repository</key> <dict> <key>cffunction</key> <dict> <key>begin</key> <string>&lt;(cffunction)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.cfml</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.language.cfml.function</string> <key>patterns</key> <array> - <!-- <dict> - <key>captures</key> - <dict> - <key>0</key> - <dict> - <key>name</key> - <string>string.quoted.double.cfml</string> - </dict> - - <key>1</key> - <dict> - <key>name</key> - <string>punctuation.definition.string.begin</string> - </dict> - - <key>2</key> - <dict> - <key>name</key> - <string>entity.name.function.cfml</string> - </dict> - - <key>3</key> - <dict> - <key>name</key> - <string>punctuation.definition.string.end</string> - </dict> - </dict> - <key>match</key> - <string>(?&lt;=name=)(")([A-Za-z$_0-9]+)(")</string> - </dict> --> - <dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> - <!-- <string>string.quoted.double.cfml</string> --> <string>meta.tag.language.cfml.function</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.string.begin</string> </dict> <key>4</key> <dict> <key>name</key> <string>entity.name.function.cfml</string> </dict> <key>5</key> <dict> <key>name</key> <string>punctuation.definition.string.end</string> </dict> </dict> <key>match</key> <string>\b([nN][aA][mM][Ee])\b\s*(=)\s*(["'])([A-Za-z$_0-9]+)(["'])</string> </dict> <dict> <key>include</key> <string>source.cfml</string> </dict> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <key>coldfusion-script</key> <dict> <key>begin</key> <string>#</string> <key>end</key> <string>\#</string> <key>name</key> <string>source.coldfusion.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> </array> </dict> <key>embedded-code</key> <dict> <key>patterns</key> <array> <dict> <key>include</key> <string>#php</string> </dict> <dict> <key>include</key> <string>#ruby</string> </dict> <dict> <key>include</key> <string>#smarty</string> </dict> <dict> <key>include</key> <string>#python</string> </dict> <dict> <key>include</key> <string>#javascript</string> </dict> </array> </dict> <key>entities</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>&amp;([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);</string> <key>name</key> <string>constant.character.entity.html</string> </dict> <dict> <key>match</key> <string>&amp;</string> <key>name</key> <string>invalid.illegal.bad-ampersand.html</string> </dict> </array> </dict> <key>string-double-quoted</key> <dict> <key>begin</key> <string>"</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <key>string-single-quoted</key> <dict> <key>begin</key> <string>'</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <key>tag-generic-attribute</key> <dict> <key>match</key> <string>\b([a-zA-Z\-:]+)</string> <key>name</key> <string>entity.other.attribute-name.html</string> </dict> <key>tag-id-attribute</key> <dict> <key>begin</key> <string>\b(id)\b\s*=</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.other.attribute-name.id.html</string> </dict> </dict> <key>end</key> <string>(?&lt;='|")</string> <key>name</key> <string>meta.attribute-with-value.id.html</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>"</string> <key>contentName</key> <string>meta.toc-list.id.html</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <dict> <key>begin</key> <string>'</string> <key>contentName</key> <string>meta.toc-list.id.html</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> </array> </dict> <key>tag-stuff</key> <dict> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-id-attribute</string> </dict> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> <dict> <key>include</key> <string>#coldfusion-script</string> </dict> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>match</key> <string>.var\s</string> <key>name</key> <string>variable.other</string> </dict> <dict> <key>begin</key> <string>.&lt;cffunction\sname=('|")1</string> <key>contentName</key> <string>entity.name.function</string> <key>end</key> <string>'|"1</string> <key>name</key> <string>meta.tag.other</string> </dict> <dict> <key>begin</key> <string>[^\#"'][a-zA-Z0-9\.]*.\(</string> <key>contentName</key> <string>support.function</string> <key>end</key> <string>\)+</string> <key>name</key> <string>support.function</string> <key>patterns</key> <array> <dict> <key>match</key> <string>("|')[^\.].+("|')</string> <key>name</key> <string>string</string> </dict> <dict> <key>match</key> <string>,</string> <key>name</key> <string>meta.tag</string> </dict> </array> </dict> </array> </dict> </dict> <key>scopeName</key> <string>text.html.cfm</string> <key>uuid</key> - <string>97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14</string> + <string>@SYNTAX_UUID@</string> </dict> </plist> diff --git a/ColdFusion.bun/info.plist b/ColdFusion.bun/info.plist index 57a0c0c..1c9390e 100644 --- a/ColdFusion.bun/info.plist +++ b/ColdFusion.bun/info.plist @@ -1,69 +1,71 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- NOTE: This file is here for reference only. The real plist file is generated by the dictToBundle.xsl file (in order for the UUIDs to work properly). If you want your changes to show up in the generated bundle, edit that file. --> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>contactEmailRot13</key> <string>[email protected]</string> <key>contactName</key> <string>Rob Rohan</string> <key>description</key> <string>Support for the ColdFusion web development environment.</string> <key>mainMenu</key> <dict> <key>items</key> <array> <!-- <string>C8F9D7A6-D447-4C16-B566-BE46335B1067</string> <string>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</string> --> <string>------------------------------------</string> <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> + <string>------------------------------------</string> + <string>@CMDDOC_UUID@</string> </array> <key>submenus</key> <dict> <key>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</key> <dict> <key>items</key> <array> <string>0AF4E3E4-8638-4EAD-B182-A4FE571E9974</string> <string>38EB1CC2-4A1A-4C37-9D69-19D81129C5DC</string> <!-- etc, etc all the uuids for functions --> </array> <key>name</key> <string>ColdFusion Functions</string> </dict> <key>C8F9D7A6-D447-4C16-B566-BE46335B1067</key> <dict> <key>items</key> <array> <string>97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14</string> <string>862EDD04-D606-4EDB-8D01-425D8024CF1B</string> <!-- etc, etc all the uuids for tags --> </array> <key>name</key> <string>ColdFusion Tags</string> </dict> </dict> </dict> <key>name</key> <string>ColdFusion</string> <key>ordering</key> <array> <!-- <string>00D00AD7-3C05-46E0-B8B9-0F5CCAC04F57</string> <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> --> </array> <key>uuid</key> <string>1A09BE0B-E81A-4CB7-AF69-AFC845162D1F</string> </dict> </plist> diff --git a/Resources/cfml.xml b/Resources/cfml.xml index 8678aa7..55e9641 100644 --- a/Resources/cfml.xml +++ b/Resources/cfml.xml @@ -14220,1097 +14220,1097 @@ --> <function name="listsetat" returns="String"> <help><![CDATA[ Replaces the contents of a list element. ]]></help> <parameter name="list" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="position" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="value" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="delimiters" type="String" required="false"> <help><![CDATA[ ]]></help> <values> <value option="," /> </values> </parameter> </function> <!-- String ListSort(list, sort_type [, sort_order] [, delimiters ]) --> <function name="listsort" returns="String"> <help><![CDATA[ Sorts list elements according to a sort type and sort order. Returns a sorted copy of the list. [sort_type - quicky] numeric: sorts numbers text: sorts text alphabetically, taking case into account - aabzABZ, if sort_order = "asc" - ZBAzbaa, if sort_order = "desc" textnocase: sorts text alphabetically, without regard to case - aAaBbBzzZ, in an asc sort; - ZzzBbBaAa, in a desc sort; ]]></help> <parameter name="list" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="sort_type" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="sort_order" type="String" required="false"> <help><![CDATA[ ]]></help> </parameter> <parameter name="delimiters" type="String" required="false"> <help><![CDATA[ ]]></help> <values> <value option="," /> </values> </parameter> </function> <!-- Array ListToArray(list [, delimiters ]) --> <function name="listtoarray" returns="Array"> <help><![CDATA[ Copies the elements of a list to an array. ]]></help> <parameter name="list" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="delimiters" type="String" required="false"> <help><![CDATA[ ]]></help> <values> <value option="," /> </values> </parameter> </function> <!-- Numeric ListValueCount(list, value [, delimiters ]) --> <function name="listvaluecount" returns="Numeric"> <help><![CDATA[ Counts instances of a specified value in a list. The search is case-sensitive. ]]></help> <parameter name="list" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="value" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="delimiters" type="String" required="false"> <help><![CDATA[ ]]></help> <values> <value option="," /> </values> </parameter> </function> <!-- Numeric ListValueCountNoCase(list, value [, delimiters ]) --> <function name="listvaluecountnocase" returns="Numeric"> <help><![CDATA[ Counts instances of a specified value in a list. The search is case-insensitive. ]]></help> <parameter name="list" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="value" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="delimiters" type="String" required="false"> <help><![CDATA[ ]]></help> <values> <value option="," /> </values> </parameter> </function> <!-- String LJustify(string, length) --> <function name="ljustify" returns="String"> <help><![CDATA[ Left justifies characters in a string of a specified length. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="length" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- Numeric Log(number) --> <function name="log" returns="Numeric"> <help><![CDATA[ Calculates the natural logarithm of a number. Natural logarithms are based on the constant e (2.71828182845904). ]]></help> <parameter name="number" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- Numeric Log10(number) --> <function name="log10" returns="Numeric"> <help><![CDATA[ Calculates the logarithm of number, to base 10. ]]></help> <parameter name="number" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- String LSCurrencyFormat(number [, type ]) --> <function name="lscurrencyformat" returns="String"> <help><![CDATA[ Formats a number in a locale-specific currency format. For countries that use the euro, the result depends on the JVM. [type - quicky] local: the currency format and currency symbol used locally. - With JDK 1.3, the default for Euro Zone: local currency. - With JDK 1.4, the default for Euro Zone: euro. international: the international standard currency format none: the local currency format; no currency symbol ]]></help> <parameter name="number" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="type" type="String" required="false"> <help><![CDATA[ ]]></help> <values> <value option="local" /> <value option="international" /> <value option="none" /> </values> </parameter> </function> <!-- String LSDateFormat(date [, mask ]) --> <function name="lsdateformat" returns="String"> <help><![CDATA[ Formats the date part of a date/time value in a locale-specific format. [mask - quicky] d,dd,ddd,dddd: Day of month / week m,mm,mmm,mmmm: Month; y,yy,yyyy: Year; gg: Period/era string short / medium / long / full ]]></help> <parameter name="date" type="DateTime" required="true"> <help><![CDATA[ ]]></help> <values> <value option="Now()" /> </values> </parameter> <parameter name="mask" type="String" required="false"> <help><![CDATA[ ]]></help> <values> <value option="short" /> <value option="medium" /> <value option="long" /> <value option="full" /> </values> </parameter> </function> <!-- String LSEuroCurrencyFormat(currency-number [, type ]) --> <function name="lseurocurrencyformat" returns="String"> <help><![CDATA[ Formats a number in a locale-specific currency format. [type - quicky] local: the currency format used in the locale. (Default.) international: the international standard currency format none: the currency format used; no currency symbol ]]></help> <parameter name="currency" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="type" type="String" required="true"> <help><![CDATA[ ]]></help> <values> <value option="local" /> <value option="international" /> <value option="none" /> </values> </parameter> </function> <!-- boolean LSIsCurrency(string) --> <function name="lsiscurrency" returns="boolean"> <help><![CDATA[ Determines whether a string is a valid representation of a currency amount in the current locale. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- boolean LSIsDate(string) --> <function name="lsisdate" returns="boolean"> <help><![CDATA[ Determines whether a string is a valid representation of a date/time value in the current locale. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- boolean LSIsNumeric(string) --> <function name="lsisnumeric" returns="boolean"> <help><![CDATA[ Determines whether a string is a valid representation of a number in the current locale. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- String LSNumberFormat(number [, mask ]) --> <function name="lsnumberformat" returns="String"> <help><![CDATA[ Formats a number in a locale-specific format. [mask - quicky] _,9 Digit placeholder; . decimal point; 0 Pads with zeros; ( ) less than zero, puts parentheses around the mask + plus sign before positive number minus before negative - a space before positive minus sign before negative , Separates every third decimal place with a comma. L,C Left-justifies or center-justifies number $ dollar sign before formatted number. ^ Separates left and right formatting. ]]></help> <parameter name="number" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="mask" type="String" required="false"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- String LSParseCurrency(string) --> <function name="lsparsecurrency" returns="String"> <help><![CDATA[ Converts a locale-specific currency string into a formatted number. Attempts conversion by comparing the string with each the three supported currency formats (none, local, international) and using the first that matches. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- DateTime LSParseDateTime(date/time-string) --> <function name="lsparsedatetime" returns="DateTime"> <help><![CDATA[ Converts a string that is a valid date/time representation in the current locale into a date/time object. ]]></help> <parameter name="dt_string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- Numeric LSParseEuroCurrency(currency-string) --> <function name="lsparseeurocurrency" returns="Numeric"> <help><![CDATA[ Formats a locale-specific currency string as a number. Attempts conversion through each of the default currency formats (none, local, international). Ensures correct handling of euro currency for Euro zone countries. ]]></help> <parameter name="currency_string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- Numeric LSParseNumber(string) --> <function name="lsparsenumber" returns="Numeric"> <help><![CDATA[ Converts a string that is a valid numeric representation in the current locale into a formatted number. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- String LSTimeFormat(time [, mask ]) --> <function name="lstimeformat" returns="String"> <help><![CDATA[ Formats the time part of a date/time string into a string in a locale-specific format. [mask - quicky] h,hh,H,HH: Hours; m,mm: Minutes; s,ss: Seconds; l: Milliseconds; t: A or P; tt: AM or PM "short" = h:mm tt; "medium" = h:mm:ss tt ]]></help> <parameter name="time" type="DateTime" required="true"> <help><![CDATA[ ]]></help> <values> <value option="Now()" /> </values> </parameter> <parameter name="mask" type="String" required="false"> <help><![CDATA[ ]]></help> <values> <value option="short" /> <value option="medium" /> <value option="long" /> </values> </parameter> </function> <!-- String LTrim(string) --> <function name="ltrim" returns="String"> <help><![CDATA[ Removes leading spaces from a string. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- Numeric Max(number1, number2) --> <function name="max" returns="Numeric"> <help><![CDATA[ Determines the greater of two numbers. ]]></help> <parameter name="number1" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="number2" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- String Mid(string, start, count) --> <function name="mid" returns="String"> <help><![CDATA[ Extracts a substring from a string. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ The string from which the substring will be extracted. ]]></help> </parameter> <parameter name="start" type="Numeric" required="true"> <help><![CDATA[ The position of the first character to retrieve. ]]></help> </parameter> <parameter name="count" type="Numeric" required="true"> <help><![CDATA[ The number of characters to retrieve. ]]></help> </parameter> </function> <!-- Numeric Min(number1, number2) --> <function name="min" returns="Numeric"> <help><![CDATA[ Determines the lesser of two numbers. ]]></help> <parameter name="number1" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="number2" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- Numeric Minute(date) --> <function name="minute" returns="Numeric"> <help><![CDATA[ Extracts the minute value from a date/time object. ]]></help> <parameter name="date" type="DateTime" required="true"> <help><![CDATA[ ]]></help> <values> <value option="Now()" /> </values> </parameter> </function> <!-- Numeric Month(date) --> - <function name="writeoutput" returns="Numeric"> + <function name="month" returns="Numeric"> <help><![CDATA[ Extracts the month value from a date/time object ]]></help> <parameter name="date" type="DateTime" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- String MonthAsString(month_number) --> <function name="monthasstring" returns="String"> <help><![CDATA[ ]]></help> <parameter name="month_number" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- DateTime Now() --> <function name="now" returns="DateTime"> <help><![CDATA[ Gets the current date and time of the computer running the CFML server. ]]></help> </function> <!-- String NumberFormat(number [, mask ]) --> <function name="numberformat" returns="String"> <help><![CDATA[ Creates a custom-formatted number value. For international number formatting use LSNumberFormat. [mask - quicky] _,9 Digit placeholder; . decimal point; 0 Pads with zeros; ( ) less than zero, puts parentheses around the mask + plus sign before positive number minus before negative - a space before positive minus sign before negative , Separates every third decimal place with a comma. L,C Left-justifies or center-justifies number $ dollar sign before formatted number. ^ Separates left and right formatting. ]]></help> <parameter name="number" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="mask" type="String" required="false"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- Numeric Month(date) --> - <function name="month" returns="Numeric"> + <!-- <function name="month" returns="Numeric"> <help><![CDATA[ Extracts the month value from a date/time object. ]]></help> <parameter name="date" type="DateTime" required="true"> <help><![CDATA[ ]]></help> <values> <value option="Now()" /> </values> </parameter> - </function> + </function> --> <!-- String ParagraphFormat(string) --> <function name="paragraphformat" returns="String"> <help><![CDATA[ Replaces characters in a string: * Single newline characters (CR/LF sequences) with spaces * Double newline characters with HTML paragraph tags (<p>) ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- DateTime ParseDateTime(date/time-string [, pop-conversion ] ) --> <function name="parsedatetime" returns="DateTime"> <help><![CDATA[ Parses a date/time string according to the English (U.S.) locale conventions. (To format a date/time string for other locales, use the LSParseDateTime function.) ]]></help> <parameter name="dt_string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="pop_conversion" type="boolean" required="false"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- Numeric Pi() --> <function name="pi" returns="Numeric"> <help><![CDATA[ Gets the mathematical constant p, accurate to 15 digits. The number 3.14159265358979. ]]></help> </function> <!-- void PreserveSingleQuotes(variable) --> <function name="preservesinglequotes" returns="void"> <help><![CDATA[ Prevents CFML from automatically escaping single quotation mark characters that are contained in a variable. CFML does not evaluate the argument. CFML MX: automatically escapes simple-variable, array-variable, and structure-variable references within a cfquery tag body or block. ]]></help> <parameter name="variable" type="String" required="true"> <help><![CDATA[ Variable that contains a string in which to preserve single quotation marks. ]]></help> </parameter> </function> <!-- Numeric Quarter(date) --> <function name="quarter" returns="Numeric"> <help><![CDATA[ Calculates the quarter of the year in which a date falls. ]]></help> <parameter name="date" type="DateTime" required="true"> <help><![CDATA[ ]]></help> <values> <value option="Now()" /> </values> </parameter> </function> <!-- Numeric QueryAddColumn(query, column-name[, datatype], array-name) --> <function name="queryaddcolumn" returns="Numeric"> <help><![CDATA[ Adds a column to a query and populates its rows with the contents of a one-dimensional array. Pads query columns, if necessary, to ensure that all columns have the same number of rows. ]]></help> <parameter name="query" type="Query" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="column-name" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="datatype" type="String" required="false"> <help><![CDATA[ Column data type. ]]></help> <values> <value option="Integer" /> <value option="BigInt" /> <value option="Double" /> <value option="Decimal" /> <value option="VarChar" /> <value option="Binary" /> <value option="Bit" /> <value option="Time" /> <value option="Data" /> </values> </parameter> <parameter name="array-name" type="Array" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- Numeric QueryAddRow(query [, number ]) --> <function name="queryaddrow" returns="Numeric"> <help><![CDATA[ Adds a specified number of empty rows to a query. ]]></help> <parameter name="query" type="Query" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="number" type="Numeric" required="false"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- Query QueryNew(columnlist [, columntypelist]) --> <function name="querynew" returns="Query"> <help><![CDATA[ Creates an empty query (query object). ]]></help> <parameter name="columnlist" type="String" required="true"> <help><![CDATA[ A string or a variable that contains one. Delimited list of column names, or an empty string. ]]></help> </parameter> <parameter name="columntypelist" type="String" required="false"> <help><![CDATA[ Comma-delimited list specifying column data types. ]]></help> <values> <value option="Integer" /> <value option="BigInt" /> <value option="Double" /> <value option="Decimal" /> <value option="VarChar" /> <value option="Binary" /> <value option="Bit" /> <value option="Time" /> <value option="Data" /> </values> </parameter> </function> <!-- boolean QuerySetCell(query, column_name, value [, row_number ]) --> <function name="querysetcell" returns="boolean"> <help><![CDATA[ Sets a cell to a value. If no row number is specified, the cell on the last row is set. ]]></help> <parameter name="query" type="Query" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="column_name" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="value" type="Object" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="row_number" type="Numeric" required="false"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- String QuotedValueList(query.column [, delimiter ]) --> <function name="quotedvaluelist" returns="String"> <help><![CDATA[ Gets the values of each record returned from an executed query. CFML does not evaluate the arguments ]]></help> <parameter name="column" type="QueryColumn" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="delimiter" type="String" required="false"> <help><![CDATA[ ]]></help> <values> <value option="," /> </values> </parameter> </function> <!-- Numeric Rand([algorithm]) --> <function name="rand" returns="Numeric"> <help><![CDATA[ Generates a pseudo-random number in the range 0 - 1. ]]></help> <parameter name="algorithm" type="String" required="false"> <help><![CDATA[ The algorithm to use to generated the random number. ]]></help> <values> <value option="CFMX_COMPAT" /> <value option="SHA1PRNG" /> <value option="IBMSecureRandom" /> </values> </parameter> </function> <!-- Numeric Randomize(number[, algorithm]) --> <function name="randomize" returns="Numeric"> <help><![CDATA[ Seeds the pseudo-random number generator with an integer number, ensuring repeatable number patterns. ]]></help> <parameter name="number" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="algorithm" type="String" required="false"> <help><![CDATA[ The algorithm to use to generated the random number. ]]></help> <values> <value option="CFMX_COMPAT" /> <value option="SHA1PRNG" /> <value option="IBMSecureRandom" /> </values> </parameter> </function> <!-- Numeric RandRange(number1, number2) --> <function name="randrange" returns="Numeric"> <help><![CDATA[ Generates a random integer between two specified numbers. Requests for random integers that are greater than 100,000,000 result in non-random numbers, to prevent overflow during internal computations. ]]></help> <parameter name="number1" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="number2" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="algorithm" type="String" required="false"> <help><![CDATA[ The algorithm to use to generated the random number. ]]></help> <values> <value option="CFMX_COMPAT" /> <value option="SHA1PRNG" /> <value option="IBMSecureRandom" /> </values> </parameter> </function> <!-- Object REFind(reg_expression, string [, start ][, returnsubexpressions ]) --> <function name="refind" returns="Object"> <help><![CDATA[ ]]></help> <parameter name="reg_expression" type="Regex" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="string" type="String" required="true"> <help><![CDATA[ A string or a variable that contains one. String in which to search. ]]></help> </parameter> <parameter name="start" type="Numeric" required="false"> <help><![CDATA[ ]]></help> <values> <value option="1" /> </values> </parameter> <parameter name="returnsubexpressions" type="boolean" required="false"> <help><![CDATA[ True: if the regular expression is found, the first array element contains the length and position, respectively, of the first match. If the regular expression contains parentheses that group subexpressions, each subsequent array element contains the length and position, respectively, of the first occurrence of each group. If the regular expression is not found, the arrays each contain one element with the value 0. False: the function returns the position in the string where the match begins. Default. ]]></help> </parameter> </function> <!-- Object REFindNoCase(reg_expression, string [, start] [, returnsubexpressions] ) --> <function name="refindnocase" returns="Object"> <help><![CDATA[ Uses a regular expression (RE) to search a string for a pattern, starting from a specified position. The search is case-insensitive. ]]></help> <parameter name="reg_expression" type="Regex" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="string" type="String" required="true"> <help><![CDATA[ A string or a variable that contains one. String in which to search. ]]></help> <values> <value option="1" /> </values> </parameter> <parameter name="start" type="Numeric" required="false"> <help><![CDATA[ ]]></help> </parameter> <parameter name="returnsubexpressions" type="boolean" required="false"> <help><![CDATA[ True: if the regular expression is found, the first array element contains the length and position, respectively, of the first match. If the regular expression contains parentheses that group subexpressions, each subsequent array element contains the length and position, respectively, of the first occurrence of each group. If the regular expression is not found, the arrays each contain one element with the value 0. False: the function returns the position in the string where the match begins. Default. ]]></help> </parameter> </function> <!-- void ReleaseComObject(objectName) --> <function name="releasecomobject" returns="void"> <help><![CDATA[ Releases a COM Object and frees up resources that it used. ]]></help> <parameter name="objectName" type="Object" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- String RemoveChars(string, start, count) --> <function name="removechars" returns="String"> <help><![CDATA[ Removes characters from a string. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="start" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="count" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- String RepeatString(string, count) --> <function name="repeatstring" returns="String"> <help><![CDATA[ Creates a string that contains a specified number of repetitions of the specified string. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="count" type="Numeric" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- String Replace(string, substring1, substring2 [, scope ]) --> <function name="replace" returns="String"> <help><![CDATA[ Replaces occurrences of substring1 in a string with substring2, in a specified scope. The search is case-sensitive. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="substring1" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="substring2" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="scope" type="String" required="false"> <help><![CDATA[ * one: replace the first occurrence (default) * all: replace all occurrences ]]></help> <values> <value option="one" /> <value option="all" /> </values> </parameter> </function> <!-- String ReplaceList(string, list1, list2) --> <function name="replacelist" returns="String"> <help><![CDATA[ Replaces occurrences of the elements from a delimited list in a string with corresponding elements from another delimited list. The search is case-sensitive. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="list1" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="list2" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- String ReplaceNoCase(string, substring1, substring2 [, scope ]) --> <function name="replacenocase" returns="String"> <help><![CDATA[ Replaces occurrences of substring1 with substring2, in the specified scope. The search is case-insensitive. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ A string (or variable that contains one) within which to replace substring ]]></help> </parameter> <parameter name="substring1" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="substring2" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="scope" type="String" required="false"> <help><![CDATA[ * one: Replace the first occurrence (default) * all: Replace all occurrences ]]></help> <values> <value option="one" /> <value option="all" /> </values> </parameter> </function> @@ -15699,1025 +15699,1025 @@ <parameter name="string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="set" type="String" required="true"> <help><![CDATA[ A string or a variable that contains a set of characters. Must contain one or more characters ]]></help> </parameter> </function> <!-- Numeric Sqr(number) --> <function name="sqr" returns="Numeric"> <help><![CDATA[ Calculates the square root of a number. ]]></help> <parameter name="number" type="Numeric" required="true"> <help><![CDATA[ A positive integer or a variable that contains one. Number whose square root to get. ]]></help> </parameter> </function> <!-- String StripCR(string) --> <function name="stripcr" returns="String"> <help><![CDATA[ Deletes return characters from a string. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ A string or a variable that contains one ]]></help> </parameter> </function> <!-- boolean StructAppend(struct1, struct2, overwriteFlag) --> <function name="structappend" returns="boolean"> <help><![CDATA[ Appends one structure to another. CFML MX: Changed behavior: this function can be used on XML objects. ]]></help> <parameter name="struct1" type="Struct" required="true"> <help><![CDATA[ Structure to append. ]]></help> </parameter> <parameter name="struct2" type="Struct" required="true"> <help><![CDATA[ Structure that contains the data to append to struct1 ]]></help> </parameter> <parameter name="overwriteFlag" type="boolean" required="false"> <help><![CDATA[ Yes: values in struct2 overwrite corresponding values in struct1. Default. ]]></help> </parameter> </function> <!-- boolean StructClear(structure) --> <function name="structclear" returns="boolean"> <help><![CDATA[ Removes all data from a structure. ]]></help> <parameter name="structure" type="Struct" required="true"> <help><![CDATA[ Structure to clear ]]></help> </parameter> </function> <!-- Struct StructCopy(structure) --> <function name="structcopy" returns="Struct"> <help><![CDATA[ Copies a structure. Copies top-level keys, values, and arrays in the structure by value; copies nested structures by reference. ]]></help> <parameter name="structure" type="Struct" required="true"> <help><![CDATA[ Structure to copy ]]></help> </parameter> </function> <!-- Numeric StructCount(structure) --> <function name="structcount" returns="Numeric"> <help><![CDATA[ Counts the keys in a structure. ]]></help> <parameter name="structure" type="Struct" required="true"> <help><![CDATA[ Structure to access ]]></help> </parameter> </function> <!-- boolean StructDelete(structure, key [, indicatenotexisting ]) --> <function name="structdelete" returns="boolean"> <help><![CDATA[ Removes an element from a structure. ]]></help> <parameter name="structure" type="String" required="true"> <help><![CDATA[ Structure or a variable that contains one. Contains element to remove ]]></help> </parameter> <parameter name="key" type="String" required="true"> <help><![CDATA[ Element to remove ]]></help> </parameter> <parameter name="indicatenotexisting" type="boolean" required="false"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- Object StructFind(structure, key) --> <function name="structfind" returns="Object"> <help><![CDATA[ Determines the value associated with a key in a structure. ]]></help> <parameter name="structure" type="Struct" required="true"> <help><![CDATA[ Structure that contains the value to return ]]></help> </parameter> <parameter name="key" type="String" required="true"> <help><![CDATA[ Key whose value to return ]]></help> </parameter> </function> <!-- Array StructFindKey(top, value, scope) --> <function name="structfindkey" returns="Array"> <help><![CDATA[ Searches recursively through a substructure of nested arrays, structures, and other elements, for structures whose values match the search key in the value parameter. ]]></help> <parameter name="top" type="Object" required="true"> <help><![CDATA[ CFML object (structure or array) from which to start search. This attribute requires an object, not a name of an object. ]]></help> </parameter> <parameter name="value" type="String" required="true"> <help><![CDATA[ String or a variable that contains one for which to search. ]]></help> </parameter> <parameter name="scope" type="String" required="true"> <help><![CDATA[ * one: returns one matching key. Default. * all: returns all matching keys ]]></help> <values> <value option="one" /> <value option="all" /> </values> </parameter> </function> <!-- Array StructFindValue( top, value [, scope]) --> <function name="structfindvalue" returns="Array"> <help><![CDATA[ Searches recursively through a substructure of nested arrays, structures, and other elements for structures with values that match the search key in the value parameter. ]]></help> <parameter name="top" type="Object" required="true"> <help><![CDATA[ CFML object (a structure or an array) from which to start search. This attribute requires an object, not a name of an object. ]]></help> </parameter> <parameter name="value" type="String" required="true"> <help><![CDATA[ String or a variable that contains one for which to search. The type must be a simple object. Arrays and structures are not supported. ]]></help> </parameter> <parameter name="scop" type="String" required="false"> <help><![CDATA[ one: function returns one matching key (default) all: function returns all matching keys ]]></help> <values> <value option="one" /> <value option="all" /> </values> </parameter> </function> <!-- Struct StructGet(pathDesired) --> <function name="structget" returns="Struct"> <help><![CDATA[ Gets a structure(s) from a specified path. ]]></help> <parameter name="pathdesired" type="String" required="true"> <help><![CDATA[ Pathname of variable that contains structure or array from which CFML retrieves structure ]]></help> </parameter> </function> <!-- boolean StructInsert(structure, key, value [, allowoverwrite ]) --> <function name="structinsert" returns="boolean"> <help><![CDATA[ Inserts a key-value pair into a structure. ]]></help> <parameter name="structure" type="Struct" required="true"> <help><![CDATA[ Structure to contain the new key-value pair. ]]></help> </parameter> <parameter name="key" type="String" required="true"> <help><![CDATA[ Key that contains the inserted value. ]]></help> </parameter> <parameter name="value" type="Object" required="true"> <help><![CDATA[ Value to add. ]]></help> </parameter> <parameter name="allowoverwrite" type="boolean" required="false"> <help><![CDATA[ Whether to allow overwriting a key. Default: False. ]]></help> </parameter> </function> <!-- boolean StructIsEmpty(structure) --> <function name="structisempty" returns="boolean"> <help><![CDATA[ Determines whether a structure contains data. ]]></help> <parameter name="structure" type="Struct" required="true"> <help><![CDATA[ Structure to test ]]></help> </parameter> </function> <!-- Array StructKeyArray(structure) --> <function name="structkeyarray" returns="Array"> <help><![CDATA[ Finds the keys in a CFML structure. An array of keys; if structure does not exist, CFML throws an exception. ]]></help> <parameter name="structure" type="Struct" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- boolean StructKeyExists(structure, "key") --> <function name="structkeyexists" returns="boolean"> <help><![CDATA[ Determines whether a specific key is present in a structure. ]]></help> <parameter name="structure" type="Struct" required="true"> <help><![CDATA[ Name of structure to test ]]></help> </parameter> <parameter name="key" type="String" required="true"> <help><![CDATA[ Key to test ]]></help> </parameter> </function> <!-- String StructKeyList(structure [, delimiter]) --> <function name="structkeylist" returns="String"> <help><![CDATA[ Extracts keys from a CFML structure. ]]></help> <parameter name="structure" type="Struct" required="true"> <help><![CDATA[ Structure from which to extract a list of keys ]]></help> </parameter> <parameter name="delimiter" type="String" required="false"> <help><![CDATA[ Character that separates keys in list. Default: comma. ]]></help> <values> <value option="," /> </values> </parameter> </function> <!-- Struct StructNew() --> <function name="structnew" returns="Struct"> <help><![CDATA[ Creates a structure. ]]></help> </function> <!-- Array StructSort(base, sortType, sortOrder, pathToSubElement) --> <function name="structsort" returns="Array"> <help><![CDATA[ Returns a sorted array of the top level keys in a structure. Sorts using alphabetic or numeric sorting, and can sort based on the values of any structure element. ]]></help> <parameter name="base" type="Struct" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="sorttype" type="String" required="true"> <help><![CDATA[ * numeric * text: case sensitive Default. * textnocase ]]></help> <values> <value option="numeric" /> <value option="text" /> <value option="textnocase" /> </values> </parameter> <parameter name="sortorder" type="String" required="true"> <help><![CDATA[ * asc: ascending (a to z) sort order. Default. * desc: descending (z to a) sort order ]]></help> </parameter> <parameter name="pathtosubelement" type="String" required="true"> <help><![CDATA[ String or a variable that contains one ]]></help> </parameter> </function> <!-- boolean StructUpdate(structure, key, value) --> <function name="structupdate" returns="boolean"> <help><![CDATA[ Updates a key with a value. ]]></help> <parameter name="structure" type="Struct" required="true"> <help><![CDATA[ Structure to update ]]></help> </parameter> <parameter name="key" type="String" required="true"> <help><![CDATA[ Key, the value of which to update ]]></help> </parameter> <parameter name="value" type="Object" required="true"> <help><![CDATA[ New value ]]></help> </parameter> </function> <!-- Numeric Tan(number) --> <function name="tan" returns="Numeric"> <help><![CDATA[ Calculates the tangent of an angle that is entered in radians. ]]></help> <parameter name="number" type="Numeric" required="true"> <help><![CDATA[ Angle, in radians, for which to calculate the tangent ]]></help> </parameter> </function> <!-- String TimeFormat(time [, mask ]) --> <function name="timeformat" returns="String"> <help><![CDATA[ Formats a time value using US English time formatting conventions. If no mask is specified, returns a time value using the hh:mm tt format. For international time formatting, see LSTimeFormat. [mask] h,hh,H,HH: Hours; m,mm: Minutes; s,ss: Seconds; l: Milliseconds; t: A or P; tt: AM or PM "short" = h:mm tt; "medium" = h:mm:ss tt ]]></help> <parameter name="time" type="DateTime" required="true"> <help><![CDATA[ A date/time value or string to convert ]]></help> <values> <value option="Now()" /> </values> </parameter> <parameter name="mask" type="String" required="false"> <help><![CDATA[ Masking characters that determine the format ]]></help> <values> <value option="short" /> <value option="medium" /> <value option="long" /> <value option="full" /> </values> </parameter> </function> <!-- String ToBase64(string_or_object[, encoding]) --> <function name="tobase64" returns="String"> <help><![CDATA[ Calculates the Base64 representation of a string or binary object. The Base64 format uses printable characters, allowing binary data to be sent in forms and e-mail, and stored in a database or file. ]]></help> <parameter name="string_or_object" type="Object" required="true"> <help><![CDATA[ A string, the name of a string, or a binary object. ]]></help> </parameter> <parameter name="encoding" type="String" required="false"> <help><![CDATA[ For a string, defines how characters are represented in a byte array. ]]></help> <values> <value option="utf-8" /> <value option="iso-8859-1" /> <value option="windows-1252" /> <value option="us-ascii" /> <value option="shift_jis" /> <value option="iso-2022-jp" /> <value option="euc-jp" /> <value option="euc-kr" /> <value option="big5" /> <value option="euc-cn" /> <value option="utf-16" /> </values> </parameter> </function> <!-- Binary ToBinary(string_in_Base64 or binary_value) --> <function name="tobinary" returns="Binary"> <help><![CDATA[ Calculates the binary representation of Base64-encoded data. ]]></help> <parameter name="base64_or_object" type="Object" required="true"> <help><![CDATA[ A string or a variable that contains one: * In Base64 format to convert to binary * In binary format to test whether it is valid ]]></help> </parameter> </function> <!-- Binary ToScript(cfvar, javascriptvar, outputformat, ASFormat) --> - <function creator="1" name="tobinary" returns="Binary"> + <function creator="1" name="toscript" returns="Binary"> <help><![CDATA[ Creates a JavaScript or ActionScript expression that assigns the value of a ColdFusion variable to a JavaScript or ActionScript variable. This function can convert ColdFusion strings, numbers, arrays, structures, and queries to JavaScript or ActionScript syntax that defines equivalent variables and values. ]]></help> <parameter name="cfvar" type="Object" required="true"> <help><![CDATA[ A ColdFusion variable. This can contain one of the following: String, Number, Array, Structure or Query. ]]></help> </parameter> <parameter name="javascriptvar" type="String" required="true"> <help><![CDATA[ A string that specifies the name of the JavaScript variable that the ToScript function creates. ]]></help> </parameter> <parameter name="outputformat" type="boolean" required="false"> <help><![CDATA[ A Boolean value that determines whether to create WDDX (JavaScript) or ActionScript style output for structures and queries. Default: true ]]></help> <values> <value option="true" /> <value option="false" /> </values> </parameter> <parameter name="ASFormat" type="boolean" required="false"> <help><![CDATA[ A Boolean value that specifies whether to use ActionScript shortcuts in the script. Default: false ]]></help> <values> <value option="true" /> <value option="false" /> </values> </parameter> </function> <!-- String ToString(any_value[, encoding]) --> <function name="tostring" returns="String"> <help><![CDATA[ Converts a value to a string. ]]></help> <parameter name="any_value" type="Object" required="true"> <help><![CDATA[ Value to convert to a string ]]></help> </parameter> <parameter name="encoding" type="String" required="false"> <help><![CDATA[ The character encoding (character set) of the string. ]]></help> <values> <value option="utf-8" /> <value option="iso-8859-1" /> <value option="windows-1252" /> <value option="us-ascii" /> <value option="shift_jis" /> <value option="iso-2022-jp" /> <value option="euc-jp" /> <value option="euc-kr" /> <value option="big5" /> <value option="euc-cn" /> <value option="utf-16" /> </values> </parameter> </function> <!-- String Trim(string) --> <function name="trim" returns="String"> <help><![CDATA[ Removes leading and trailing spaces from a string. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ A string or a variable that contains one ]]></help> </parameter> </function> <!-- String UCase(string) --> <function name="ucase" returns="String"> <help><![CDATA[ Converts the alphabetic characters in a string to uppercase. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ A string or a variable that contains one ]]></help> </parameter> </function> <!-- String URLDecode(urlEncodedString[, charset]) --> <function name="urldecode" returns="String"> <help><![CDATA[ Decodes a URL-encoded string. ]]></help> <parameter name="urlencodedstring" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> <parameter name="charset" type="String" required="false"> <help><![CDATA[ The character encoding in which the string is encoded. ]]></help> <values> <value option="utf-8" /> <value option="iso-8859-1" /> <value option="windows-1252" /> <value option="us-ascii" /> <value option="shift_jis" /> <value option="iso-2022-jp" /> <value option="euc-jp" /> <value option="euc-kr" /> <value option="big5" /> <value option="euc-cn" /> <value option="utf-16" /> </values> </parameter> </function> <!-- String URLEncodedFormat(string [, charset ]) --> <function name="urlencodedformat" returns="String"> <help><![CDATA[ Generates a URL-encoded string. For example, it replaces spaces with %20, and non-alphanumeric characters with equivalent hexadecimal escape sequences. Passes arbitrary strings within a URL. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ A string or a variable that contains one ]]></help> </parameter> <parameter name="charset" type="String" required="false"> <help><![CDATA[ The character encoding in which the string is encoded. ]]></help> <values> <value option="utf-8" /> <value option="iso-8859-1" /> <value option="windows-1252" /> <value option="us-ascii" /> <value option="shift_jis" /> <value option="iso-2022-jp" /> <value option="euc-jp" /> <value option="euc-kr" /> <value option="big5" /> <value option="euc-cn" /> <value option="utf-16" /> </values> </parameter> </function> <!-- URL URLSessionFormat(request_URL) --> <function name="urlsessionformat" returns="URL"> <help><![CDATA[ Depending on whether a client computer accepts cookies, this function does the following: * If the client does not accept cookies: automatically appends all required client identification information to a URL * If the client accepts cookies: does not append information ]]></help> <parameter name="requesturl" type="URL" required="true"> <help><![CDATA[ URL of a CFML page ]]></help> <values> <value option="cgi.script_name" /> </values> </parameter> </function> <!-- Numeric Val(string) --> <function name="val" returns="Numeric"> <help><![CDATA[ Converts numeric characters that occur at the beginning of a string to a number. If conversion fails, returns zero. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ A string or a variable that contains one ]]></help> </parameter> </function> <!-- String ValueList(query.column [, delimiter ]) --> <function name="valuelist" returns="String"> <help><![CDATA[ Inserts a delimiter between each value in an executed query. CFML does not evaluate the arguments. A delimited list of the values of each record returned from an executed query ]]></help> <parameter name="column" type="QueryColumn" required="true"> <help><![CDATA[ Name of an executed query and column. Separate query name and column name with a period. ]]></help> </parameter> <parameter name="delimiter" type="String" required="false"> <help><![CDATA[ A delimiter character to separate column data items. Default: comma (,). ]]></help> <values> <value option="," /> </values> </parameter> </function> <!-- Numeric Week(date) --> <function name="week" returns="Numeric"> <help><![CDATA[ From a date/time object, determines the week number within the year. An integer in the range 1-53; the ordinal of the week, within the year. ]]></help> <parameter name="date" type="DateTime" required="true"> <help><![CDATA[ A date/time object in the range 100 AD-9999 AD. ]]></help> <values> <value option="Now()" /> </values> </parameter> </function> <!-- String Wrap(string, limit[, strip]) --> <function name="wrap" returns="String"> <help><![CDATA[ Wraps text so that each line has a specified maximum number of characters. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ String or variable that contains one. The text to wrap. ]]></help> </parameter> <parameter name="limit" type="Numeric" required="true"> <help><![CDATA[ Positive integer maximum number of characters to allow on a line. ]]></help> </parameter> <parameter name="strip" type="boolean" required="false"> <help><![CDATA[ whether to remove all existing newline and carriage return characters in the input string with spaces before wrapping the text. Default: False. ]]></help> </parameter> </function> <!-- String WriteOutput(string) --> <function name="writeoutput" returns="String"> <help><![CDATA[ Appends text to the page-output stream. This function writes to the page-output stream regardless of conditions established by the cfsetting tag. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ A string, or a variable that contains one ]]></help> </parameter> </function> <!-- Numeric XmlChildPos(elem, childName, N) --> <function name="xmlchildpos" returns="Numeric"> <help><![CDATA[ Gets the position of a child element within an XML document object. The position, in an XmlChildren array, of the Nth child that has the specified name. ]]></help> <parameter name="elem" type="Node" required="true"> <help><![CDATA[ XML element within which to search ]]></help> </parameter> <parameter name="childname" type="String" required="true"> <help><![CDATA[ XML child element for which to search ]]></help> </parameter> <parameter name="n" type="Numeric" required="true"> <help><![CDATA[ Index of XMLchild element for which to search ]]></help> </parameter> </function> <!-- Object XmlElemNew(xmlObj[, namespace], childName) --> <function name="xmlelemnew" returns="Object"> <help><![CDATA[ Creates an XML document object element ]]></help> <parameter name="xmlobj" type="Object" required="true"> <help><![CDATA[ The name of an XML object. An XML document or an element. ]]></help> </parameter> <parameter name="namespace" type="String" required="false"> <help><![CDATA[ URI of the namespace to which this element belongs. ]]></help> </parameter> <parameter name="childname" type="String" required="true"> <help><![CDATA[ The name of the element to create. This element becomes a child element of xmlObj in the tree. ]]></help> </parameter> </function> <!-- String XmlFormat(string) --> <function name="xmlformat" returns="String"> <help><![CDATA[ Escapes special XML characters in a string, so that the string is safe to use with XML. ]]></help> <parameter name="string" type="String" required="true"> <help><![CDATA[ ]]></help> </parameter> </function> <!-- String XmlGetNodeType(xmlNode) --> <function creator="1" name="xmlgetnodetype" returns="String"> <help><![CDATA[ Determines the type of an XML document object node. ]]></help> <parameter name="xmlNode" type="Object" required="true"> <help><![CDATA[ An XML DOM object node. ]]></help> </parameter> </function> <!-- Object XmlNew([caseSensitive]) --> <function name="xmlnew" returns="Object"> <help><![CDATA[ Creates an XML document object. ]]></help> <parameter name="casesensitive" type="boolean" required="false"> <help><![CDATA[ Determines how CFML processes the case of XML document object component identifiers ]]></help> </parameter> </function> <!-- Object XmlParse(xmlText [[, caseSensitive ], validator]) --> <function name="xmlparse" returns="Object"> <help><![CDATA[ Converts an XML document that is represented as a string variable into an XML document object. ]]></help> <parameter name="xmlstring" type="String" required="true"> <help><![CDATA[ Any of the following: - A string containing XML text. - The name of an XML file. - The URL of an XML file; valid protocol identifiers include http, https, ftp, and file. ]]></help> </parameter> <parameter name="casesensitive" type="boolean" required="false"> <help><![CDATA[ Maintains the case of document elements and attributes. Default: false ]]></help> <values> <value option="true" /> <value option="false" /> </values> </parameter> <parameter name="validator" type="String" required="false"> <help><![CDATA[ Any of the following: - The name of a Document Type Definition (DTD) or XML Schema file. - The URL of a DTD or Schema file; valid protocol identifiers include http, https, ftp, and file. - A string representation of a DTD or Schema. - An empty string; in this case, the XML file must contain an embedded DTD or Schema identifier, which is used to validate the document. ]]></help> </parameter> </function> <!-- Array XmlSearch(xmlDoc, xPathString) --> <function name="xmlsearch" returns="Array"> <help><![CDATA[ ]]></help> <parameter name="xmldoc" type="Object" required="true"> <help><![CDATA[ XML document object ]]></help> </parameter> <parameter name="xpathstring" type="String" required="true"> <help><![CDATA[ XPath expression ]]></help> </parameter> </function> <!-- String XmlTransform(xml, xsl[, parameters]) --> <function name="xmltransform" returns="String"> <help><![CDATA[ Applies an Extensible Stylesheet Language Transformation (XSLT) to an XML document object that is represented as a string variable. An XSLT converts an XML document to another format or representation by applying an Extensible Stylesheet Language (XSL) stylesheet to it. ]]></help> <parameter name="xml" type="String" required="true"> <help><![CDATA[ An XML document in string format, or an XML document object. ]]></help> </parameter> <parameter name="xsl" type="String" required="true"> <help><![CDATA[ XSLT transformation to apply; can be any of the following: - A string containing XSL text. - The name of an XSTLT file. Relative paths start at the directory containing the current CFML page. - The URL of an XSLT file; valid protocol identifiers include http, https, ftp, and file. Relative paths start at the directory containing the current CFML page. ]]></help> </parameter> <parameter name="parameters" type="Struct" required="false"> <help><![CDATA[ A structure containing XSL template parameter name-value pairs to use in transforming the document. The XSL transform defined in the xslString parameter uses these parameter values in processing the xml. ]]></help> </parameter> </function> <!-- Struct XmlValidate(xmlDoc[, validator]) --> <function creator="1" name="xmlvalidate" returns="Struct"> <help><![CDATA[ Uses a Document Type Definition (DTD) or XML Schema to validate an XML text document or an XML document object. ]]></help> <parameter name="xmlDoc" type="Object" required="true"> <help><![CDATA[ Any of the following: - A string containing an XML document. - The name of an XML file. - The URL of an XML file; valid protocol identifiers include http, https, ftp, and file. - An XML document object, such as one generated by the XmlParse function. ]]></help> </parameter> <parameter name="validator" type="String" required="false"> <help><![CDATA[ Any of the following: - A string containing a DTD or Schema. - The name of a DTD or Schema file. - The URL of a DTD or Schema file; valid protocol identifiers include http, https, ftp, and file. diff --git a/Resources/cfmlBD621.xml b/Resources/cfmlBD621.xml index 2c5847b..0fc5fe4 100644 --- a/Resources/cfmlBD621.xml +++ b/Resources/cfmlBD621.xml @@ -1,1012 +1,1012 @@ <?xml version="1.0"?> <!-- Note: you can not put cfx or cf_ tags in here ... well you can but this is the dictionary for the cfxxxxx tags only (system tags) A better place to put the cfx and cf_ tags is in the user.xml file <!DOCTYPE dictionary [ <!ENTITY value_boolean SYSTEM "inc/value_boolean.xml"> ]> --> <dictionary xmlns="http://www.cfeclipse.org/version1/dictionary" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xi="http://www.w3.org/2001/XInclude" xsi:schemaLocation="http://www.cfeclipse.org/version1/dictionary http://cfeclipse.tigris.org/version1/dictionary/dictionary.xsd"> <tags> <!--BEGIN: BlueDragon specific tags --> <!-- cfassert --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfassert" single="true" xmlstyle="false"> <help><![CDATA[ CFASSERT is a new CFML tag introduced by BlueDragon that can be used as a testing tool to enhance the reliability and robustness of your applications. The concept of using assertions is frequently found in more advanced languages, and it’s critical to effective unit-testing of your applications. ]]></help> </tag> <!-- cfbase --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfbase" single="true" xmlstyle="false"> <help><![CDATA[ CFBASE is a CFML tag introduced by BlueDragon that is primarily intended for use in BlueDragon for J2EE Servers. The CFBASE tag can be used to create an absolute URL that serves as the base for resolving relative URLs within a CFML page (such as in IMG tags). The absolute URL created by the CFBASE tag includes the J2EE web application context path. See the document Deploying CFML on Application J2EE Application Servers for a detailed discussion of CFBASE. ]]></help> </tag> <!-- cfcachecontent action = "action" action = "name of cache" group = "group name"> cachedwithin = "timeout for cache" --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfcachecontent" single="false" xmlstyle="false"> <help><![CDATA[ CFCACHECONTENT is a new tag introduced by BlueDragon to cache blocks of html for a given time without having to regenerate it every time. While it may seem a melding of CFSAVECONTENT and CFCACHE, this tag is more powerful as it can cache not only in memory but to a database table as well. Additionally, flushing of the cache is enhanced as well, with two available attributes: CACHENAME and GROUP. GROUP allows you to gather together cached elements and treat them as a single logical unit. For example, you may wish to cache various elements for a given user, but should that user change something, you can flush and clear all their cached elements in a single operation. ]]></help> <parameter name="action" type="String" required="true"> <help><![CDATA[ Operation to perform; possible operations are CACHE, FLUSH, FLUSHGROUP, FLUSHALL, STATS and RESET: CACHE – Default value. Caches the data within the tag FLUSH - Flushes cached items designated using the given CACHENAME. All items cached with this CACHENAME are removed FLUSHGROUP - Flushes cached items designated using the given GROUP. All items cached with this GROUP are removed FLUSHALL - Flushes the entire cache, including all data in the database cache STATS - This will return a structure, CFCACHECONTENT, with two fields, MISSES and HITS, which detail the number of times requests have found data using the cache and the number of times requests called for a cached result to be generated. This gives you an indi-cation of how efficient your cache is performing RESET - resets the HIT and MISS counts to zero, for all GROUP/CACHENAMEs or individ-ual ones. ]]></help> <values> <value option="cache" /> <value option="flush" /> <value option="flushgroup" /> <value option="flushall" /> <value option="stats" /> <value option="reset" /> </values> </parameter> <parameter name="cachename" type="String" required="false"> <help><![CDATA[ Required for ACTION=CACHE. The name to be given for the item being cached, which should be unique across all GROUPs. ]]></help> <values /> </parameter> <parameter name="group" type="String" required="false"> <help><![CDATA[ A name given to group cached results together. It defaults to the name of the server, as determined in cgi.server_name. ]]></help> <values /> </parameter> <parameter name="cachedwithin" type="String" required="false"> <help><![CDATA[ Used with ACTION=CACHE. The maximum time to maintain this cached result. If the cached data is found to be older than this when a request attempts to use the cached result, the cached content will be regenerated. Specified using #CreateTimeSpan()#. ]]></help> <values /> </parameter> </tag> <!-- cfcontinue --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfcontinue" single="true" xmlstyle="false"> <help><![CDATA[ The new CFCONTINUE tag works similarly to CFBREAK in that it can only be used within the body of a CFLOOP tag (it cannot be used in a CFOUTPUT QUERY loop.) CFBREAK terminates execution of the current iteration of the CFLOOP body and continues execution after the closing CFLOOP tag. CFCONTINUE, on the other hand, terminates execution of the current iteration of the CFLOOP body and continues execution of the next iteration of the CFLOOP body from the opening CFLOOP tag. ]]></help> </tag> <!-- cfdebugger logfile="somefilepath" --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfdebugger" single="true" xmlstyle="false"> <help><![CDATA[ Creates a debug trace for the currently executing template in the specified log file. ]]></help> <parameter name="logfile" type="String" required="true"> <help><![CDATA[ Absolute path to the file where the trace log should be stored. ]]></help> <values /> </parameter> </tag> <!-- cfforward page="somefile" --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfforward" single="true" xmlstyle="false"> <help><![CDATA[ CFFORWARD is a tag introduced by BlueDragon that allows you to do a “server-side redi-rect” to another CFML page, or in some BlueDragon editions a Java servlet or JavaServer Page (JSP), or in the .NET edition an ASP.NET page. In a “client-side redirect,” which is done using the CFLOCATION tag, a response is sent to the browser telling it to send in a new request for a specified URL. In contrast, CFFORWARD processing is handled com-pletely on the server. ]]></help> <parameter name="page" type="String" required="true"> <help><![CDATA[ Relative URI where the request should be redirected. ]]></help> <values /> </parameter> </tag> <!-- cfimage action="edit" srcfile="picture.gif" destfile="newPicture.gif" uridirectory="yes" text="Copyright 2003" width="50%" height="50%" fontsize=20 fontcolour="violet" position="SOUTH" nameconflict="overwrite" --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfimage" single="true" xmlstyle="false"> <help><![CDATA[ CFIMAGE is a tag introduced by BlueDragon that allows you to modify an existing GIF or JPEG image file to produce a new image file that is resized and/or has a text label added to the image. Variables returned by this tag provide information about the new image file. ]]></help> <parameter name="action" type="String" required="false"> <help><![CDATA[ The action to be taken by the CFIMAGE tag. The value INFO populates the CFIMAGE variables with information about the image file specified by the srcFile attrib-ute without modifying the image. The value of EDIT creates a new image file by resizing and/or adding a text label to the source image file. Defaults to EDIT. ]]></help> <values> <value option="edit" /> <value option="info" /> </values> </parameter> <parameter name="srcfile" type="String" required="true"> <help><![CDATA[ The file name of the source image file that is to be modified. Can be either a full physical path or a relative path (see the URIDirectory attribute). ]]></help> <values /> </parameter> <parameter name="destfile" type="String" required="false"> <help><![CDATA[ Required if ACTION=EDIT, Optional if ACTION=INFO. The file name of the new image file to be created by the CFIMAGE tag. Can be either a full physical path or a relative path (see the URIDirectory attribute). ]]></help> <values /> </parameter> <parameter name="type" type="String" required="false"> <help><![CDATA[ The image file type, either GIF or JPEG. If this attribute is not specified, the CFIMAGE tag attempts to determine the image type based on the file name extension. ]]></help> <values /> </parameter> <parameter name="width" type="String" required="false"> <help><![CDATA[ The width of the new image, can be specified either in pixels or as a percentage of the source image width. Defaults to “100%”. ]]></help> <values /> </parameter> <parameter name="height" type="String" required="false"> <help><![CDATA[ The height of the new image, can be specified either in pixels or as a percentage of the source image height. Defaults to “100%”. ]]></help> <values /> </parameter> <parameter name="fontsize" type="Numeric" required="false"> <help><![CDATA[ An integer value that specified the font size of the text label to be added to the image. Defaults to 12. ]]></help> <values /> </parameter> <parameter name="fontcolor" type="String" required="false"> <help><![CDATA[ Specifies the font color of the text label to be added to the image. Accepts any value that is valid for use in the FONT tag. Defaults to “black”. ]]></help> <values /> </parameter> <parameter name="text" type="String" required="false"> <help><![CDATA[ The text label to add to the image. ]]></help> <values /> </parameter> <parameter name="position" type="String" required="false"> <help><![CDATA[ The position of the text label to add to the image; valid valued are “north” and “south”. Defaults to “south”. ]]></help> <values> <value option="north" /> <value option="south" /> </values> </parameter> <parameter name="nameconflict" type="String" required="false"> <help><![CDATA[ Indicates the behavior of the CFIMAGE tag when the file specified by destFile already exists. Valid values are ERROR, which generates a runtime error; SKIP, which causes the CFIMAGE tag to do nothing without generating an error; OVERWRITE, to over-write the existing image; and, MAKEUNIQUE, which causes CFIMAGE to create a new unique file name for the new image file. Defaults to ERROR. ]]></help> <values> <value option="error" /> <value option="skip" /> <value option="overwrite" /> <value option="makeunique" /> </values> </parameter> <parameter name="uridirectory" type="String" required="false"> <help><![CDATA[ If YES, relative paths specified in srcFile and destFile are calculated from the web server document root directory. If NO, relative paths are calculated as relative to the current file. Defaults to NO. ]]></help> <values /> </parameter> </tag> <!-- CFIMAP ACTION="OPEN" SERVICE="POP3 or IMAP" CONNECTION="name" SERVER="mail.yourdomain.com" USERNAME="username" PASSWORD="password" --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfimap" single="true" xmlstyle="false"> <help><![CDATA[ ]]></help> <parameter name="action" type="String" required="false"> <help><![CDATA[ The action to perform ]]></help> <values> <value option="open" /> <value option="listfolder" /> <value option="listallfolders" /> <value option="listmail" /> <value option="readmail" /> <value option="markread" /> <value option="deletemail" /> <value option="movemail" /> <value option="deletefolder" /> <value option="renamefolder" /> <value option="close" /> <value option="setflags" /> <value option="createfolder" /> </values> </parameter> <parameter name="service" type="String" required="false"> <help><![CDATA[ The type of service you are connecting to ]]></help> <values> <value option="pop3" /> <value option="imap" /> </values> <triggers> <selectedValue attributeName="action" value="open" required="true"/> </triggers> </parameter> <parameter name="connection" type="String" required="false"> <help><![CDATA[ A name for the connection so you can interact with it in your code. ]]></help> <values /> </parameter> <parameter name="server" type="String" required="false"> <help><![CDATA[ The server name or IP address of the server ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="open" required="true"/> </triggers> </parameter> <parameter name="username" type="String" required="false"> <help><![CDATA[ The username to use for authentication. ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="open" required="true"/> </triggers> </parameter> <parameter name="password" type="String" required="false"> <help><![CDATA[ The password to use for authentication ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="open" required="true"/> </triggers> </parameter> <parameter name="folder" type="String" required="false"> <help><![CDATA[ The name of a folder to work with. Must be a fully qualified folder name on the IMAP server. ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="listfolder" required="true"/> <selectedValue attributeName="action" value="listmail" required="true"/> <selectedValue attributeName="action" value="deletemail" required="true"/> <selectedValue attributeName="action" value="setflags" required="true"/> <selectedValue attributeName="action" value="movemail" required="true"/> <selectedValue attributeName="action" value="createfolder" required="true"/> <selectedValue attributeName="action" value="deleteefolder" required="true"/> </triggers> </parameter> <parameter name="name" type="String" required="false"> <help><![CDATA[ The name of the variable to create when returning resultsets ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="listfolder" required="true"/> <selectedValue attributeName="action" value="listallfolders" required="true"/> <selectedValue attributeName="action" value="listmail" required="true"/> </triggers> </parameter> <parameter name="messageid" type="String" required="false"> <help><![CDATA[ The id of the message to work with. ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="readmail" required="true"/> <selectedValue attributeName="action" value="setflags" required="true"/> </triggers> </parameter> <parameter name="attachmentsuri" type="String" required="false"> <help><![CDATA[ The uri of the folder where attachments should be stored. ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="readmail" required="true"/> </triggers> </parameter> <parameter name="messagelist" type="String" required="false"> <help><![CDATA[ The list of message IDs to mark as read. ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="markread" required="true"/> <selectedValue attributeName="action" value="deletemail" required="true"/> <selectedValue attributeName="action" value="movemail" required="true"/> </triggers> </parameter> <parameter name="flagname" type="String" required="false"> <help><![CDATA[ The flag to set on a message. ]]></help> <values> <value option="answered" /> <value option="deleted" /> <value option="draft" /> <value option="flagged" /> <value option="recent" /> <value option="seen" /> </values> <triggers> <selectedValue attributeName="action" value="setflags" required="true"/> </triggers> </parameter> <parameter name="destfolder" type="String" required="false"> <help><![CDATA[ The folder to move the message to ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="movemail" required="true"/> </triggers> </parameter> <parameter name="oldfolder" type="String" required="false"> <help><![CDATA[ The folder to rename ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="renamefolder" required="true"/> </triggers> </parameter> <parameter name="newfolder" type="String" required="false"> <help><![CDATA[ The new name for the folder. ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="renamefolder" required="true"/> </triggers> </parameter> </tag> <!-- cfmapping logicalpath = "name" relativepath = "relative path" directorypath = "full path" ---><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfabort" single="true" xmlstyle="false"> +--><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfmapping" single="true" xmlstyle="false"> <help><![CDATA[ Allows for the creation of mappings at the page or application level. ]]></help> <parameter name="logicalpath" type="String" required="true"> <help><![CDATA[ The name of the mapping to create. Should start with / ]]></help> <values/> </parameter> <parameter name="relativepath" type="String" required="false"> <help><![CDATA[ The relative path on the server to the mapped directory. e.g. /WEB-INF/map1 or ../../map1 ]]></help> <values/> </parameter> <parameter name="directorypath" type="String" required="false"> <help><![CDATA[ The fully qualified path to the mapped directory. ]]></help> <values/> </parameter> </tag> <!-- cfpause interval = "number of seconds" --><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfpause" single="true" xmlstyle="false"> <help><![CDATA[ Causes page execution to pause for the specified number of seconds ]]></help> <parameter name="interval" type="Numeric" required="true"> <help><![CDATA[ The number of seconds to pause for. Must be an integer. ]]></help> <values/> </parameter> </tag> <!-- cfthrottle action = "throttle, flush, status, set" history = "window size" token = "name of item to track" hitthreshold = "number of hits" hittimeperiod = "time period to count hits" minhittime = "time between each request" --><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfthrottle" single="true" xmlstyle="false"> <help><![CDATA[ CFTHROTTLE is a new tag introduced by BlueDragon to help respond to requests that are coming in too quickly from a given host/client. Rogue spiders, bad software etc can cripple a server with repeated requests. This tag is designed to track such requests in a given a window of time and give you the opportunity to deny or redirect their requests. ]]></help> <parameter name="action" type="Numeric" required="true"> <help><![CDATA[ The action to take Available values are: THROTTLE – Default value. Enable throttle processing FLUSH - Flushes entire historical table of throttle processing STATUS - Returns a CFML variable, CFTHROTTLE, which is an array of structures detailing each item that is currently being tracked by CFTHROTTLE. Allows creation of a status page. SET - Sets the size of the window for tracking. Defaults to 100, for the last 100 items to be tracked; can be overriden by passing a new value using the optional HISTORY attribute. ]]></help> <values> <value option="throttle" /> <value option="flush" /> <value option="status" /> <value option="set" /> </values> </parameter> <parameter name="history" type="Numeric" required="false"> <help><![CDATA[ Sets the size of the window for tracking. Defaults to 100, for the last 100 items being tracked. ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="set" required="false"/> </triggers> </parameter> <parameter name="token" type="String" required="false"> <help><![CDATA[ The string used to track repeated requests. In most instances you will track the client ip address, and this is the default if not specified. You may choose to use the CGI.HTTP_USER_AGENT variable to track, for instance, when re-quests from certain search engines are visiting your site too often in a given period of time. ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="throttle" required="false"/> </triggers> </parameter> <parameter name="hitThreshold" type="String" required="false"> <help><![CDATA[ The maximum number of times a unique TOKEN value can be used by requests being monitored in the time period specified by HITTIMEPERIOD. If the number is exceeded, then the request is flagged as excessive and a candidate to be throttled. Defaults to 5. ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="throttle" required="false"/> </triggers> </parameter> <parameter name="hitTimePeriod" type="String" required="false"> <help><![CDATA[ The time period, expressed in milliseconds, where if a successive number of requests (determined by HITTHRESHHOLD) are received sharing the given TOKEN, the request will be deemed excessive. Defaults to 10000 (10 seconds). ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="throttle" required="false"/> </triggers> </parameter> <parameter name="minHitTime" type="String" required="false"> <help><![CDATA[ The time period, expressed in milliseconds, where if successive requests (regardless of the TOKEN) are received, the request will be deemed excessive. Defaults to 500 (one half second). ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="throttle" required="false"/> </triggers> </parameter> </tag> <!-- cfxmlrpc server = "url of server" method = "name of method" params = "array of params" --><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfxmlrpc" single="true" xmlstyle="false"> <help><![CDATA[ Allows invocation of XML-RPC services ]]></help> <parameter name="server" type="String" required="true"> <help><![CDATA[ The full URL to the XML-RPC server ]]></help> <values/> </parameter> <parameter name="method" type="String" required="true"> <help><![CDATA[ The name of the method to invoke. ]]></help> <values/> </parameter> <parameter name="params" type="Array" required="true"> <help><![CDATA[ An array containing parameters for the method. ]]></help> <values/> </parameter> </tag> <!-- cfzip zipfile = "name of file" action = "create,extract" source = "name of file to create" recurse = "true, false" filter = "file name filter" timeout = "number of seconds" compressionlevel = "0-9" newpath = "new file path" prefix = "path prefix" variable = "name of list variable" destination = "path to extract directory" flatten = "true, false" --><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfzip" single="true" xmlstyle="false"> <help><![CDATA[ CFZIP is a new tag introduced by BlueDragon to assist in creating, extracting, and listing the contents of compressed (zip) files. ]]></help> <parameter name="action" type="String" required="false"> <help><![CDATA[ The action to be taken by the CFZIP tag. The value CREATE creates a zip file from the file(s) specified by the source attribute. The value of EXTRACT extracts a file(s) from a zipfile to the named DESTINATION. The value of LIST creates a query resultset describing the contents of the zip file. Defaults to CREATE. ]]></help> <values> <value option="create" /> <value option="extract" /> <value option="list" /> </values> </parameter> <parameter name="zipfile" type="String" required="true"> <help><![CDATA[ The name of the zipfile to create, extract, or list. ]]></help> <values/> </parameter> <parameter name="source" type="String" required="false"> <help><![CDATA[ The path to a file, or directory in which to find files, to be added to the zipfile. (To name multiple directories or files, use CFZIPPARAM.) ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="create" required="false" /> </triggers> </parameter> <parameter name="recurse" type="boolean" required="false"> <help><![CDATA[ Used with ACTION=CREATE. Indicates whether the subdirectories in the SOURCE directory be included. Defaults to YES. ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="create" required="false" /> </triggers> </parameter> <parameter name="filter" type="boolean" required="false"> <help><![CDATA[ Specify a filter for the given SOURCE directory e.g. *.gif (similar to the cfdirectory filter attribute) ]]></help> <values> <value option="true" /> <value option="false" /> </values> <triggers> <selectedValue attributeName="action" value="create" required="false" /> </triggers> </parameter> <parameter name="timeout" type="Numeric" required="false"> <help><![CDATA[ An exception will be thrown if the time taken to create/extract the zipfile exceeds this. Defaults to 60 seconds. ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="create" required="false" /> <selectedValue attributeName="action" value="extract" required="false" /> </triggers> </parameter> <parameter name="compressionLevel" type="Numeric" required="false"> <help><![CDATA[ A numeric in the range 0-9 (inclusive) that specifies the level of compression with 0 meaning no compression and 9 being the maximum. Defaults to 8. ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="create" required="false" /> </triggers> </parameter> <parameter name="newPath" type="String" required="false"> <help><![CDATA[ If the item specified in SOURCE is a file then this attribute can be used to specify a replacement path. If the SOURCE item is a directory then this is ignored. ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="create" required="false" /> </triggers> </parameter> <parameter name="prefix" type="String" required="false"> <help><![CDATA[ A prefix that will be prepended to the path of files in the created zipfile ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="create" required="false" /> </triggers> </parameter> <parameter name="variable" type="String" required="false"> <help><![CDATA[ The name of the variable where the result of the zipfile contents listing will appear (as a query result set) ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="list" required="true" /> </triggers> </parameter> <parameter name="destination" type="String" required="false"> <help><![CDATA[ The directory to which the zip file will be extracted. ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="extract" required="true" /> </triggers> </parameter> <parameter name="flatten" type="boolean" required="false"> <help><![CDATA[ Whether the directory structure of the zip file will be maintained in the directory to which the zipfile contents are extracted. Defaults to true. ]]></help> <values> <value option="true" /> <value option="false" /> </values> <triggers> <selectedValue attributeName="action" value="extract" required="false" /> </triggers> </parameter> </tag> <!-- cfzipparam source = "name of file to create" recurse = "true, false" filter = "file name filter" newpath = "new file path" prefix = "path prefix" --><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfzipparam" single="true" xmlstyle="false"> <help><![CDATA[ The CFZIPPARAM tag can be used to embed references to multiple files/directories during the process of creating a zip file. It is to be used only with CFZIP ACTION=”create”. ]]></help> <parameter name="source" type="String" required="true"> <help><![CDATA[ The path to a file, or directory in which to find files, to be added to the zipfile. ]]></help> <values/> </parameter> <parameter name="recurse" type="boolean" required="false"> <help><![CDATA[ Used with ACTION=CREATE. Indicates whether the subdirectories in the SOURCE directory be included. Defaults to YES. ]]></help> <values> <value option="true" /> <value option="false" /> </values> </parameter> <parameter name="filter" type="boolean" required="false"> <help><![CDATA[ Specify a filter for the given SOURCE directory e.g. *.gif (similar to the cfdirectory filter attribute) ]]></help> <values/> </parameter> <parameter name="newPath" type="String" required="false"> <help><![CDATA[ If the item specified in SOURCE is a file then this attribute can be used to specify a replacement path. If the SOURCE item is a directory then this is ignored. ]]></help> <values/> </parameter> <parameter name="prefix" type="String" required="false"> <help><![CDATA[ A prefix that will be prepended to the path of files in the created zipfile ]]></help> <values/> </parameter> </tag> <!--END: BlueDragon specific tags --> <!-- cfabort showError = "error_message" --><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfabort" single="true" xmlstyle="false"> <help><![CDATA[ Stops the processing of a CFML page at the tag location. CFML returns everything that was processed before the tag. The tag is often used with conditional logic to stop processing a page when a condition occurs. ]]></help> <parameter name="showerror" type="String" required="false"> <help><![CDATA[ Error to display, in a standard CFML error page, when tag executes ]]></help> <values/> </parameter> </tag> <!-- cfapplication name = "application_name" loginStorage = "cookie" or "session" clientManagement = "boolean" clientStorage = "datasource_name" or "Registry" or "Cookie" setClientCookies = "boolean" sessionManagement = "boolean" sessionTimeout = #CreateTimeSpan(days, hours, minutes, seconds)# applicationTimeout = #CreateTimeSpan(days, hours, minutes, seconds)# setDomainCookies = "boolean" --><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfapplication" single="true" xmlstyle="false"> <help><![CDATA[ Defines the scope of a CFML application; enables and disables storage of Client variables; specifies the Client variable storage mechanism; enables Session variables; and sets Application variable timeouts. ]]></help> <return type="application" name="application"/> <return type="session" name="session"/> <return type="client" name="client"/> <parameter name="name" type="String" required="false"> <help><![CDATA[ Name of application. Up to 64 characters ]]></help> <values/> </parameter> <parameter name="loginstorage" type="String" required="false"> <help><![CDATA[ ]]></help> <values default="cookie"> <value option="cookie"/> <value option="session"/> </values> </parameter> <parameter name="clientmanagement" type="boolean" required="false"> <help><![CDATA[ enables client variables ]]></help> <values default="false"> <value option="true"/> <value option="false"/> </values> </parameter> <parameter name="clientstorage" type="String" required="false"> <help><![CDATA[ How client variables are stored * datasource_name: in ODBC or native data source. You must create storage repository in the Administrator. * registry: in the system registry. * cookie: on client computer in a cookie. Scalable. If client disables cookies in the browser, client variables do not work ]]></help> <values default="registry"> <value option="cookie"/> <value option="registry"/> <value option="datasource_name"/> </values> </parameter> <parameter name="setclientcookies" type="boolean" required="false"> <help><![CDATA[ No: CFML does not automatically send CFID and CFTOKEN cookies to client browser; you must manually code CFID and CFTOKEN on the URL for every page that uses Session or Client variables ]]></help> <values default="true"> <value option="true"/> <value option="false"/> </values> </parameter> <parameter name="sessionmanagement" type="boolean" required="false"> <help><![CDATA[ enables session variables ]]></help> <values default="false"> <value option="true"/> <value option="false"/> </values> </parameter> <parameter name="sessiontimeout" type="Timespan" required="false"> <help><![CDATA[ Lifespan of session variables. CreateTimeSpan function and values in days, hours, minutes, and seconds, separated by commas ]]></help> <values/> </parameter> <parameter name="applicationtimeout" type="Timespan" required="false"> <help><![CDATA[ Lifespan of application variables. CreateTimeSpan function and values in days, hours, minutes, and seconds, separated by commas. ]]></help> <values/> </parameter> <parameter name="setdomaincookies" type="boolean" required="false"> <help><![CDATA[ Yes: Sets CFID and CFTOKEN cookies for a domain (not a host) Required, for applications running on clusters. ]]></help> <values default="false"> <value option="true"/> <value option="false"/> </values> </parameter> </tag> <!-- cfargument name = "String" type = "data type" required = "boolean" default = "default value" displayname = "descriptive name" hint = "extended description" --><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfargument" single="true" xmlstyle="false" allowanyattribute="true"> <help><![CDATA[ Creates a parameter definition within a component definition. Defines a function argument. Used within a cffunction tag. ]]></help> diff --git a/Resources/cfmlBD70.xml b/Resources/cfmlBD70.xml index 01e95a6..e02e7ac 100644 --- a/Resources/cfmlBD70.xml +++ b/Resources/cfmlBD70.xml @@ -53,1025 +53,1025 @@ <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfjoin" single="true" xmlstyle="false"> <help><![CDATA[ CFJOIN is a new tag for creating threads. ]]></help> <parameter name="thread" type="String" required="true"> <help><![CDATA[ Required. The name of the thread ]]></help> <values /> </parameter> </tag> <!-- cfinterrupt thread = "name" --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfinterrupt" single="true" xmlstyle="false"> <help><![CDATA[ CFINTERRUPT is a new tag for creating threads. ]]></help> <parameter name="thread" type="String" required="true"> <help><![CDATA[ Required. The name of the thread ]]></help> <values /> </parameter> </tag> <!-- cfassert --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfassert" single="true" xmlstyle="false"> <help><![CDATA[ CFASSERT is a new CFML tag introduced by BlueDragon that can be used as a testing tool to enhance the reliability and robustness of your applications. The concept of using assertions is frequently found in more advanced languages, and it’s critical to effective unit-testing of your applications. ]]></help> </tag> <!-- cfbase --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfbase" single="true" xmlstyle="false"> <help><![CDATA[ CFBASE is a CFML tag introduced by BlueDragon that is primarily intended for use in BlueDragon for J2EE Servers. The CFBASE tag can be used to create an absolute URL that serves as the base for resolving relative URLs within a CFML page (such as in IMG tags). The absolute URL created by the CFBASE tag includes the J2EE web application context path. See the document Deploying CFML on Application J2EE Application Servers for a detailed discussion of CFBASE. ]]></help> </tag> <!-- cfcachecontent action = "action" action = "name of cache" group = "group name"> cachedwithin = "timeout for cache" --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfcachecontent" single="false" xmlstyle="false"> <help><![CDATA[ CFCACHECONTENT is a new tag introduced by BlueDragon to cache blocks of html for a given time without having to regenerate it every time. While it may seem a melding of CFSAVECONTENT and CFCACHE, this tag is more powerful as it can cache not only in memory but to a database table as well. Additionally, flushing of the cache is enhanced as well, with two available attributes: CACHENAME and GROUP. GROUP allows you to gather together cached elements and treat them as a single logical unit. For example, you may wish to cache various elements for a given user, but should that user change something, you can flush and clear all their cached elements in a single operation. ]]></help> <parameter name="action" type="String" required="true"> <help><![CDATA[ Operation to perform; possible operations are CACHE, FLUSH, FLUSHGROUP, FLUSHALL, STATS and RESET: CACHE – Default value. Caches the data within the tag FLUSH - Flushes cached items designated using the given CACHENAME. All items cached with this CACHENAME are removed FLUSHGROUP - Flushes cached items designated using the given GROUP. All items cached with this GROUP are removed FLUSHALL - Flushes the entire cache, including all data in the database cache STATS - This will return a structure, CFCACHECONTENT, with two fields, MISSES and HITS, which detail the number of times requests have found data using the cache and the number of times requests called for a cached result to be generated. This gives you an indi-cation of how efficient your cache is performing RESET - resets the HIT and MISS counts to zero, for all GROUP/CACHENAMEs or individ-ual ones. ]]></help> <values> <value option="cache" /> <value option="flush" /> <value option="flushgroup" /> <value option="flushall" /> <value option="stats" /> <value option="reset" /> </values> </parameter> <parameter name="cachename" type="String" required="false"> <help><![CDATA[ Required for ACTION=CACHE. The name to be given for the item being cached, which should be unique across all GROUPs. ]]></help> <values /> </parameter> <parameter name="group" type="String" required="false"> <help><![CDATA[ A name given to group cached results together. It defaults to the name of the server, as determined in cgi.server_name. ]]></help> <values /> </parameter> <parameter name="cachedwithin" type="String" required="false"> <help><![CDATA[ Used with ACTION=CACHE. The maximum time to maintain this cached result. If the cached data is found to be older than this when a request attempts to use the cached result, the cached content will be regenerated. Specified using #CreateTimeSpan()#. ]]></help> <values /> </parameter> </tag> <!-- cfcontinue --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfcontinue" single="true" xmlstyle="false"> <help><![CDATA[ The new CFCONTINUE tag works similarly to CFBREAK in that it can only be used within the body of a CFLOOP tag (it cannot be used in a CFOUTPUT QUERY loop.) CFBREAK terminates execution of the current iteration of the CFLOOP body and continues execution after the closing CFLOOP tag. CFCONTINUE, on the other hand, terminates execution of the current iteration of the CFLOOP body and continues execution of the next iteration of the CFLOOP body from the opening CFLOOP tag. ]]></help> </tag> <!-- cfdebugger logfile="somefilepath" --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfdebugger" single="true" xmlstyle="false"> <help><![CDATA[ Creates a debug trace for the currently executing template in the specified log file. ]]></help> <parameter name="logfile" type="String" required="true"> <help><![CDATA[ Absolute path to the file where the trace log should be stored. ]]></help> <values /> </parameter> </tag> <!-- cfforward page="somefile" --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfforward" single="true" xmlstyle="false"> <help><![CDATA[ CFFORWARD is a tag introduced by BlueDragon that allows you to do a “server-side redi-rect” to another CFML page, or in some BlueDragon editions a Java servlet or JavaServer Page (JSP), or in the .NET edition an ASP.NET page. In a “client-side redirect,” which is done using the CFLOCATION tag, a response is sent to the browser telling it to send in a new request for a specified URL. In contrast, CFFORWARD processing is handled com-pletely on the server. ]]></help> <parameter name="page" type="String" required="true"> <help><![CDATA[ Relative URI where the request should be redirected. ]]></help> <values /> </parameter> </tag> <!-- cfimage action="edit" srcfile="picture.gif" destfile="newPicture.gif" uridirectory="yes" text="Copyright 2003" width="50%" height="50%" fontsize=20 fontcolour="violet" position="SOUTH" nameconflict="overwrite" --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfimage" single="true" xmlstyle="false"> <help><![CDATA[ CFIMAGE is a tag introduced by BlueDragon that allows you to modify an existing GIF or JPEG image file to produce a new image file that is resized and/or has a text label added to the image. Variables returned by this tag provide information about the new image file. ]]></help> <parameter name="action" type="String" required="false"> <help><![CDATA[ The action to be taken by the CFIMAGE tag. The value INFO populates the CFIMAGE variables with information about the image file specified by the srcFile attrib-ute without modifying the image. The value of EDIT creates a new image file by resizing and/or adding a text label to the source image file. Defaults to EDIT. ]]></help> <values> <value option="edit" /> <value option="info" /> </values> </parameter> <parameter name="srcfile" type="String" required="true"> <help><![CDATA[ The file name of the source image file that is to be modified. Can be either a full physical path or a relative path (see the URIDirectory attribute). ]]></help> <values /> </parameter> <parameter name="destfile" type="String" required="false"> <help><![CDATA[ Required if ACTION=EDIT, Optional if ACTION=INFO. The file name of the new image file to be created by the CFIMAGE tag. Can be either a full physical path or a relative path (see the URIDirectory attribute). ]]></help> <values /> </parameter> <parameter name="type" type="String" required="false"> <help><![CDATA[ The image file type, either GIF or JPEG. If this attribute is not specified, the CFIMAGE tag attempts to determine the image type based on the file name extension. ]]></help> <values /> </parameter> <parameter name="width" type="String" required="false"> <help><![CDATA[ The width of the new image, can be specified either in pixels or as a percentage of the source image width. Defaults to “100%”. ]]></help> <values /> </parameter> <parameter name="height" type="String" required="false"> <help><![CDATA[ The height of the new image, can be specified either in pixels or as a percentage of the source image height. Defaults to “100%”. ]]></help> <values /> </parameter> <parameter name="fontsize" type="Numeric" required="false"> <help><![CDATA[ An integer value that specified the font size of the text label to be added to the image. Defaults to 12. ]]></help> <values /> </parameter> <parameter name="fontcolor" type="String" required="false"> <help><![CDATA[ Specifies the font color of the text label to be added to the image. Accepts any value that is valid for use in the FONT tag. Defaults to “black”. ]]></help> <values /> </parameter> <parameter name="text" type="String" required="false"> <help><![CDATA[ The text label to add to the image. ]]></help> <values /> </parameter> <parameter name="position" type="String" required="false"> <help><![CDATA[ The position of the text label to add to the image; valid valued are “north” and “south”. Defaults to “south”. ]]></help> <values> <value option="north" /> <value option="south" /> </values> </parameter> <parameter name="nameconflict" type="String" required="false"> <help><![CDATA[ Indicates the behavior of the CFIMAGE tag when the file specified by destFile already exists. Valid values are ERROR, which generates a runtime error; SKIP, which causes the CFIMAGE tag to do nothing without generating an error; OVERWRITE, to over-write the existing image; and, MAKEUNIQUE, which causes CFIMAGE to create a new unique file name for the new image file. Defaults to ERROR. ]]></help> <values> <value option="error" /> <value option="skip" /> <value option="overwrite" /> <value option="makeunique" /> </values> </parameter> <parameter name="uridirectory" type="String" required="false"> <help><![CDATA[ If YES, relative paths specified in srcFile and destFile are calculated from the web server document root directory. If NO, relative paths are calculated as relative to the current file. Defaults to NO. ]]></help> <values /> </parameter> </tag> <!-- CFIMAP ACTION="OPEN" SERVICE="POP3 or IMAP" CONNECTION="name" SERVER="mail.yourdomain.com" USERNAME="username" PASSWORD="password" --> <tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfimap" single="true" xmlstyle="false"> <help><![CDATA[ ]]></help> <parameter name="action" type="String" required="false"> <help><![CDATA[ The action to perform ]]></help> <values> <value option="open" /> <value option="listfolder" /> <value option="listallfolders" /> <value option="listmail" /> <value option="readmail" /> <value option="markread" /> <value option="deletemail" /> <value option="movemail" /> <value option="deletefolder" /> <value option="renamefolder" /> <value option="close" /> <value option="setflags" /> <value option="createfolder" /> </values> </parameter> <parameter name="service" type="String" required="false"> <help><![CDATA[ The type of service you are connecting to ]]></help> <values> <value option="pop3" /> <value option="imap" /> </values> <triggers> <selectedValue attributeName="action" value="open" required="true"/> </triggers> </parameter> <parameter name="connection" type="String" required="false"> <help><![CDATA[ A name for the connection so you can interact with it in your code. ]]></help> <values /> </parameter> <parameter name="server" type="String" required="false"> <help><![CDATA[ The server name or IP address of the server ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="open" required="true"/> </triggers> </parameter> <parameter name="username" type="String" required="false"> <help><![CDATA[ The username to use for authentication. ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="open" required="true"/> </triggers> </parameter> <parameter name="password" type="String" required="false"> <help><![CDATA[ The password to use for authentication ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="open" required="true"/> </triggers> </parameter> <parameter name="folder" type="String" required="false"> <help><![CDATA[ The name of a folder to work with. Must be a fully qualified folder name on the IMAP server. ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="listfolder" required="true"/> <selectedValue attributeName="action" value="listmail" required="true"/> <selectedValue attributeName="action" value="deletemail" required="true"/> <selectedValue attributeName="action" value="setflags" required="true"/> <selectedValue attributeName="action" value="movemail" required="true"/> <selectedValue attributeName="action" value="createfolder" required="true"/> <selectedValue attributeName="action" value="deleteefolder" required="true"/> </triggers> </parameter> <parameter name="name" type="String" required="false"> <help><![CDATA[ The name of the variable to create when returning resultsets ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="listfolder" required="true"/> <selectedValue attributeName="action" value="listallfolders" required="true"/> <selectedValue attributeName="action" value="listmail" required="true"/> </triggers> </parameter> <parameter name="messageid" type="String" required="false"> <help><![CDATA[ The id of the message to work with. ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="readmail" required="true"/> <selectedValue attributeName="action" value="setflags" required="true"/> </triggers> </parameter> <parameter name="attachmentsuri" type="String" required="false"> <help><![CDATA[ The uri of the folder where attachments should be stored. ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="readmail" required="true"/> </triggers> </parameter> <parameter name="messagelist" type="String" required="false"> <help><![CDATA[ The list of message IDs to mark as read. ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="markread" required="true"/> <selectedValue attributeName="action" value="deletemail" required="true"/> <selectedValue attributeName="action" value="movemail" required="true"/> </triggers> </parameter> <parameter name="flagname" type="String" required="false"> <help><![CDATA[ The flag to set on a message. ]]></help> <values> <value option="answered" /> <value option="deleted" /> <value option="draft" /> <value option="flagged" /> <value option="recent" /> <value option="seen" /> </values> <triggers> <selectedValue attributeName="action" value="setflags" required="true"/> </triggers> </parameter> <parameter name="destfolder" type="String" required="false"> <help><![CDATA[ The folder to move the message to ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="movemail" required="true"/> </triggers> </parameter> <parameter name="oldfolder" type="String" required="false"> <help><![CDATA[ The folder to rename ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="renamefolder" required="true"/> </triggers> </parameter> <parameter name="newfolder" type="String" required="false"> <help><![CDATA[ The new name for the folder. ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="renamefolder" required="true"/> </triggers> </parameter> </tag> <!-- cfmapping logicalpath = "name" relativepath = "relative path" directorypath = "full path" ---><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfabort" single="true" xmlstyle="false"> +--><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfmapping" single="true" xmlstyle="false"> <help><![CDATA[ Allows for the creation of mappings at the page or application level. ]]></help> <parameter name="logicalpath" type="String" required="true"> <help><![CDATA[ The name of the mapping to create. Should start with / ]]></help> <values/> </parameter> <parameter name="relativepath" type="String" required="false"> <help><![CDATA[ The relative path on the server to the mapped directory. e.g. /WEB-INF/map1 or ../../map1 ]]></help> <values/> </parameter> <parameter name="directorypath" type="String" required="false"> <help><![CDATA[ The fully qualified path to the mapped directory. ]]></help> <values/> </parameter> </tag> <!-- cfpause interval = "number of seconds" --><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfpause" single="true" xmlstyle="false"> <help><![CDATA[ Causes page execution to pause for the specified number of seconds ]]></help> <parameter name="interval" type="Numeric" required="true"> <help><![CDATA[ The number of seconds to pause for. Must be an integer. ]]></help> <values/> </parameter> </tag> <!-- cfthrottle action = "throttle, flush, status, set" history = "window size" token = "name of item to track" hitthreshold = "number of hits" hittimeperiod = "time period to count hits" minhittime = "time between each request" --><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfthrottle" single="true" xmlstyle="false"> <help><![CDATA[ CFTHROTTLE is a new tag introduced by BlueDragon to help respond to requests that are coming in too quickly from a given host/client. Rogue spiders, bad software etc can cripple a server with repeated requests. This tag is designed to track such requests in a given a window of time and give you the opportunity to deny or redirect their requests. ]]></help> <parameter name="action" type="Numeric" required="true"> <help><![CDATA[ The action to take Available values are: THROTTLE – Default value. Enable throttle processing FLUSH - Flushes entire historical table of throttle processing STATUS - Returns a CFML variable, CFTHROTTLE, which is an array of structures detailing each item that is currently being tracked by CFTHROTTLE. Allows creation of a status page. SET - Sets the size of the window for tracking. Defaults to 100, for the last 100 items to be tracked; can be overriden by passing a new value using the optional HISTORY attribute. ]]></help> <values> <value option="throttle" /> <value option="flush" /> <value option="status" /> <value option="set" /> </values> </parameter> <parameter name="history" type="Numeric" required="false"> <help><![CDATA[ Sets the size of the window for tracking. Defaults to 100, for the last 100 items being tracked. ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="set" required="false"/> </triggers> </parameter> <parameter name="token" type="String" required="false"> <help><![CDATA[ The string used to track repeated requests. In most instances you will track the client ip address, and this is the default if not specified. You may choose to use the CGI.HTTP_USER_AGENT variable to track, for instance, when re-quests from certain search engines are visiting your site too often in a given period of time. ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="throttle" required="false"/> </triggers> </parameter> <parameter name="hitThreshold" type="String" required="false"> <help><![CDATA[ The maximum number of times a unique TOKEN value can be used by requests being monitored in the time period specified by HITTIMEPERIOD. If the number is exceeded, then the request is flagged as excessive and a candidate to be throttled. Defaults to 5. ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="throttle" required="false"/> </triggers> </parameter> <parameter name="hitTimePeriod" type="String" required="false"> <help><![CDATA[ The time period, expressed in milliseconds, where if a successive number of requests (determined by HITTHRESHHOLD) are received sharing the given TOKEN, the request will be deemed excessive. Defaults to 10000 (10 seconds). ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="throttle" required="false"/> </triggers> </parameter> <parameter name="minHitTime" type="String" required="false"> <help><![CDATA[ The time period, expressed in milliseconds, where if successive requests (regardless of the TOKEN) are received, the request will be deemed excessive. Defaults to 500 (one half second). ]]></help> <values /> <triggers> <selectedValue attributeName="action" value="throttle" required="false"/> </triggers> </parameter> </tag> <!-- cfxmlrpc server = "url of server" method = "name of method" params = "array of params" --><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfxmlrpc" single="true" xmlstyle="false"> <help><![CDATA[ Allows invocation of XML-RPC services ]]></help> <parameter name="server" type="String" required="true"> <help><![CDATA[ The full URL to the XML-RPC server ]]></help> <values/> </parameter> <parameter name="method" type="String" required="true"> <help><![CDATA[ The name of the method to invoke. ]]></help> <values/> </parameter> <parameter name="params" type="Array" required="true"> <help><![CDATA[ An array containing parameters for the method. ]]></help> <values/> </parameter> </tag> <!-- cfzip zipfile = "name of file" action = "create,extract" source = "name of file to create" recurse = "true, false" filter = "file name filter" timeout = "number of seconds" compressionlevel = "0-9" newpath = "new file path" prefix = "path prefix" variable = "name of list variable" destination = "path to extract directory" flatten = "true, false" --><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfzip" single="true" xmlstyle="false"> <help><![CDATA[ CFZIP is a new tag introduced by BlueDragon to assist in creating, extracting, and listing the contents of compressed (zip) files. ]]></help> <parameter name="action" type="String" required="false"> <help><![CDATA[ The action to be taken by the CFZIP tag. The value CREATE creates a zip file from the file(s) specified by the source attribute. The value of EXTRACT extracts a file(s) from a zipfile to the named DESTINATION. The value of LIST creates a query resultset describing the contents of the zip file. Defaults to CREATE. ]]></help> <values> <value option="create" /> <value option="extract" /> <value option="list" /> </values> </parameter> <parameter name="zipfile" type="String" required="true"> <help><![CDATA[ The name of the zipfile to create, extract, or list. ]]></help> <values/> </parameter> <parameter name="source" type="String" required="false"> <help><![CDATA[ The path to a file, or directory in which to find files, to be added to the zipfile. (To name multiple directories or files, use CFZIPPARAM.) ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="create" required="false" /> </triggers> </parameter> <parameter name="recurse" type="boolean" required="false"> <help><![CDATA[ Used with ACTION=CREATE. Indicates whether the subdirectories in the SOURCE directory be included. Defaults to YES. ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="create" required="false" /> </triggers> </parameter> <parameter name="filter" type="boolean" required="false"> <help><![CDATA[ Specify a filter for the given SOURCE directory e.g. *.gif (similar to the cfdirectory filter attribute) ]]></help> <values> <value option="true" /> <value option="false" /> </values> <triggers> <selectedValue attributeName="action" value="create" required="false" /> </triggers> </parameter> <parameter name="timeout" type="Numeric" required="false"> <help><![CDATA[ An exception will be thrown if the time taken to create/extract the zipfile exceeds this. Defaults to 60 seconds. ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="create" required="false" /> <selectedValue attributeName="action" value="extract" required="false" /> </triggers> </parameter> <parameter name="compressionLevel" type="Numeric" required="false"> <help><![CDATA[ A numeric in the range 0-9 (inclusive) that specifies the level of compression with 0 meaning no compression and 9 being the maximum. Defaults to 8. ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="create" required="false" /> </triggers> </parameter> <parameter name="newPath" type="String" required="false"> <help><![CDATA[ If the item specified in SOURCE is a file then this attribute can be used to specify a replacement path. If the SOURCE item is a directory then this is ignored. ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="create" required="false" /> </triggers> </parameter> <parameter name="prefix" type="String" required="false"> <help><![CDATA[ A prefix that will be prepended to the path of files in the created zipfile ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="create" required="false" /> </triggers> </parameter> <parameter name="variable" type="String" required="false"> <help><![CDATA[ The name of the variable where the result of the zipfile contents listing will appear (as a query result set) ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="list" required="true" /> </triggers> </parameter> <parameter name="destination" type="String" required="false"> <help><![CDATA[ The directory to which the zip file will be extracted. ]]></help> <values/> <triggers> <selectedValue attributeName="action" value="extract" required="true" /> </triggers> </parameter> <parameter name="flatten" type="boolean" required="false"> <help><![CDATA[ Whether the directory structure of the zip file will be maintained in the directory to which the zipfile contents are extracted. Defaults to true. ]]></help> <values> <value option="true" /> <value option="false" /> </values> <triggers> <selectedValue attributeName="action" value="extract" required="false" /> </triggers> </parameter> </tag> <!-- cfzipparam source = "name of file to create" recurse = "true, false" filter = "file name filter" newpath = "new file path" prefix = "path prefix" --><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfzipparam" single="true" xmlstyle="false"> <help><![CDATA[ The CFZIPPARAM tag can be used to embed references to multiple files/directories during the process of creating a zip file. It is to be used only with CFZIP ACTION=”create”. ]]></help> <parameter name="source" type="String" required="true"> <help><![CDATA[ The path to a file, or directory in which to find files, to be added to the zipfile. ]]></help> <values/> </parameter> <parameter name="recurse" type="boolean" required="false"> <help><![CDATA[ Used with ACTION=CREATE. Indicates whether the subdirectories in the SOURCE directory be included. Defaults to YES. ]]></help> <values> <value option="true" /> <value option="false" /> </values> </parameter> <parameter name="filter" type="boolean" required="false"> <help><![CDATA[ Specify a filter for the given SOURCE directory e.g. *.gif (similar to the cfdirectory filter attribute) ]]></help> <values/> </parameter> <parameter name="newPath" type="String" required="false"> <help><![CDATA[ If the item specified in SOURCE is a file then this attribute can be used to specify a replacement path. If the SOURCE item is a directory then this is ignored. ]]></help> <values/> </parameter> <parameter name="prefix" type="String" required="false"> <help><![CDATA[ A prefix that will be prepended to the path of files in the created zipfile ]]></help> <values/> </parameter> </tag> <!--END: BlueDragon specific tags --> <!-- cfabort showError = "error_message" --><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfabort" single="true" xmlstyle="false"> <help><![CDATA[ Stops the processing of a CFML page at the tag location. CFML returns everything that was processed before the tag. The tag is often used with conditional logic to stop processing a page when a condition occurs. ]]></help> <parameter name="showerror" type="String" required="false"> <help><![CDATA[ Error to display, in a standard CFML error page, when tag executes ]]></help> <values/> </parameter> </tag> <!-- cfapplication name = "application_name" loginStorage = "cookie" or "session" clientManagement = "boolean" clientStorage = "datasource_name" or "Registry" or "Cookie" setClientCookies = "boolean" sessionManagement = "boolean" sessionTimeout = #CreateTimeSpan(days, hours, minutes, seconds)# applicationTimeout = #CreateTimeSpan(days, hours, minutes, seconds)# setDomainCookies = "boolean" --><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfapplication" single="true" xmlstyle="false"> <help><![CDATA[ Defines the scope of a CFML application; enables and disables storage of Client variables; specifies the Client variable storage mechanism; enables Session variables; and sets Application variable timeouts. ]]></help> <return type="application" name="application"/> <return type="session" name="session"/> <return type="client" name="client"/> <parameter name="name" type="String" required="false"> <help><![CDATA[ Name of application. Up to 64 characters ]]></help> <values/> </parameter> <parameter name="loginstorage" type="String" required="false"> <help><![CDATA[ ]]></help> <values default="cookie"> <value option="cookie"/> <value option="session"/> </values> </parameter> <parameter name="clientmanagement" type="boolean" required="false"> <help><![CDATA[ enables client variables ]]></help> <values default="false"> <value option="true"/> <value option="false"/> </values> </parameter> <parameter name="clientstorage" type="String" required="false"> <help><![CDATA[ How client variables are stored * datasource_name: in ODBC or native data source. You must create storage repository in the Administrator. * registry: in the system registry. * cookie: on client computer in a cookie. Scalable. If client disables cookies in the browser, client variables do not work ]]></help> <values default="registry"> <value option="cookie"/> <value option="registry"/> <value option="datasource_name"/> </values> </parameter> <parameter name="setclientcookies" type="boolean" required="false"> <help><![CDATA[ No: CFML does not automatically send CFID and CFTOKEN cookies to client browser; you must manually code CFID and CFTOKEN on the URL for every page that uses Session or Client variables ]]></help> <values default="true"> <value option="true"/> <value option="false"/> </values> </parameter> <parameter name="sessionmanagement" type="boolean" required="false"> <help><![CDATA[ enables session variables ]]></help> <values default="false"> <value option="true"/> <value option="false"/> </values> </parameter> <parameter name="sessiontimeout" type="Timespan" required="false"> <help><![CDATA[ Lifespan of session variables. CreateTimeSpan function and values in days, hours, minutes, and seconds, separated by commas ]]></help> <values/> </parameter> <parameter name="applicationtimeout" type="Timespan" required="false"> <help><![CDATA[ Lifespan of application variables. CreateTimeSpan function and values in days, hours, minutes, and seconds, separated by commas. ]]></help> <values/> </parameter> <parameter name="setdomaincookies" type="boolean" required="false"> <help><![CDATA[ Yes: Sets CFID and CFTOKEN cookies for a domain (not a host) Required, for applications running on clusters. ]]></help> <values default="false"> <value option="true"/> <value option="false"/> </values> </parameter> </tag> <!-- cfargument name = "String" type = "data type" required = "boolean" default = "default value" displayname = "descriptive name" hint = "extended description" --><tag xmlns="http://www.cfeclipse.org/version1/dictionary" name="cfargument" single="true" xmlstyle="false" allowanyattribute="true"> <help><![CDATA[ Creates a parameter definition within a component definition. Defines a function argument. Used within a cffunction tag. ]]></help> diff --git a/build.xml b/build.xml index bc14b8b..d69d518 100644 --- a/build.xml +++ b/build.xml @@ -1,43 +1,65 @@ <project name="ColdFusion Textmate Bundle"> <!-- The xslt process needs an XSLT 2.0 processor, so I am using Saxon--> <property name="saxon.path" value="/Applications/saxonb9-0-0-4j/saxon9.jar" /> <!-- Probably wont need to change this unless you are going to try to use a different cfeclipse dictionary file. --> - <property name="dictionary.file" value="Resources/cf8.xml" /> - <property name="xsl.file" value="dictToBundle.xsl" /> - - <property name="base.bundle" value="ColdFusion.bun" /> - <property name="output.bundle" value="ColdFusion.tmbundle" /> + <property name="dictionary.file" value="Resources/cfml.xml" /> + <property name="output.name" value="ColdFusion" /> + <property name="output.bundle" value="${output.name}.tmbundle" /> <property name="bundle.uuid" value="1A09BE0B-E81A-4CB7-AF69-AFC845162D1F" /> + <property name="snytax.uuid" value="97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14" /> + <property name="cmddoc.uuid" value="9902B0A3-0523-4190-B541-374AC09CC72F" /> + + <property name="xsl.file" value="dictToBundle.xsl" /> + <property name="doc.xsl.file" value="dictToAPI.xsl" /> + <property name="base.bundle" value="ColdFusion.bun" /> <target name="clean"> - <delete dir="${output.bundle}" /> - <!-- <delete verbose="true"> - <fileset dir="./${base.bundle}/Snippets" - includes="**/gen-*.tmSnippet" /> - </delete> --> + <delete dir="build/${output.bundle}" /> + </target> + + <target name="superclean"> + <delete dir="build" /> </target> <target name="createSnippets"> - <!-- <mkdir dir="${output.bundle}" /> --> <java jar="${saxon.path}" fork="true"> - <arg value="-o:${output.bundle}/info.plist" /> + <arg value="-o:build/${output.bundle}/info.plist" /> <arg value="${dictionary.file}" /> <arg value="${xsl.file}" /> <arg value="bundle-uuid=${bundle.uuid}" /> + <arg value="bundle-name=${output.name}" /> + </java> + </target> + + <target name="createAPIDoc"> + <java jar="${saxon.path}" fork="true"> + <arg value="-o:doc/${output.name}.html" /> + <arg value="${dictionary.file}" /> + <arg value="${doc.xsl.file}" /> + <!-- <arg value="bundle-uuid=${bundle.uuid}" /> + <arg value="bundle-name=${output.name}" /> --> </java> </target> <target name="createBundle"> - <copy todir="${output.bundle}"> + <copy todir="build/${output.bundle}"> <fileset dir="${base.bundle}"/> + <filterset> + <filter token="BUNDLE_NAME" value="${output.name}"/> + <filter token="BUNDLE_UUID" value="${bundle.uuid}"/> + <filter token="SYNTAX_UUID" value="${syntax.uuid}"/> + <filter token="CMDDOC_UUID" value="${cmddoc.uuid}"/> + </filterset> </copy> </target> <target name="build"> + <mkdir dir="build" /> <antcall target="createBundle" /> <antcall target="createSnippets" /> + <antcall target="createAPIDoc" /> </target> </project> \ No newline at end of file diff --git a/dictToAPI.xsl b/dictToAPI.xsl new file mode 100644 index 0000000..193655b --- /dev/null +++ b/dictToAPI.xsl @@ -0,0 +1,131 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<!-- @@Copyright: Daemon Pty Limited 2002-2008, http://www.daemon.com.au --> +<!-- @@License: + This file is part of FarCry. + + FarCry is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + FarCry is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with FarCry. If not, see <http://www.gnu.org/licenses/>. + + On Mac you can run this by typing the following at the Terminal: + $ xsltproc api.xsl farcry51.xml > farcry5-1-doc.html + After an apt-get (or what have you) you can do that on Linux as well. + As for windows, you'll need to grab your favorite XSLT transforming + application. You can do it in an ant build script as well. + +--> +<!-- @@displayname: api.xsl --> +<!-- @@description: Turns a cfeclipse dictionary into a simple web page--> +<!-- @@author: Rob Rohan ([email protected]) --> + +<xsl:stylesheet version="2.0" + xmlns:xsl="http://www.w3.org/1999/XSL/Transform" + xmlns:d="http://www.cfeclipse.org/version1/dictionary" +> + <xsl:output encoding="UTF-8" indent="yes" method="html" /> + + <xsl:template match="/"> + <html> + <head> + <link rel="stylesheet" type="text/css" href="style.css" /> + </head> + <body> + <xsl:call-template name="makeTOC"/> + + <xsl:apply-templates select="/d:dictionary/d:tags" /> + <xsl:apply-templates select="/d:dictionary/d:functions" /> + <xsl:apply-templates select="/d:dictionary/d:scopes" /> + </body> + </html> + </xsl:template> + + <xsl:template name="makeTOC"> + <h1>Available Tags and Functions</h1> + <div class="tocWrapper"> + <h2>Tags</h2> + <div class="tagTOCWrapper"> + <xsl:for-each select="//d:tag"> + <xsl:sort select="@name" data-type="text" + order="ascending" case-order="lower-first"/> + <a href="#{@name}"><xsl:value-of select="@name" /></a> &#160; + </xsl:for-each> + </div> + + <h2>Functions</h2> + <div class="functionTOCWrapper"> + <xsl:for-each select="//d:function"> + <xsl:sort select="@name" data-type="text" + order="ascending" case-order="lower-first"/> + <a href="#{@name}"><xsl:value-of select="@name" /></a> &#160; + </xsl:for-each> + </div> + </div> + + </xsl:template> + + <xsl:template match="d:tags"> + <h1>Tags</h1> + <xsl:apply-templates select="d:tag" /> + </xsl:template> + + <xsl:template match="d:functions"> + <h1>Functions</h1> + <xsl:apply-templates select="d:function" /> + </xsl:template> + + <xsl:template match="d:scopes"> + <h1>Scopes</h1> + <xsl:apply-templates select="d:scope" /> + </xsl:template> + + <xsl:template match="d:tag"> + <a name="{@name}"></a> + <div class="tag"> + <div class="tagName"><xsl:value-of select="@name" /></div> + <div class="tagHelp"><xsl:value-of select="d:help" /></div> + + <div class="paramWrapper"> + <xsl:apply-templates select="d:parameter" /> + </div> + </div> + </xsl:template> + + <xsl:template match="d:function"> + <a name="{@name}"></a> + <div class="function"> + <div class="functionName"><xsl:value-of select="@name" /></div> + <div class="functionHelp"><xsl:value-of select="d:help" /></div> + + <div class="paramWrapper"> + <xsl:apply-templates select="d:parameter" /> + </div> + </div> + </xsl:template> + + <xsl:template match="d:parameter"> + <div class="param"> + <div class="paramName"><xsl:value-of select="@name" /></div> + <div class="paramType"><xsl:value-of select="@type" /></div> + <div class="paramRequired"><xsl:value-of select="@required" /></div> + <div class="paramHelp"><xsl:value-of select="d:help" /></div> + </div> + </xsl:template> + + <xsl:template match="d:scope"> + <div class="scope"> + <xsl:value-of select="@value" /> + </div> + </xsl:template> + + <xsl:template match="text()" /> + +</xsl:stylesheet> diff --git a/dictToBundle.xsl b/dictToBundle.xsl index c5f5368..6ca76fb 100644 --- a/dictToBundle.xsl +++ b/dictToBundle.xsl @@ -1,277 +1,278 @@ <?xml version="1.0" encoding="UTF-8" ?> <!-- dictToBundle Created by Rob Rohan on 2008-11-22. Copyright (c) 2008-2009 Rob Rohan. All rights reserved. --> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:dic="http://www.cfeclipse.org/version1/dictionary" xmlns:util="java:java.util.UUID" version="2.0" exclude-result-prefixes="xsl dic util"> <xsl:output method="xml" indent="yes" /> <xsl:output method="xml" indent="yes" name="plistxml" exclude-result-prefixes="xsl dic util" /> <!-- <xsl:param name="bundle-dir" select="'ColdFusion.bun'" /> --> <!-- The uuid that will be set in the plist file. I think this needs to be unique per bundle --> <xsl:param name="bundle-uuid" select="'1A09BE0B-E81A-4CB7-AF69-AFC845162D1F'" /> + <xsl:param name="bundle-name" select="'ColdFusion'" /> <xsl:variable name="NL"> <xsl:text> </xsl:text> </xsl:variable> <xsl:variable name="TAB"> <xsl:text> </xsl:text> </xsl:variable> <xsl:template match="/"> <plist version="1.0"> <dict> <key>contactEmailRot13</key> <string>[email protected]</string> <key>contactName</key> <string>Rob Rohan</string> <key>description</key> <string>Support for the ColdFusion web development environment.</string> <key>mainMenu</key> <dict> <key>items</key> <array> <string>C8F9D7A6-D447-4C16-B566-BE46335B1067</string> <string>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</string> <string>------------------------------------</string> <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> </array> <key>submenus</key> <dict> <key>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</key> <dict> <key>items</key> <array> <xsl:comment>FUNCTIONS</xsl:comment><xsl:value-of select="$NL" /> <xsl:apply-templates select="/dic:dictionary/dic:functions/dic:function" /> </array> <key>name</key> <string>ColdFusion Functions</string> </dict> <key>C8F9D7A6-D447-4C16-B566-BE46335B1067</key> <dict> <key>items</key> <array> <xsl:comment>TAGS</xsl:comment><xsl:value-of select="$NL" /> <xsl:apply-templates select="/dic:dictionary/dic:tags/dic:tag" /> </array> <key>name</key> <string>ColdFusion Tags</string> </dict> </dict> </dict> <key>name</key> - <string>ColdFusion</string> + <string><xsl:value-of select="$bundle-name" /></string> <key>ordering</key> <array> <!-- <string>00D00AD7-3C05-46E0-B8B9-0F5CCAC04F57</string> <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> --> </array> <key>uuid</key> <string><xsl:value-of select="$bundle-uuid" /></string> </dict> </plist> </xsl:template> <!-- Formats the functions. Writes the plist too. --> <xsl:template match="dic:function"> <xsl:variable name="filename" select="translate(@name,':','-')" /> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:value-of select="$NL" /> <!-- {$bundle-dir}/ --> <xsl:result-document href="Snippets/gen-{$filename}.tmSnippet" format="plistxml"> <plist version="1.0"> <dict> <key>content</key> <string><xsl:value-of select="@name" /> <xsl:text>(${1:</xsl:text> <xsl:for-each select="./dic:parameter"> <xsl:call-template name="param-with-placement"> <xsl:with-param name="placement" select="position()+1" /> <xsl:with-param name="separator" select="''" /> <xsl:with-param name="preparator" select="', '" /> <xsl:with-param name="use-equals" select="'false'" /> <xsl:with-param name="total-param-count" select="count(../dic:parameter)" /> </xsl:call-template> </xsl:for-each> <xsl:text>})</xsl:text></string> <key>name</key> <string><xsl:value-of select="@name"/></string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string><xsl:value-of select="@name"/></string> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <!-- Formats the tags. Writes out the plist file too --> <xsl:template match="dic:tag"> <xsl:variable name="filename" select="translate(@name,':','-')" /> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:value-of select="$NL" /> <!-- {$bundle-dir}/ --> <xsl:result-document href="Snippets/gen-{$filename}.tmSnippet" format="plistxml"> <plist version="1.0"> <dict> <key>content</key> <string><xsl:text>&lt;</xsl:text> <xsl:value-of select="@name" /> <xsl:text> ${1:</xsl:text> <xsl:for-each select="./dic:parameter"> <xsl:call-template name="param-with-placement"> <xsl:with-param name="placement" select="position()+position()" /> <xsl:with-param name="separator" select="' '" /> <xsl:with-param name="preparator" select="''" /> <xsl:with-param name="use-equals" select="'true'" /> <xsl:with-param name="total-param-count" select="count(../dic:parameter)" /> <!-- <xsl:with-param name="element" select="." /> --> </xsl:call-template> </xsl:for-each> <xsl:text>}</xsl:text> <xsl:choose> <xsl:when test="@single = 'true'"> <xsl:text> /&gt;$0</xsl:text> </xsl:when> <xsl:otherwise> <xsl:text>&gt;</xsl:text> <xsl:value-of select="$NL" /> <xsl:value-of select="$TAB" /> <xsl:text>$0</xsl:text> <xsl:value-of select="$NL" /> <xsl:text>&lt;</xsl:text> <xsl:value-of select="@name" /> <xsl:text>&gt;</xsl:text> </xsl:otherwise> </xsl:choose></string> <key>name</key> <string><xsl:value-of select="@name"/></string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string> <xsl:choose> <xsl:when test="contains(@name,':')"> <xsl:value-of select="substring-before(@name,':')" /> </xsl:when> <xsl:otherwise> <xsl:value-of select="@name" /> </xsl:otherwise> </xsl:choose> </string> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <!-- handles doing the tag and function params. Takes 3 params. placement = where to start the textmate $N variables from separator = what to tack on to the end of each paramenter total-param-count = total number of params, so we don't add the separator to the last item. --> <xsl:template name="param-with-placement"> <xsl:param name="placement" /> <xsl:param name="separator" /> <xsl:param name="preparator" /> <xsl:param name="use-equals" /> <xsl:param name="total-param-count" /> <xsl:choose> <xsl:when test="$use-equals = 'true'"> <xsl:text>$</xsl:text> <xsl:text>{</xsl:text> <xsl:value-of select="$placement" /> <xsl:text>:</xsl:text> <xsl:value-of select="$preparator" /> <xsl:value-of select="@name" /><xsl:text>="$</xsl:text> <xsl:value-of select="$placement+1" /> <xsl:text>"</xsl:text> <xsl:if test="position() != $total-param-count"> <xsl:value-of select="$separator" /> </xsl:if> <xsl:text>}</xsl:text> </xsl:when> <xsl:otherwise> <xsl:if test="@required = 'true'"> <xsl:if test="position() != 1"> <xsl:value-of select="$preparator" /> </xsl:if> <xsl:if test="@type = 'String'"> <xsl:text>"</xsl:text> </xsl:if> </xsl:if> <xsl:text>${</xsl:text> <xsl:value-of select="$placement" /> <xsl:text>:</xsl:text> <xsl:if test="@required = 'false'"> <xsl:if test="position() != 1"> <xsl:value-of select="$preparator" /> </xsl:if> </xsl:if> <xsl:if test="@required = 'false'"><xsl:text>[</xsl:text></xsl:if> <xsl:value-of select="@name" /> <xsl:if test="@required = 'false'"><xsl:text>]</xsl:text></xsl:if> <xsl:text>}</xsl:text> <xsl:if test="@required = 'true'"> <xsl:if test="@type = 'String'"> <xsl:text>"</xsl:text> </xsl:if> </xsl:if> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match="text()" /> </xsl:stylesheet> \ No newline at end of file diff --git a/distro_all.sh b/distro_all.sh new file mode 100755 index 0000000..d097c0d --- /dev/null +++ b/distro_all.sh @@ -0,0 +1,13 @@ +#!/bin/sh + +./distro_main.sh + +./distro_railo.sh + +./distro_cf8.sh +./distro_cf7.sh +./distro_cf61.sh +./distro_cf5.sh + +./distro_bd70.sh +./distro_bd62.sh diff --git a/distro_bd62.sh b/distro_bd62.sh new file mode 100755 index 0000000..ea378ba --- /dev/null +++ b/distro_bd62.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +ant clean -Doutput.name=BlueDragon-6.2 + +ant -Doutput.name=BlueDragon-6.2 \ + -Ddictionary.file=Resources/cfmlBD621.xml \ + -Dbundle.uuid=4E1ABDD8-CE67-4192-9D76-1103D3639D47 \ + -Dsyntax.uuid=AE4BC6F4-4EE1-471C-B509-85E683F94BA6 \ + -Dcmddoc.uuid=6FCD2CF3-D0CE-4191-A750-BE5D5196AFEF \ + build \ No newline at end of file diff --git a/distro_bd70.sh b/distro_bd70.sh new file mode 100755 index 0000000..dc4e43c --- /dev/null +++ b/distro_bd70.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +ant clean -Doutput.name=BlueDragon-7.0 + +ant -Doutput.name=BlueDragon-7.0 \ + -Ddictionary.file=Resources/cfmlBD70.xml \ + -Dbundle.uuid=EA6D9495-D926-4EE9-BEE3-F49F63A5C5D0 \ + -Dsyntax.uuid=2B5E29C4-68BA-4F0D-9994-3970C9497ADD \ + -Dcmddoc.uuid=1C98FC52-4F0A-42D8-9AA8-F1713842EE05 \ + build \ No newline at end of file diff --git a/distro_cf5.sh b/distro_cf5.sh new file mode 100755 index 0000000..e0e2ea2 --- /dev/null +++ b/distro_cf5.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +ant clean -Doutput.name=ColdFusion-5 + +ant -Doutput.name=ColdFusion-5 \ + -Ddictionary.file=Resources/cfml5.xml \ + -Dbundle.uuid=F1E04FB5-BC5C-4F7D-8C3A-BA57840C9F67 \ + -Dsyntax.uuid=F8252600-A1B4-4A3D-A00A-E15518D6DFF5 \ + -Dcmddoc.uuid=E9D2E2D0-9FD1-4F20-AF4D-0E5E33A27C2A \ + build \ No newline at end of file diff --git a/distro_cf61.sh b/distro_cf61.sh new file mode 100755 index 0000000..88d1835 --- /dev/null +++ b/distro_cf61.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +ant clean -Doutput.name=ColdFusion-6.1 + +ant -Doutput.name=ColdFusion-6.1 \ + -Ddictionary.file=Resources/cfml61.xml \ + -Dbundle.uuid=94CAE6E0-460A-49B9-86A2-5ED54D895B2C \ + -Dsyntax.uuid=6B36B371-7CFB-4DB7-95D7-A58F4DDC2B8D \ + -Dcmddoc.uuid=9BFEC409-C77E-44E4-8CC3-FCD819461F33 \ + build \ No newline at end of file diff --git a/distro_cf7.sh b/distro_cf7.sh new file mode 100755 index 0000000..0d38c7f --- /dev/null +++ b/distro_cf7.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +ant clean -Doutput.name=ColdFusion-7 + +ant -Doutput.name=ColdFusion-7 \ + -Ddictionary.file=Resources/cfml7.xml \ + -Dbundle.uuid=7E0B6266-EF5F-47C2-97A6-C109B3ACD1CE \ + -Dsyntax.uuid=73AEAF76-C984-4D97-8ACC-F988169D549B \ + -Dcmddoc.uuid=E03CB152-F2C7-4F54-BA6A-CA09ADCEF4E9 \ + build \ No newline at end of file diff --git a/distro_cf8.sh b/distro_cf8.sh new file mode 100755 index 0000000..9c19ef0 --- /dev/null +++ b/distro_cf8.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +ant clean -Doutput.name=ColdFusion-8 + +ant -Doutput.name=ColdFusion-8 \ + -Ddictionary.file=Resources/cf8.xml \ + -Dbundle.uuid=5542B766-BF1B-4C9C-819A-555606E2B52A \ + -Dsyntax.uuid=77E00F27-5C6F-4AC7-ACF1-494D9016CFB5 \ + -Dcmddoc.uuid=2DF46A31-45E7-4DF5-B8DA-E7C6D1FB3E37 \ + build \ No newline at end of file diff --git a/distro_main.sh b/distro_main.sh new file mode 100755 index 0000000..1a15859 --- /dev/null +++ b/distro_main.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +ant clean +ant build diff --git a/distro_railo.sh b/distro_railo.sh new file mode 100755 index 0000000..f7fcaa1 --- /dev/null +++ b/distro_railo.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +ant clean -Doutput.name=Railo + +ant -Doutput.name=Railo \ + -Ddictionary.file=Resources/railo1.xml \ + -Dbundle.uuid=2E937CBE-9B70-42C6-974A-987E8848251E \ + -Dsyntax.uuid=888FB6E0-4CBC-4521-A51C-3D03AAB85F01 \ + -Dcmddoc.uuid=632D2425-1F06-4944-9712-7EEA5FE7AE54 \ + build \ No newline at end of file diff --git a/doc/.DS_Store b/doc/.DS_Store new file mode 100644 index 0000000..28eec92 Binary files /dev/null and b/doc/.DS_Store differ diff --git a/doc/style.css b/doc/style.css new file mode 100644 index 0000000..d22bb96 --- /dev/null +++ b/doc/style.css @@ -0,0 +1,90 @@ +body { + margin: 0; + padding: 0; + font-family: helvetica, sans-serif; + font-size: 1em; +} + +div.tocWrapper { + margin-left: 20px; +} + +div.tagTOCWrapper { + margin-left: 10px; +} + +div.functionTOCWrapper { + margin-left: 10px; +} + + +h1 { + padding-left: 10px; + padding-top: 10px; +} + +div.tag, div.function { + padding-left: 20px; + padding-right: 20px; + /* background: green; */ + margin-bottom: 50px; +} + +div.scope { + padding-left: 20px; + padding-right: 20px; +} + +div.paramWrapper { + display: block; +} + +div.tagName, div.functionName { + margin-left: -10px; + font-size: 1.5em; + margin-top: 10px; + margin-bottom: 5px; + padding-top: 3px; + border-size: 2px; + border-style: solid; + border-width: 1px 0 0 0; + /* background: red; */ +} + +div.tagHelp, div.functionHelp { + padding: 8px; + margin: 5px; + border: 1px solid silver; + /* background: blue; */ +} + +div.param { + /*float: right; + clear: both; */ +} + +div.paramName { + display: inline; + font-weight: bold; +} + +div.paramType { + display: inline; + font-size: .8em; +} + +div.paramRequired:before { + content: " - required: "; +} +div.paramRequired { + display: inline; + font-size: .8em; +} + +div.paramHelp:before { + content: " - "; +} +div.paramHelp { + display: inline; + font-size: .8em; +}
robrohan/coldfusion.tmbundle
1c58c2d2270dfa4cd37efe63101f564f31275b3c
Trying to get the default behavior for functions to be a bit more enjoyable.
diff --git a/ColdFusion.bun/info.plist b/ColdFusion.bun/info.plist index 6aee8cc..57a0c0c 100644 --- a/ColdFusion.bun/info.plist +++ b/ColdFusion.bun/info.plist @@ -1,607 +1,69 @@ <?xml version="1.0" encoding="UTF-8"?> +<!-- + NOTE: This file is here for reference only. The real plist file is generated by the dictToBundle.xsl file (in order for the UUIDs to work properly). If you want your changes to show up in the generated bundle, edit that file. +--> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>contactEmailRot13</key> <string>[email protected]</string> <key>contactName</key> <string>Rob Rohan</string> <key>description</key> <string>Support for the ColdFusion web development environment.</string> <key>mainMenu</key> <dict> <key>items</key> <array> <!-- <string>C8F9D7A6-D447-4C16-B566-BE46335B1067</string> <string>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</string> --> <string>------------------------------------</string> <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> </array> - <!-- + <key>submenus</key> <dict> <key>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</key> <dict> <key>items</key> <array> <string>0AF4E3E4-8638-4EAD-B182-A4FE571E9974</string> <string>38EB1CC2-4A1A-4C37-9D69-19D81129C5DC</string> - <string>E0D7DCCA-9801-4DD5-9C26-3B607BEF7135</string> - <string>241129A8-4AF3-4005-B276-6F431B5CB3F2</string> - <string>8AE48664-E323-4DF9-BED2-CE700CAC7C15</string> - <string>08392E18-5D55-41CB-BE64-7B091492E7BF</string> - <string>9AEFE392-91BE-4968-8FF8-8A2C9D51D4CC</string> - <string>67423190-2729-4C30-B10D-51B7DC3FAB85</string> - <string>1B072993-0FFD-44B7-8C6D-3F9D60AF9E7B</string> - <string>B8817D6A-B326-48F9-9E35-B28778A79412</string> - <string>157C15A0-D535-4EAB-8173-6D6EB0906173</string> - <string>0E400696-4C11-4072-9DAD-7BFF6F7789BE</string> - <string>5A2941B5-2D73-4348-AB92-932665EB6E1D</string> - <string>902C51B4-E4E3-4B2C-BA03-769FC6AC0867</string> - <string>5CF87863-EBA1-49BE-AB51-016A2D0FDA80</string> - <string>A72AC858-A593-4758-894F-266F9925990D</string> - <string>6E59F119-65E3-4D1F-B393-121208A9A83F</string> - <string>E336E487-B1EA-449C-9B32-4C5994136CEA</string> - <string>90B1EE50-DAC5-4748-8415-5C3ABB38CFD5</string> - <string>784AAEB3-2367-4275-95E0-DFDBE61E9423</string> - <string>D5310F63-357F-4E8A-9583-26F569D309EB</string> - <string>1ADF5606-9DC3-413F-8BC2-5E54E7BAC4FF</string> - <string>28364618-9329-4501-98EC-852D28D2F59A</string> - <string>EA2AA961-32E7-4B4B-85C8-0F458AC6E671</string> - <string>A14677C7-FB24-4A35-B9F5-F764C2EFE00E</string> - <string>5736162D-BDF6-4C94-8F3C-8F4CEB38E349</string> - <string>C6C27604-1D24-4EC3-B40D-BD1FF6196DF8</string> - <string>96D4FDBD-4A7D-42E4-BF7A-AB366E22758B</string> - <string>E1BBA1F0-05C7-4EA0-87BA-FB0FC5D1CAED</string> - <string>C8C2C389-AEE0-4CE2-8944-A7EEEFB9B680</string> - <string>36F4B163-2ACD-48F1-8E72-365E54EB7811</string> - <string>5D0E9DF4-6631-419C-AEEE-7710EE30502F</string> - <string>0A3097F1-36A8-4009-8501-CC5B9349072E</string> - <string>C28091B5-3245-4E3C-BC49-38AAB093D00F</string> - <string>1D9BEE6E-907F-430A-BD62-2DF38A454B3E</string> - <string>B8DC9CF1-AFF5-44E4-B9A8-42093D829889</string> - <string>BEDB5CCC-7FF1-4C78-8169-2B58BFB2C449</string> - <string>E6EE6F14-372D-469B-B31F-827A54CFC5E3</string> - <string>DB5DE93A-DA9A-40E9-B469-EF8337A11CBE</string> - <string>63B626CD-2818-42F2-BD90-DE112A8DEF7A</string> - <string>5C3D7157-DFC0-4762-B059-C10F1A098089</string> - <string>BD84E1FB-DCA2-493E-887E-1A1330DD6EA9</string> - <string>CED5A340-3643-4F34-A8ED-A9FB99008300</string> - <string>AB4A8782-7466-4B5D-A180-96E0BD19C050</string> - <string>D01E4126-187A-4275-8583-DFA44FE3BB3C</string> - <string>F9725187-DAE2-43BB-9209-BAF4F709AD72</string> - <string>C83F3775-A62D-425B-B05E-C6A58C929399</string> - <string>6674FAC2-9201-4D0D-BAA5-E35D64BDADDC</string> - <string>53E1E9D3-8F53-4CFE-8ADD-83AC13969D24</string> - <string>415DDDAF-1163-49E7-8D5B-3B6CD1A27A06</string> - <string>B2FCBECB-D1E0-4BF4-B046-5A9C4A6475F9</string> - <string>601BA2FE-EA4D-4B9C-A8EF-646A9E9626DD</string> - <string>B14D6A84-2B4D-4FF8-99CB-E2B41B0E00BF</string> - <string>29745C05-70EC-418A-A7E1-E60EE6042A95</string> - <string>2FB6FDE3-F8F0-47A1-AE6D-AA3895A489CD</string> - <string>0B69D306-8DF0-4494-87AC-B8E92091E0E6</string> - <string>9AA75F85-02C0-4006-9D95-F7EC2728A050</string> - <string>192D1402-A2E5-43F1-B0C5-990853DB5D98</string> - <string>8BBB6187-A1D9-43AF-AF72-CDF3BB8B0A76</string> - <string>DE1C603E-D791-469F-99D3-69E17B9B41EB</string> - <string>FA01E47F-EB01-4FE1-9EB6-96FDEB923E70</string> - <string>AA6262C5-CA32-415E-B666-D2FBF93E0905</string> - <string>80B9754E-47ED-46D6-8BA5-80744B0FBE4B</string> - <string>9A1343CB-5E9E-45A2-8D21-B4959C412B6E</string> - <string>622A22FB-207B-4322-BC6C-C2B3D605AF00</string> - <string>4DD466D2-0B15-4E06-8446-5AFBFC8B4128</string> - <string>183709C1-9414-4A25-89FB-A0D9A7E59D27</string> - <string>35060F61-EF40-4046-BF12-1AB2748884A1</string> - <string>44EA1298-2450-498B-82F6-1BF1BC1FFE59</string> - <string>29486C8D-7A9A-4EE0-B6A3-34C77A7D253E</string> - <string>7F70512F-517F-4361-89ED-13E8C3BD98F0</string> - <string>2A8760F9-6ED1-4066-B996-5E490B5A17EF</string> - <string>9187A792-54F4-4773-A2D7-EB5D207D1A54</string> - <string>F0AFF0A1-90FA-424F-A6AF-6EA6EC1BB225</string> - <string>026FDCF1-E739-42E4-925D-59D80EE7FF05</string> - <string>50182FB9-0179-4CF6-9AD7-4E7BC725C594</string> - <string>3B19D8BC-5389-4263-A539-160170F7DFB1</string> - <string>B096E910-EE96-4E63-BB46-EB12616C80F6</string> - <string>08743309-6431-44D2-8A38-926516B04BEF</string> - <string>A4876D40-55A7-44A0-9CDD-BCF62A621FC3</string> - <string>5C441A88-2F12-4C54-83F8-81A62F735F88</string> - <string>FDDBDC40-D1D9-4981-92DE-30CA475BC8FA</string> - <string>3C93CAC9-0DC3-4371-8E5F-2727B0A282BD</string> - <string>6F5A4D8F-DE7C-4663-9D39-7BF23D84769E</string> - <string>75FFC09D-CB71-49CF-AB01-3DA8C44F29F3</string> - <string>97DD90F8-5334-46A0-B973-C59F357D6C31</string> - <string>3ED1297F-4C77-4187-9356-4262D3F28625</string> - <string>F36E8F58-CDBD-4E42-A64F-9D05BE2D49B9</string> - <string>1B6D6622-49BD-4EAB-B521-B3D1ACF2E4B1</string> - <string>E09B46CF-DDE0-4B40-B7AF-93C005F23BAB</string> - <string>A607B362-68CB-4AE3-BE72-575EB7CBA55A</string> - <string>A57CC7BE-F39A-4B64-908D-44EA058C294F</string> - <string>0C5234DB-A0F6-4BE2-AF28-5276ED3F81BB</string> - <string>BC74CDF9-65E1-4FD0-A939-110CF53F3F67</string> - <string>D6CFEC97-357A-4EBD-9D95-F89FECD4ED66</string> - <string>293B3EF2-892E-4FF9-BB3B-82AE01FFA38D</string> - <string>24AEB6C9-9CDE-478C-9C08-5CB1825321AE</string> - <string>4417C4C8-F581-41FC-96FF-76A28A1F0640</string> - <string>BC022681-5DE4-4E5C-8638-93EF655F7B0D</string> - <string>47BD7B3C-4316-4C5B-AD7D-596D90D64A7C</string> - <string>ED205418-D60B-41CE-9942-6855C78C65F6</string> - <string>AEA7BB76-4231-41DC-829C-D093F7BF28E5</string> - <string>F29A9DA7-B58E-4839-8664-2C99C5679384</string> - <string>7423A717-6340-4CEC-9151-2B882D052CB9</string> - <string>6E621AA5-5304-4DCE-82B9-820FDB78C5FE</string> - <string>21B96169-6556-4436-B3B2-4556A6372567</string> - <string>7A62D445-BDCF-4C67-8B71-35255FACC231</string> - <string>9B25BE9A-A2E8-4BA6-A1CD-A545C6A3AEDE</string> - <string>AD74D8BA-A774-4748-BF7E-22A6E94194ED</string> - <string>8743E910-AD98-42C7-AC9D-4EBD26B54456</string> - <string>5EB9976E-F76E-40FE-828F-22B393BA59AE</string> - <string>8A82A0E0-7396-436B-A3FD-46680599A33A</string> - <string>B36FA4B0-F6AE-4489-97D1-54BFE773A560</string> - <string>281422A7-AF82-45BF-8707-4242A22FA908</string> - <string>CD089D33-F3B3-4BC8-9650-B7CF29B877BF</string> - <string>18A3925F-BF0F-4FAF-B45C-C02B2D4C4CB1</string> - <string>7188A872-4A9F-4A05-ADCA-46D83E911D2D</string> - <string>6322FE39-5B27-49EF-A632-A6073EDCE0C4</string> - <string>BEC86CCF-C220-4B07-9ACD-320238D1FE48</string> - <string>1F61F24F-166C-4D2E-98B0-7BA454B21619</string> - <string>5BAF7E27-FEAB-43E0-899F-ABE9DA500FD0</string> - <string>EE49E017-4812-4CAA-8CCC-29DAB3BE7B64</string> - <string>97F31F3F-B885-4DE8-B784-5582990C21CD</string> - <string>5D2DC339-C6E8-4919-9500-DD24DC9D2F73</string> - <string>9E6E0847-D0DB-435D-A129-CA90BE6B9210</string> - <string>82B42D60-DC77-47AA-B433-14969E2A2CEB</string> - <string>DE1DB107-EC48-4128-B400-203B72AFD40F</string> - <string>2051A0AE-51E2-413F-9CCB-92826FCD5C99</string> - <string>2DD711BA-8C2D-4AF4-85C2-C42733743D0A</string> - <string>5C998560-6284-4F59-A6F9-420962E130E2</string> - <string>5DBF4A9D-7C3E-4FAD-B6DE-16AB145F081B</string> - <string>C3F1BC8E-892F-4FB5-8A63-F8225B42CCFC</string> - <string>3B7767FB-E117-4543-B27C-C178D5F451DF</string> - <string>618D41F8-8A13-42B6-9000-551AA2DF9FA3</string> - <string>ACB55DF1-EE3F-4B20-A3CA-3DC63018212B</string> - <string>466D3581-0875-4E99-952A-0650CB84D33D</string> - <string>17CFEC94-0BF5-40CD-97DD-79A2CAECB041</string> - <string>5C46558A-599C-427F-8A7E-0343F1BED079</string> - <string>D2675FE6-79EF-40C6-A864-A5C6F092BA4C</string> - <string>D61CD41D-9838-4169-A754-424345AC4601</string> - <string>4C31384B-2B27-4C39-B2BB-CC2CA57B659A</string> - <string>02261555-8147-43DF-9D49-AEE4F58E1619</string> - <string>3757F0B8-F3B0-4272-9F6E-8968CE670387</string> - <string>3514ADDF-C60D-4A16-9346-11EB7A2AA61A</string> - <string>90E0EBD1-EC9F-425B-ACC3-06EFAB5F1F69</string> - <string>41ED9831-365B-4D4F-AF8D-2864343E271F</string> - <string>696A8BD3-EF4F-4A4C-A264-93BE6781D657</string> - <string>40051E46-ECE8-4A07-B600-934A3B482EFC</string> - <string>2016AF2A-1AC1-45A8-BCA0-A52F23142863</string> - <string>FD148128-FF2A-4CFE-99F6-FF43653FE8EA</string> - <string>6C79157D-36F9-4F91-B012-BDD27622FF9B</string> - <string>E45A3C54-88D7-4E4A-8092-56854FE825BE</string> - <string>49443738-7978-4865-A1AC-7358A0BEE2DE</string> - <string>C17555B3-A84A-404B-AECA-3F11CA9ABF0D</string> - <string>22ECD416-BC42-4C13-8BAF-F435A144A56E</string> - <string>E0363D86-A148-44D2-9AF9-45A2A57D1676</string> - <string>9992024A-E07D-4E29-9B35-F85038E890AF</string> - <string>23E6B8AA-CA8F-4CCC-BC29-76A027849595</string> - <string>28FE5A03-F962-4ECE-AF92-EE3436D20664</string> - <string>0D55F7C2-16A2-4B78-B390-EF780FF0F2EC</string> - <string>D9676E4C-3E0A-4886-8F2A-03E25DB4D44C</string> - <string>2C83D486-C0A5-4493-8562-BEA824BAD2D7</string> - <string>817F3C02-47AD-4553-9DE2-BDB0EC97BC9F</string> - <string>FEF3A4E6-7B4E-47B6-A529-ED41EDA41002</string> - <string>917BA410-EC71-492D-8472-A3C2CED279FA</string> - <string>6C78FA7D-0B84-4E9A-A063-77490073E99F</string> - <string>0F018E42-BB09-4631-B11E-EDDD267C8DFF</string> - <string>068FD2EE-B721-4DE3-A4E2-F98476C0530A</string> - <string>9A231D17-D36C-4081-B1EE-E3F5016040C1</string> - <string>E648C975-48FA-4818-89B6-34913675E41D</string> - <string>E7FD5C33-5516-4DB0-A553-B832515D17D4</string> - <string>F3102771-3AA4-492D-AD42-2FDB4F686662</string> - <string>C3AE011B-75E2-45AF-B427-864997717FE2</string> - <string>519D474D-FE82-4419-9D5F-AA88D817EDE6</string> - <string>6816281D-E43D-4DEC-AC2B-0E0756A00EEB</string> - <string>25ACCCC1-401C-4084-80DE-6CFFF6FDEA20</string> - <string>41E4F63F-C59D-4712-B29A-9CC83D717469</string> - <string>63CA1E9E-34AB-4EDD-B6CC-16C22EA5B777</string> - <string>2B8BC0E7-93C3-4DE2-957E-8212F6E373C3</string> - <string>19400E23-B260-4E85-AFFD-109708545A80</string> - <string>312DD333-8664-4C27-9C67-ED8B285579D4</string> - <string>9BDE4AC0-BEC2-4585-AEC7-AD60767AFBEE</string> - <string>9D47F8B3-B009-418B-8AB9-0E72D33F137D</string> - <string>79EDA618-F9E9-4A72-8A7F-DDC0D6826C19</string> - <string>0BA580D0-B978-48C0-8CEB-F78042E9F58F</string> - <string>AE303AF0-FAE2-4C2F-A5BF-0745D3161289</string> - <string>228F7B63-E8C8-48EF-9613-A32CAB3FF100</string> - <string>CB454D76-239A-40D2-B194-43CA6DDD9B8D</string> - <string>CBEAE712-0FC9-4210-B157-DC5C264BFCBF</string> - <string>8F41DFB0-285F-4FA7-A21D-210832BEBD60</string> - <string>81541C90-0980-47A1-9B9B-9F3E750016C7</string> - <string>E651A0E3-0EC3-45AC-B7D0-92E2DAD1F733</string> - <string>8D4E0C06-8D06-4871-9D92-5C72B18A5562</string> - <string>D455BE22-95B8-477F-BA2B-22C8C33D2C85</string> - <string>1262430C-CE62-4585-9EFC-7D5D001C5F24</string> - <string>5A00FE89-14AB-4DCA-B601-5FEA6C36F8F4</string> - <string>F82AABEA-89D3-4DE6-8B6C-3B7BDC194667</string> - <string>DEB3845A-FE19-4B41-84AD-EAA44A4BD1DB</string> - <string>3B74EAA8-B431-423C-971B-09349375FE3E</string> - <string>FA705D08-0DFD-4C3B-AB79-FF7719E9258D</string> - <string>C02F0BE6-CDE7-489F-8B1D-C63CD15AEEC6</string> - <string>2559432A-5071-4C85-B71B-A546326C4DE6</string> - <string>2358C3ED-39E9-4CB1-BBE0-C2C0419F4E9C</string> - <string>C91A69A3-2ECA-4F98-8777-E142F6777683</string> - <string>F78D0262-1B71-4AD6-8BB5-C2E9DC9BB083</string> - <string>8FC4AFD0-98E2-414D-8F80-ED36E5BD977A</string> - <string>80ECE03A-C2E3-4334-8F7B-2A2ED7BC80A7</string> - <string>0A20DB84-AAEF-4B95-A19F-18D6F3694798</string> - <string>31B2DCFD-1049-49CF-BCA8-FAE5D0D4917D</string> - <string>DDE93618-33D9-494A-93F0-1E0CAC672042</string> - <string>DD2F9E4A-E204-4CEF-ADCD-18B523A65966</string> - <string>44379253-BF02-4341-8BB2-B40CD39ED593</string> - <string>DF3F5402-8B88-40D3-81F4-B960A6174610</string> - <string>C22A5FC3-65EA-4234-85F2-2B43DFF811FF</string> - <string>041E3434-05CD-49B2-BFC3-4E3BE5643A65</string> - <string>829C9A8E-323D-44DA-BD6F-72AC150755A1</string> - <string>E55FC014-0F85-4A3E-884D-F7C4F3179659</string> - <string>C4D060C7-FF47-4799-AD06-108B3A757EB6</string> - <string>FB98EFB0-2C9C-4037-96CF-5C0644041281</string> - <string>8330E508-BE78-4713-BF73-2C8B08C02883</string> - <string>2452CEE2-65EC-4FF1-8E1E-C77876F1D14E</string> - <string>1B854256-5B23-4FCC-8367-2330D94D200E</string> - <string>BCF434DF-79AB-4F95-83E0-8D9B0163956B</string> - <string>F93D53FB-7669-4780-B53A-16276844A5BD</string> - <string>89150D95-04F4-4A3B-B885-20A9C95E3FBA</string> - <string>4F0429B6-0FB1-4CF6-BCB8-6350EBD89C35</string> - <string>998B082A-A679-4494-B66C-69AA8256E4D2</string> - <string>E03C0C8A-5CBA-4654-A4BD-EB6500901709</string> - <string>62B6DE6D-751C-4599-8094-6F3EA39F2517</string> - <string>ED3D3507-B8D9-4A83-88B7-CAD0F46A664A</string> - <string>958C7148-B01A-4FE8-AA42-88CADB026CBA</string> - <string>DEF118D7-4325-45E5-9AFC-77C80839A76F</string> - <string>AB98AFE4-E946-4CC6-B453-B6E478590152</string> - <string>3B4924D7-1FCB-4D61-85C8-63E69BFC808F</string> - <string>4640A976-0C9E-45AA-912F-AD2EEF351E60</string> - <string>5A3FFFCD-C7A2-457E-8D6E-151680293EBD</string> - <string>CA44FB3A-353F-418C-AC80-1DC89F4D65BF</string> - <string>0CC8642F-3BE7-45DA-86CB-179A4AE9C264</string> - <string>FD813CA3-8050-4E6A-815A-9F083D80A2F8</string> - <string>28CCC198-2A33-4677-8B8E-4774BF542C54</string> - <string>9038D5E1-01AC-41B8-BEB2-681702E589FF</string> - <string>8B3912D3-1C28-4DF2-8883-6C4B05377278</string> - <string>4C10EFDF-A3CE-48E3-8B9B-5174B0163EC2</string> - <string>24F07D3F-9B21-4035-A519-CF84DA5DB543</string> - <string>A0B83920-09E1-4361-8597-5B05BA1A23F9</string> - <string>5C8F03CB-AAD6-42F4-B20B-705D101354C7</string> - <string>C25BD8B9-99B8-429E-9499-BEA2C3C2F8C0</string> - <string>849C7A84-7E2B-4420-AE9D-FEFB11CA4A3F</string> - <string>67A5B7BD-0E56-477D-A38C-B101A2719988</string> - <string>56525EF4-4A5C-4415-B2D9-9D135CA32157</string> - <string>9C179D97-C855-420C-8689-642EB11AC767</string> - <string>F0FB9A33-FFB9-43D3-847D-AEF559D86B68</string> - <string>7B0D2A4C-CF10-4985-AEE3-212D3C479C38</string> - <string>ADA257DD-BB15-4CFD-BB53-55C7E1A30365</string> - <string>7F5D11B3-45DE-41E6-B5D1-71F370315500</string> - <string>92F58CD9-AE3E-4553-BA7B-B10FD1376B2F</string> - <string>259B5FFC-6CB8-4141-8270-CCEF88550A04</string> - <string>C953538A-5B40-4D20-B920-EE242B415A21</string> - <string>C6B47D42-9614-4C5A-A862-81A4E59EFC55</string> - <string>AAC6EB2B-2BE9-4CF5-995A-09C4632E5809</string> - <string>F8CE823F-8C57-4DAF-957A-C2370F49EB8D</string> - <string>DA3FB6A9-6C8A-47F1-932B-76E9AC9FF4A8</string> - <string>30468398-BDF8-4221-B8C1-108D660B5462</string> - <string>317DCAFC-B419-43D1-9516-CB020D48FE08</string> - <string>7FFE3035-50A2-43BC-9A6A-D3392DD711DA</string> - <string>67FC60DD-74BC-40D8-96F5-77E90D45E820</string> - <string>BE836A4A-003B-43B6-845D-E19A813D7E57</string> - <string>523CD084-3B13-46DB-AB6F-8961EC5914CB</string> - <string>5FA14C8D-B9CA-4635-B0ED-A9F6E8133716</string> - <string>DF07EEE5-5D1C-4226-921C-862390ED60D9</string> - <string>02288997-F2FE-4F78-86B5-7EB341820E31</string> - <string>09B68D0D-9DF3-4183-A57C-12352C1F992A</string> - <string>B040F5CB-43F8-442C-88D7-0C8B8FDB8989</string> - <string>BA93AEF3-2AF9-4987-820C-71788DE2DEF3</string> - <string>A28980B1-0C97-4C38-AC73-788170AE1D32</string> - <string>4A1ADF4A-5EDD-4D82-8141-B91E66BFD80D</string> - <string>6D88583E-821E-4921-AABD-997C5738F059</string> - <string>EC3B9C82-CD02-4EDE-B292-457CC8774E41</string> - <string>AE66DCD8-09E8-4EED-BAA6-031BACF237A0</string> - <string>A56B5F64-EF48-4000-B7D4-78B6C0E04CC1</string> - <string>11346CB0-A4DE-4DFF-BB31-E2D4DCDD14FC</string> - <string>206C70C1-010B-43F9-BC75-0CA766DB2DD3</string> - <string>B97E295E-62AD-4DD6-9E2D-625B016CC5AA</string> - <string>17180447-13E1-4330-A9DD-18D9DD6B8C2B</string> - <string>DAF8DD98-B342-4746-B017-EA3AA8861EE9</string> - <string>2FD9FC81-619B-4256-AFDB-4E1B4EB3B479</string> - <string>65714417-FFB2-441B-8A92-E660882D3A9B</string> - <string>CA71EDF5-8BDC-4CEF-A25B-91AD55BA9C07</string> - <string>A0DFAD24-FBA0-4867-841C-2DDA8B863454</string> - <string>E1F8DF31-6867-4D7B-96C1-842A860C3CF1</string> - <string>A8EEDB00-F4F2-4EC3-AB22-14A5E331D89C</string> - <string>C4BE4DC7-045B-470E-9BEE-6438C19D6D51</string> - <string>E411CA38-BF07-480C-AA82-864F2AF548B6</string> - <string>300C9DE5-E673-4A8F-B678-8A86E6AC24F6</string> - <string>31A1B000-84FE-4FC6-B941-B2080F6908E9</string> - <string>4554BD19-8A33-460E-BDC8-B2E4525D508F</string> - <string>48BF60D2-E9C1-4F1E-9FF8-BB08FC6F7A32</string> - <string>B09C244B-F8E0-4069-A4FF-5029DA586F72</string> - <string>6D3C12F2-DF3C-40F8-B47E-381FDD0A981A</string> - <string>60F3E813-2319-4310-9985-B7B50C0A9A33</string> - <string>32B99607-5DE8-4560-8079-2D84CD4E0001</string> - <string>F34A2296-6FF0-4090-ABAB-2C9D6F7EF482</string> - <string>14E4A176-FB73-41C7-BCF5-B11F90733CE9</string> - <string>D000FBCE-5C70-45C2-B9D2-86C42500568C</string> - <string>6DB8C1A2-09F5-4C4E-B4D8-A75F5E3D76FF</string> - <string>07A7E990-237A-43F9-A87E-8EA14DD81333</string> - <string>C245FB6E-95C2-4D6E-935F-A7F470328E49</string> - <string>0528B454-B8BC-466B-9AF9-BE68BC77E4E1</string> - <string>3D9D15C5-2E00-4332-9169-FC35542D1BEB</string> - <string>96265680-CFE2-404F-B614-B83B78AC1A0C</string> - <string>245A194E-803F-4951-BF63-19D639AA99FB</string> - <string>4B02989E-5D1A-497D-8FC1-561E4F2B67AB</string> - <string>9CA961D9-F34C-489F-865A-EB20A896C0F6</string> - <string>0FA5ADFC-C4D7-45D8-B745-2C0BC538179B</string> - <string>696428FC-070E-4D23-ACFD-0469CCC70079</string> - <string>2EDD4802-B07E-4CC2-9A88-B563FF05146E</string> - <string>286B13D0-E6C9-423C-B593-CD4B59A87E8F</string> - <string>041AC446-491D-4416-8E14-E60C8018A0D5</string> - <string>EB8C4DE1-8A2A-4C1B-AE5D-57D3FC8281CC</string> - <string>5BD2B7EB-5452-420D-BF49-B33C1D4E8706</string> - <string>268F708E-DBD4-4E38-9194-7063950783D7</string> - <string>DCAD363E-492B-49FD-B84F-43A3F77118CD</string> - <string>9072A654-06FA-42D6-950D-90E33975B2EB</string> - <string>3F07F52E-724D-4D8D-84E4-D4E87220B020</string> - <string>9DE5A98B-BEB2-4F3E-997C-4851CDAD76C5</string> - <string>FFADDBFF-B24E-4C06-8C4C-B28F6BD42349</string> - <string>538BB22C-E30C-45E4-92D1-F837360785AF</string> - <string>40BC17A0-BC89-4D08-A1C0-A54C85E90B46</string> - <string>509BDA8F-1AE1-4B62-9E5C-3742AE06167B</string> - <string>3F56DF3C-E73E-4133-B4D0-6EA5926E61B3</string> - <string>E50E3BBE-8581-4EC4-8875-717CA123463E</string> - <string>4E3ABBC1-20D2-4D0F-BC10-A128F85AD5BE</string> - <string>BF26D328-E8B2-4255-AB7E-E139FD8161CE</string> - <string>087457F5-B8B2-4673-8E60-92430D951D4C</string> - <string>A79C2E63-7CBD-453A-AD1A-B4B15A554C6B</string> - <string>8FC0283E-CE94-450F-9560-9990FB253D95</string> - <string>3FA1DAF0-1259-41F5-B642-872D9FD60297</string> - <string>21ADF248-F14F-469F-956B-14251B78B83A</string> - <string>92CA447A-F1ED-4C5A-B999-DFE13C587B8C</string> - <string>4F173886-8EF8-422A-A368-8E2F1B3699C0</string> - <string>FA4CAE63-B259-4A38-943B-88F1444835DB</string> - <string>452C6FF5-FF58-4799-841F-786BB2386B5C</string> - <string>12C986E9-3511-4179-AA1A-204BF3AC0EBB</string> - <string>9C53FE15-1C26-41B5-8ADE-EA902A7FCD89</string> - <string>606B7B7B-236D-42DE-AF65-5C9CBE79EDF5</string> - <string>C9DDCAF9-7A94-40B8-A355-17CBFD9FB0CB</string> - <string>80797385-06D3-45A6-A034-8C5BE53A5419</string> - <string>B8181ACC-5FBB-4813-BCBD-42326F575D16</string> - <string>C1E197A3-22AB-4EA7-8D06-E53478B70CD6</string> - <string>6D8B302B-3980-4B6D-AB18-0642220A1D09</string> - <string>4B4BAF15-6DDF-4AEC-A949-C09DF23D3A0E</string> - <string>70B7E6F1-FB81-4741-87D7-6E2CDBEBE6CA</string> - <string>2A358D34-E286-48DB-8FE4-34957124FE4B</string> - <string>F99266AC-C47B-4662-8140-91FC9CD83CD1</string> - <string>1F895B4D-8226-4945-9AFB-7680E54A8AF6</string> - <string>0CABE9A1-3E50-4516-9EE2-2189D1D87724</string> - <string>6DBA82BD-A1CE-40CA-B200-23E82562ACB5</string> - <string>956A0059-FFF9-4B14-9072-9B66B8D85BC7</string> - <string>65E81A15-9D95-4CE8-B2D1-9952FEF5226F</string> - <string>37710819-E241-495B-8EED-4FDCD9BE6A22</string> - <string>229077E7-4284-4085-A449-3C5AA8DCF41B</string> - <string>710BC149-0A06-48FE-87A7-4CABA810A519</string> - <string>A8B0343F-CD2C-41E7-BFE5-133C9AE9675F</string> - <string>A67CBED1-95F6-4920-A8D7-E84E650520ED</string> - <string>56173E05-CA6A-4773-AB05-050A3BBF0F49</string> - <string>40D70647-3C75-4588-9CFC-3448A881F79E</string> - <string>67D98396-31F6-4821-BF31-F75F08A92850</string> - <string>7E41534A-A1FF-4214-A106-2B721FB1A920</string> - <string>B01C3BE2-956D-4E5A-9DE0-2FA6B544DA25</string> - <string>96F76523-E10D-4366-BFF0-918D22BA37E9</string> - <string>DCBE259C-2268-4194-A4FE-03E53A232FBD</string> - <string>F61A0D68-C33F-48F6-B045-B1B3C4EF9525</string> - <string>B3617124-733D-47EC-9B2A-FAD4C0397831</string> - <string>BD44D578-30A0-4ECF-A8E2-4A23C36BD8DE</string> - <string>8AF8F6D9-32FD-4AAB-8453-7A2FDE3FD382</string> - <string>4AEAA48E-D914-4EB4-B917-01D00D0C8E0B</string> - <string>1CF0F70D-B223-4B80-8454-4AEC0B5A10D2</string> - <string>7830F906-A21D-441D-BA1D-E37635247542</string> - <string>085B8E6C-388F-456F-882C-B8D3392D61FA</string> - <string>A75D991D-240C-43AA-B9A6-553AC44F76FA</string> - <string>53B9B5E7-D897-49E4-AEEC-DE94F781AA2B</string> - <string>6B126A42-3320-4978-8ADF-F53C600B5795</string> - <string>00DA1390-C91E-4583-B83B-CC16F8892239</string> - <string>EC7BC99A-B82D-43EC-AEF2-8EB54041CDE6</string> - <string>3B195EF9-CCC3-4B2D-91D3-15D514E5F4BF</string> - <string>6521B870-750F-4109-8BBF-2910D584C525</string> - <string>16F25A48-3166-4E7C-8F80-DC9E61C65645</string> - <string>018DC512-CE52-4DCC-B556-DA3A9AD96FE6</string> - <string>94993BC1-CB55-4F02-9705-70ABCED8CFC9</string> - <string>5622EC10-8A81-4C9F-87C3-E3B6A9B4D96B</string> - <string>498615E3-E82E-4CD3-A526-EBAE9F68C7EF</string> - <string>217C9FA9-BB27-403B-8CBD-659B64FA6CF4</string> - <string>102E8B00-3629-43A3-A2D4-864C6CF0CD32</string> - <string>4B01C66D-8A74-4433-A07D-8FE705C7A352</string> - <string>9924DCE9-8C1C-4CAE-B232-E9FD07E1B53E</string> - <string>9A1B4C8F-EC35-4F05-8AB0-8122EB4B9A93</string> - <string>01E0876B-4D91-49AF-937A-7EC39DDDEE79</string> - <string>774B14A7-EDC4-4855-9915-6AB8B15D2F68</string> - <string>D8D50F69-36E3-45DA-807E-29D1E5914DD8</string> - <string>1CFD7E53-FFF7-46A8-9149-49E9F5088E55</string> - <string>3E572472-BBF1-4DDA-AFCF-D52B95B0ADFB</string> - <string>EBCC36A0-38E4-438D-BB39-6D3AC690C8AF</string> - <string>4158361F-D366-4BAA-8CC5-DC46AD449229</string> - <string>EE1507E5-F01B-4D73-8EE6-CCFECE98C3F4</string> - <string>C280847F-1A0C-47CC-9EE5-168B9973A8BB</string> - <string>F54727CC-8F88-4D17-AC6A-B5E4C8AC872F</string> - <string>FA9F757A-290F-4E33-92FC-9E6214113E58</string> - <string>C772C456-6B38-4987-87CF-D10486D185A9</string> - <string>1A402F7D-1B17-4090-BFD6-42BD426FF0A6</string> - <string>A80FF473-4E66-4DBF-89E2-3BC1AFC00A0D</string> - <string>6A325FC2-6C57-4B2C-9326-3244EAC96A47</string> - <string>87D35E2A-FCC1-4496-9198-8BC85C16E97F</string> - <string>63538655-54A5-465E-9E8D-9F57ABA5E40D</string> - <string>BA7CE17D-DDC3-4394-808D-6D58588C329C</string> - <string>EF439919-653A-4250-B8B6-9337DA8DD851</string> - <string>0A58EA58-3BBC-4A07-80FF-366933CF24A7</string> - <string>B00CB7C5-C864-493C-9C6E-DCF759CE3B6A</string> + <!-- etc, etc all the uuids for functions --> </array> <key>name</key> <string>ColdFusion Functions</string> </dict> <key>C8F9D7A6-D447-4C16-B566-BE46335B1067</key> <dict> <key>items</key> <array> <string>97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14</string> <string>862EDD04-D606-4EDB-8D01-425D8024CF1B</string> - <string>0AF4E3E4-8638-4EAD-B182-A4FE571E9974</string> - <string>38EB1CC2-4A1A-4C37-9D69-19D81129C5DC</string> - <string>E0D7DCCA-9801-4DD5-9C26-3B607BEF7135</string> - <string>241129A8-4AF3-4005-B276-6F431B5CB3F2</string> - <string>8AE48664-E323-4DF9-BED2-CE700CAC7C15</string> - <string>08392E18-5D55-41CB-BE64-7B091492E7BF</string> - <string>9AEFE392-91BE-4968-8FF8-8A2C9D51D4CC</string> - <string>67423190-2729-4C30-B10D-51B7DC3FAB85</string> - <string>1B072993-0FFD-44B7-8C6D-3F9D60AF9E7B</string> - <string>B8817D6A-B326-48F9-9E35-B28778A79412</string> - <string>157C15A0-D535-4EAB-8173-6D6EB0906173</string> - <string>0E400696-4C11-4072-9DAD-7BFF6F7789BE</string> - <string>5A2941B5-2D73-4348-AB92-932665EB6E1D</string> - <string>902C51B4-E4E3-4B2C-BA03-769FC6AC0867</string> - <string>5CF87863-EBA1-49BE-AB51-016A2D0FDA80</string> - <string>A72AC858-A593-4758-894F-266F9925990D</string> - <string>6E59F119-65E3-4D1F-B393-121208A9A83F</string> - <string>E336E487-B1EA-449C-9B32-4C5994136CEA</string> - <string>90B1EE50-DAC5-4748-8415-5C3ABB38CFD5</string> - <string>784AAEB3-2367-4275-95E0-DFDBE61E9423</string> - <string>D5310F63-357F-4E8A-9583-26F569D309EB</string> - <string>1ADF5606-9DC3-413F-8BC2-5E54E7BAC4FF</string> - <string>28364618-9329-4501-98EC-852D28D2F59A</string> - <string>EA2AA961-32E7-4B4B-85C8-0F458AC6E671</string> - <string>A14677C7-FB24-4A35-B9F5-F764C2EFE00E</string> - <string>5736162D-BDF6-4C94-8F3C-8F4CEB38E349</string> - <string>C6C27604-1D24-4EC3-B40D-BD1FF6196DF8</string> - <string>96D4FDBD-4A7D-42E4-BF7A-AB366E22758B</string> - <string>E1BBA1F0-05C7-4EA0-87BA-FB0FC5D1CAED</string> - <string>C8C2C389-AEE0-4CE2-8944-A7EEEFB9B680</string> - <string>36F4B163-2ACD-48F1-8E72-365E54EB7811</string> - <string>5D0E9DF4-6631-419C-AEEE-7710EE30502F</string> - <string>0A3097F1-36A8-4009-8501-CC5B9349072E</string> - <string>C28091B5-3245-4E3C-BC49-38AAB093D00F</string> - <string>1D9BEE6E-907F-430A-BD62-2DF38A454B3E</string> - <string>B8DC9CF1-AFF5-44E4-B9A8-42093D829889</string> - <string>BEDB5CCC-7FF1-4C78-8169-2B58BFB2C449</string> - <string>E6EE6F14-372D-469B-B31F-827A54CFC5E3</string> - <string>DB5DE93A-DA9A-40E9-B469-EF8337A11CBE</string> - <string>63B626CD-2818-42F2-BD90-DE112A8DEF7A</string> - <string>5C3D7157-DFC0-4762-B059-C10F1A098089</string> - <string>BD84E1FB-DCA2-493E-887E-1A1330DD6EA9</string> - <string>CED5A340-3643-4F34-A8ED-A9FB99008300</string> - <string>AB4A8782-7466-4B5D-A180-96E0BD19C050</string> - <string>D01E4126-187A-4275-8583-DFA44FE3BB3C</string> - <string>F9725187-DAE2-43BB-9209-BAF4F709AD72</string> - <string>C83F3775-A62D-425B-B05E-C6A58C929399</string> - <string>6674FAC2-9201-4D0D-BAA5-E35D64BDADDC</string> - <string>53E1E9D3-8F53-4CFE-8ADD-83AC13969D24</string> - <string>415DDDAF-1163-49E7-8D5B-3B6CD1A27A06</string> - <string>B2FCBECB-D1E0-4BF4-B046-5A9C4A6475F9</string> - <string>601BA2FE-EA4D-4B9C-A8EF-646A9E9626DD</string> - <string>B14D6A84-2B4D-4FF8-99CB-E2B41B0E00BF</string> - <string>29745C05-70EC-418A-A7E1-E60EE6042A95</string> - <string>2FB6FDE3-F8F0-47A1-AE6D-AA3895A489CD</string> - <string>0B69D306-8DF0-4494-87AC-B8E92091E0E6</string> - <string>9AA75F85-02C0-4006-9D95-F7EC2728A050</string> - <string>192D1402-A2E5-43F1-B0C5-990853DB5D98</string> - <string>8BBB6187-A1D9-43AF-AF72-CDF3BB8B0A76</string> - <string>DE1C603E-D791-469F-99D3-69E17B9B41EB</string> - <string>FA01E47F-EB01-4FE1-9EB6-96FDEB923E70</string> - <string>AA6262C5-CA32-415E-B666-D2FBF93E0905</string> - <string>80B9754E-47ED-46D6-8BA5-80744B0FBE4B</string> - <string>9A1343CB-5E9E-45A2-8D21-B4959C412B6E</string> - <string>622A22FB-207B-4322-BC6C-C2B3D605AF00</string> - <string>4DD466D2-0B15-4E06-8446-5AFBFC8B4128</string> - <string>183709C1-9414-4A25-89FB-A0D9A7E59D27</string> - <string>35060F61-EF40-4046-BF12-1AB2748884A1</string> - <string>44EA1298-2450-498B-82F6-1BF1BC1FFE59</string> - <string>29486C8D-7A9A-4EE0-B6A3-34C77A7D253E</string> - <string>7F70512F-517F-4361-89ED-13E8C3BD98F0</string> - <string>2A8760F9-6ED1-4066-B996-5E490B5A17EF</string> - <string>9187A792-54F4-4773-A2D7-EB5D207D1A54</string> - <string>F0AFF0A1-90FA-424F-A6AF-6EA6EC1BB225</string> - <string>026FDCF1-E739-42E4-925D-59D80EE7FF05</string> - <string>50182FB9-0179-4CF6-9AD7-4E7BC725C594</string> - <string>3B19D8BC-5389-4263-A539-160170F7DFB1</string> - <string>B096E910-EE96-4E63-BB46-EB12616C80F6</string> - <string>08743309-6431-44D2-8A38-926516B04BEF</string> - <string>A4876D40-55A7-44A0-9CDD-BCF62A621FC3</string> - <string>5C441A88-2F12-4C54-83F8-81A62F735F88</string> - <string>FDDBDC40-D1D9-4981-92DE-30CA475BC8FA</string> - <string>3C93CAC9-0DC3-4371-8E5F-2727B0A282BD</string> - <string>6F5A4D8F-DE7C-4663-9D39-7BF23D84769E</string> - <string>75FFC09D-CB71-49CF-AB01-3DA8C44F29F3</string> - <string>97DD90F8-5334-46A0-B973-C59F357D6C31</string> - <string>3ED1297F-4C77-4187-9356-4262D3F28625</string> - <string>F36E8F58-CDBD-4E42-A64F-9D05BE2D49B9</string> - <string>1B6D6622-49BD-4EAB-B521-B3D1ACF2E4B1</string> - <string>E09B46CF-DDE0-4B40-B7AF-93C005F23BAB</string> - <string>A607B362-68CB-4AE3-BE72-575EB7CBA55A</string> - <string>A57CC7BE-F39A-4B64-908D-44EA058C294F</string> - <string>0C5234DB-A0F6-4BE2-AF28-5276ED3F81BB</string> - <string>BC74CDF9-65E1-4FD0-A939-110CF53F3F67</string> - <string>D6CFEC97-357A-4EBD-9D95-F89FECD4ED66</string> - <string>293B3EF2-892E-4FF9-BB3B-82AE01FFA38D</string> - <string>24AEB6C9-9CDE-478C-9C08-5CB1825321AE</string> - <string>4417C4C8-F581-41FC-96FF-76A28A1F0640</string> - <string>BC022681-5DE4-4E5C-8638-93EF655F7B0D</string> - <string>47BD7B3C-4316-4C5B-AD7D-596D90D64A7C</string> - <string>ED205418-D60B-41CE-9942-6855C78C65F6</string> - <string>AEA7BB76-4231-41DC-829C-D093F7BF28E5</string> - <string>F29A9DA7-B58E-4839-8664-2C99C5679384</string> - <string>7423A717-6340-4CEC-9151-2B882D052CB9</string> - <string>6E621AA5-5304-4DCE-82B9-820FDB78C5FE</string> - <string>21B96169-6556-4436-B3B2-4556A6372567</string> - <string>7A62D445-BDCF-4C67-8B71-35255FACC231</string> - <string>9B25BE9A-A2E8-4BA6-A1CD-A545C6A3AEDE</string> - <string>AD74D8BA-A774-4748-BF7E-22A6E94194ED</string> - <string>8743E910-AD98-42C7-AC9D-4EBD26B54456</string> - <string>5EB9976E-F76E-40FE-828F-22B393BA59AE</string> - <string>8A82A0E0-7396-436B-A3FD-46680599A33A</string> - <string>B36FA4B0-F6AE-4489-97D1-54BFE773A560</string> - <string>281422A7-AF82-45BF-8707-4242A22FA908</string> - <string>CD089D33-F3B3-4BC8-9650-B7CF29B877BF</string> - <string>18A3925F-BF0F-4FAF-B45C-C02B2D4C4CB1</string> - <string>7188A872-4A9F-4A05-ADCA-46D83E911D2D</string> - <string>6322FE39-5B27-49EF-A632-A6073EDCE0C4</string> - <string>BEC86CCF-C220-4B07-9ACD-320238D1FE48</string> - <string>1F61F24F-166C-4D2E-98B0-7BA454B21619</string> - <string>5BAF7E27-FEAB-43E0-899F-ABE9DA500FD0</string> - <string>EE49E017-4812-4CAA-8CCC-29DAB3BE7B64</string> - <string>97F31F3F-B885-4DE8-B784-5582990C21CD</string> - <string>5D2DC339-C6E8-4919-9500-DD24DC9D2F73</string> - <string>9E6E0847-D0DB-435D-A129-CA90BE6B9210</string> - <string>82B42D60-DC77-47AA-B433-14969E2A2CEB</string> - <string>DE1DB107-EC48-4128-B400-203B72AFD40F</string> - <string>2051A0AE-51E2-413F-9CCB-92826FCD5C99</string> + <!-- etc, etc all the uuids for tags --> </array> <key>name</key> <string>ColdFusion Tags</string> </dict> - </dict> --> + </dict> </dict> <key>name</key> <string>ColdFusion</string> <key>ordering</key> <array> <!-- <string>00D00AD7-3C05-46E0-B8B9-0F5CCAC04F57</string> <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> --> </array> <key>uuid</key> <string>1A09BE0B-E81A-4CB7-AF69-AFC845162D1F</string> </dict> </plist> diff --git a/build.xml b/build.xml index f0155fc..bc14b8b 100644 --- a/build.xml +++ b/build.xml @@ -1,41 +1,43 @@ <project name="ColdFusion Textmate Bundle"> <!-- The xslt process needs an XSLT 2.0 processor, so I am using Saxon--> <property name="saxon.path" value="/Applications/saxonb9-0-0-4j/saxon9.jar" /> <!-- Probably wont need to change this unless you are going to try to use a different cfeclipse dictionary file. --> <property name="dictionary.file" value="Resources/cf8.xml" /> <property name="xsl.file" value="dictToBundle.xsl" /> <property name="base.bundle" value="ColdFusion.bun" /> <property name="output.bundle" value="ColdFusion.tmbundle" /> + <property name="bundle.uuid" value="1A09BE0B-E81A-4CB7-AF69-AFC845162D1F" /> + <target name="clean"> <delete dir="${output.bundle}" /> <!-- <delete verbose="true"> <fileset dir="./${base.bundle}/Snippets" includes="**/gen-*.tmSnippet" /> </delete> --> </target> <target name="createSnippets"> <!-- <mkdir dir="${output.bundle}" /> --> <java jar="${saxon.path}" fork="true"> <arg value="-o:${output.bundle}/info.plist" /> <arg value="${dictionary.file}" /> <arg value="${xsl.file}" /> - <!-- <arg value="bundle-dir=''" /> --> + <arg value="bundle-uuid=${bundle.uuid}" /> </java> </target> <target name="createBundle"> <copy todir="${output.bundle}"> <fileset dir="${base.bundle}"/> </copy> </target> <target name="build"> <antcall target="createBundle" /> <antcall target="createSnippets" /> </target> </project> \ No newline at end of file diff --git a/dictToBundle.xsl b/dictToBundle.xsl index 64ab977..c5f5368 100644 --- a/dictToBundle.xsl +++ b/dictToBundle.xsl @@ -1,224 +1,277 @@ <?xml version="1.0" encoding="UTF-8" ?> <!-- dictToBundle Created by Rob Rohan on 2008-11-22. Copyright (c) 2008-2009 Rob Rohan. All rights reserved. --> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:dic="http://www.cfeclipse.org/version1/dictionary" xmlns:util="java:java.util.UUID" version="2.0" exclude-result-prefixes="xsl dic util"> <xsl:output method="xml" indent="yes" /> <xsl:output method="xml" indent="yes" name="plistxml" exclude-result-prefixes="xsl dic util" /> <!-- <xsl:param name="bundle-dir" select="'ColdFusion.bun'" /> --> + <!-- The uuid that will be set in the plist file. I think this needs to be unique per bundle --> + <xsl:param name="bundle-uuid" select="'1A09BE0B-E81A-4CB7-AF69-AFC845162D1F'" /> + <xsl:variable name="NL"> <xsl:text> </xsl:text> </xsl:variable> + <xsl:variable name="TAB"> + <xsl:text> </xsl:text> + </xsl:variable> <xsl:template match="/"> - <!-- - <?xml version="1.0" encoding="UTF-8"?> - <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> --> <plist version="1.0"> <dict> <key>contactEmailRot13</key> <string>[email protected]</string> <key>contactName</key> <string>Rob Rohan</string> <key>description</key> <string>Support for the ColdFusion web development environment.</string> <key>mainMenu</key> <dict> <key>items</key> <array> <string>C8F9D7A6-D447-4C16-B566-BE46335B1067</string> <string>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</string> <string>------------------------------------</string> <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> </array> <key>submenus</key> <dict> <key>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</key> <dict> <key>items</key> <array> <xsl:comment>FUNCTIONS</xsl:comment><xsl:value-of select="$NL" /> <xsl:apply-templates select="/dic:dictionary/dic:functions/dic:function" /> </array> <key>name</key> <string>ColdFusion Functions</string> </dict> <key>C8F9D7A6-D447-4C16-B566-BE46335B1067</key> <dict> <key>items</key> <array> <xsl:comment>TAGS</xsl:comment><xsl:value-of select="$NL" /> <xsl:apply-templates select="/dic:dictionary/dic:tags/dic:tag" /> </array> <key>name</key> <string>ColdFusion Tags</string> </dict> </dict> </dict> <key>name</key> <string>ColdFusion</string> <key>ordering</key> <array> <!-- <string>00D00AD7-3C05-46E0-B8B9-0F5CCAC04F57</string> <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> --> </array> <key>uuid</key> - <string>1A09BE0B-E81A-4CB7-AF69-AFC845162D1F</string> + <string><xsl:value-of select="$bundle-uuid" /></string> </dict> </plist> </xsl:template> <!-- Formats the functions. Writes the plist too. --> <xsl:template match="dic:function"> <xsl:variable name="filename" select="translate(@name,':','-')" /> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:value-of select="$NL" /> <!-- {$bundle-dir}/ --> <xsl:result-document href="Snippets/gen-{$filename}.tmSnippet" format="plistxml"> - <!-- <xsl:text><!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"></xsl:text> --> <plist version="1.0"> <dict> <key>content</key> <string><xsl:value-of select="@name" /> <xsl:text>(${1:</xsl:text> <xsl:for-each select="./dic:parameter"> <xsl:call-template name="param-with-placement"> - <xsl:with-param name="placement" select="position()+position()" /> - <xsl:with-param name="separator" select="', '" /> + <xsl:with-param name="placement" select="position()+1" /> + <xsl:with-param name="separator" select="''" /> + <xsl:with-param name="preparator" select="', '" /> + <xsl:with-param name="use-equals" select="'false'" /> <xsl:with-param name="total-param-count" select="count(../dic:parameter)" /> </xsl:call-template> </xsl:for-each> <xsl:text>})</xsl:text></string> <key>name</key> <string><xsl:value-of select="@name"/></string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string><xsl:value-of select="@name"/></string> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <!-- Formats the tags. Writes out the plist file too --> <xsl:template match="dic:tag"> <xsl:variable name="filename" select="translate(@name,':','-')" /> - <!-- <xsl:value-of select="$filename" /> --> <xsl:variable name="uid" select="util:randomUUID()"/> <string><xsl:value-of select="util:toString($uid)"/></string> <xsl:value-of select="$NL" /> <!-- {$bundle-dir}/ --> <xsl:result-document href="Snippets/gen-{$filename}.tmSnippet" format="plistxml"> - <!-- <xsl:text><!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"></xsl:text> --> <plist version="1.0"> <dict> <key>content</key> <string><xsl:text>&lt;</xsl:text> <xsl:value-of select="@name" /> <xsl:text> ${1:</xsl:text> <xsl:for-each select="./dic:parameter"> <xsl:call-template name="param-with-placement"> <xsl:with-param name="placement" select="position()+position()" /> <xsl:with-param name="separator" select="' '" /> + <xsl:with-param name="preparator" select="''" /> + <xsl:with-param name="use-equals" select="'true'" /> <xsl:with-param name="total-param-count" select="count(../dic:parameter)" /> <!-- <xsl:with-param name="element" select="." /> --> </xsl:call-template> </xsl:for-each> <xsl:text>}</xsl:text> <xsl:choose> <xsl:when test="@single = 'true'"> - <xsl:text>/&gt;$0</xsl:text> + <xsl:text> /&gt;$0</xsl:text> </xsl:when> <xsl:otherwise> - <xsl:text>&gt;$0&lt;</xsl:text> + <xsl:text>&gt;</xsl:text> + <xsl:value-of select="$NL" /> + <xsl:value-of select="$TAB" /> + <xsl:text>$0</xsl:text> + <xsl:value-of select="$NL" /> + <xsl:text>&lt;</xsl:text> <xsl:value-of select="@name" /> <xsl:text>&gt;</xsl:text> </xsl:otherwise> </xsl:choose></string> <key>name</key> <string><xsl:value-of select="@name"/></string> <key>scope</key> <string>text.html.cfm</string> <key>tabTrigger</key> <string> <xsl:choose> <xsl:when test="contains(@name,':')"> <xsl:value-of select="substring-before(@name,':')" /> </xsl:when> <xsl:otherwise> <xsl:value-of select="@name" /> </xsl:otherwise> </xsl:choose> </string> <key>uuid</key> <string><xsl:value-of select="util:toString($uid)"/></string> </dict> </plist> </xsl:result-document> </xsl:template> <!-- handles doing the tag and function params. Takes 3 params. placement = where to start the textmate $N variables from separator = what to tack on to the end of each paramenter total-param-count = total number of params, so we don't add the separator to the last item. --> <xsl:template name="param-with-placement"> <xsl:param name="placement" /> <xsl:param name="separator" /> + <xsl:param name="preparator" /> + <xsl:param name="use-equals" /> <xsl:param name="total-param-count" /> - <xsl:text>$</xsl:text> - <xsl:text>{</xsl:text> - <xsl:value-of select="$placement" /> - <xsl:text>:</xsl:text> - <xsl:value-of select="@name" /><xsl:text>="$</xsl:text> - <xsl:value-of select="$placement+1" /> - <xsl:text>"</xsl:text> - <xsl:if test="position() != $total-param-count"> - <xsl:value-of select="$separator" /> - </xsl:if> - <xsl:text>}</xsl:text> + <xsl:choose> + <xsl:when test="$use-equals = 'true'"> + <xsl:text>$</xsl:text> + <xsl:text>{</xsl:text> + <xsl:value-of select="$placement" /> + <xsl:text>:</xsl:text> + + <xsl:value-of select="$preparator" /> + + <xsl:value-of select="@name" /><xsl:text>="$</xsl:text> + <xsl:value-of select="$placement+1" /> + <xsl:text>"</xsl:text> + <xsl:if test="position() != $total-param-count"> + <xsl:value-of select="$separator" /> + </xsl:if> + <xsl:text>}</xsl:text> + </xsl:when> + <xsl:otherwise> + <xsl:if test="@required = 'true'"> + <xsl:if test="position() != 1"> + <xsl:value-of select="$preparator" /> + </xsl:if> + + <xsl:if test="@type = 'String'"> + <xsl:text>"</xsl:text> + </xsl:if> + </xsl:if> + + <xsl:text>${</xsl:text> + <xsl:value-of select="$placement" /> + <xsl:text>:</xsl:text> + + <xsl:if test="@required = 'false'"> + <xsl:if test="position() != 1"> + <xsl:value-of select="$preparator" /> + </xsl:if> + </xsl:if> + <xsl:if test="@required = 'false'"><xsl:text>[</xsl:text></xsl:if> + <xsl:value-of select="@name" /> + <xsl:if test="@required = 'false'"><xsl:text>]</xsl:text></xsl:if> + + <xsl:text>}</xsl:text> + + <xsl:if test="@required = 'true'"> + <xsl:if test="@type = 'String'"> + <xsl:text>"</xsl:text> + </xsl:if> + </xsl:if> + + </xsl:otherwise> + </xsl:choose> + + </xsl:template> <xsl:template match="text()" /> </xsl:stylesheet> \ No newline at end of file
robrohan/coldfusion.tmbundle
74c89a8b2f60e54096e8deb403df3f96d288f6b1
Getting cfffunction names to show up in the symbol popup so it's easy to jump to them
diff --git a/Syntaxes/ColdFusion.tmLanguage b/Syntaxes/ColdFusion.tmLanguage index a2d3431..1abff67 100644 --- a/Syntaxes/ColdFusion.tmLanguage +++ b/Syntaxes/ColdFusion.tmLanguage @@ -1,765 +1,817 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> -<dict> - <key>bundleUUID</key> - <string>1A09BE0B-E81A-4CB7-AF69-AFC845162D1F</string> - <key>fileTypes</key> - <array> - <string>cfm</string> - <string>cfml</string> - <string>cfc</string> - </array> - <key>firstLineMatch</key> - <string>&lt;!DOCTYPE|&lt;(?i:html)</string> - <key>foldingStartMarker</key> - <string>(?x) + <dict> + <key>bundleUUID</key> + <string>1A09BE0B-E81A-4CB7-AF69-AFC845162D1F</string> + <key>fileTypes</key> + <array> + <string>cfm</string> + <string>cfml</string> + <string>cfc</string> + </array> + <key>firstLineMatch</key> + <string>&lt;!DOCTYPE|&lt;(?i:html)</string> + <key>foldingStartMarker</key> + <string>(?x) (&lt;(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script |ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction)\b.*?&gt; |&lt;!---(?!.*---\s*&gt;) )</string> - <key>foldingStopMarker</key> - <string>(?x) + <key>foldingStopMarker</key> + <string>(?x) (&lt;/(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|scrip t|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction)&gt; |^(?!.*?&lt;!---).*?---\s*&gt; )</string> - <key>keyEquivalent</key> - <string>^~@c</string> - <key>name</key> - <string>ColdFusion</string> - <key>patterns</key> - <array> - <dict> - <key>begin</key> - <string>&lt;([a-zA-Z0-9:]+)(?=[^&gt;]*&gt;&lt;/\1&gt;)</string> - <key>beginCaptures</key> - <dict> - <key>1</key> - <dict> - <key>name</key> - <string>entity.name.tag.html</string> - </dict> - </dict> - <key>end</key> - <string>&gt;(&lt;)/(\1)&gt;</string> - <key>endCaptures</key> + <key>keyEquivalent</key> + <string>^~@c</string> + <key>name</key> + + <string>ColdFusion</string> + <key>patterns</key> + <array> <dict> - <key>1</key> + <key>begin</key> + <string>&lt;([a-zA-Z0-9:]+)(?=[^&gt;]*&gt;&lt;/\1&gt;)</string> + <key>beginCaptures</key> <dict> - <key>name</key> - <string>meta.scope.between-tag-pair.html</string> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.html</string> + </dict> </dict> - <key>2</key> + <key>end</key> + <string>&gt;(&lt;)/(\1)&gt;</string> + <key>endCaptures</key> <dict> - <key>name</key> - <string>entity.name.tag.html</string> + <key>1</key> + <dict> + <key>name</key> + <string>meta.scope.between-tag-pair.html</string> + </dict> + <key>2</key> + <dict> + <key>name</key> + <string>entity.name.tag.html</string> + </dict> </dict> + <key>name</key> + <string>meta.tag.any.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + </array> </dict> - <key>name</key> - <string>meta.tag.any.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#tag-stuff</string> - </dict> - </array> - </dict> - <dict> - <key>begin</key> - <string>&lt;\?(xml)</string> - <key>captures</key> <dict> - <key>1</key> + <key>begin</key> + <string>&lt;\?(xml)</string> + <key>captures</key> <dict> - <key>name</key> - <string>entity.name.tag.xml.html</string> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.xml.html</string> + </dict> </dict> + <key>end</key> + <string>\?&gt;</string> + <key>name</key> + <string>meta.tag.preprocessor.xml.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-generic-attribute</string> + </dict> + <dict> + <key>include</key> + <string>#string-double-quoted</string> + </dict> + <dict> + <key>include</key> + <string>#string-single-quoted</string> + </dict> + </array> </dict> - <key>end</key> - <string>\?&gt;</string> - <key>name</key> - <string>meta.tag.preprocessor.xml.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#tag-generic-attribute</string> - </dict> - <dict> - <key>include</key> - <string>#string-double-quoted</string> - </dict> - <dict> - <key>include</key> - <string>#string-single-quoted</string> - </dict> - </array> - </dict> - <dict> - <key>begin</key> - <string>&lt;!---</string> - <key>end</key> - <string>---\s*&gt;</string> - <key>name</key> - <string>comment.block.html</string> - <key>patterns</key> - <array> - <dict> - <key>match</key> - <string>---</string> - <key>name</key> - <string>invalid.illegal.bad-comments-or-CDATA.html</string> - </dict> - </array> - </dict> - <dict> - <key>begin</key> - <string>&lt;!</string> - <key>end</key> - <string>&gt;</string> - <key>name</key> - <string>meta.tag.sgml.html</string> - <key>patterns</key> - <array> - <dict> - <key>begin</key> - <string>(DOCTYPE)</string> - <key>captures</key> + <dict> + <key>begin</key> + <string>&lt;!---</string> + <key>end</key> + <string>---\s*&gt;</string> + <key>name</key> + <string>comment.block.html</string> + <key>patterns</key> + <array> <dict> - <key>1</key> - <dict> - <key>name</key> - <string>entity.name.tag.doctype.html</string> - </dict> + <key>match</key> + <string>---</string> + <key>name</key> + <string>invalid.illegal.bad-comments-or-CDATA.html</string> </dict> - <key>end</key> - <string>(?=&gt;)</string> - <key>name</key> - <string>meta.tag.sgml.doctype.html</string> - <key>patterns</key> - <array> + </array> + </dict> + <dict> + <key>begin</key> + <string>&lt;!</string> + <key>end</key> + <string>&gt;</string> + <key>name</key> + <string>meta.tag.sgml.html</string> + <key>patterns</key> + <array> + <dict> + <key>begin</key> + <string>(DOCTYPE)</string> + <key>captures</key> <dict> - <key>match</key> - <string>"[^"&gt;]*"</string> - <key>name</key> - <string>string.quoted.double.doctype.identifiers-and-DTDs.html</string> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.doctype.html</string> + </dict> </dict> - </array> - </dict> - <dict> - <key>begin</key> - <string>\[CDATA\[</string> - <key>end</key> - <string>]](?=&gt;)</string> - <key>name</key> - <string>constant.other.inline-data.html</string> - </dict> - <dict> - <key>match</key> - <string>(\s*)(?!---|&gt;)\S(\s*)</string> - <key>name</key> - <string>invalid.illegal.bad-comments-or-CDATA.html</string> - </dict> - </array> - </dict> - <dict> - <key>include</key> - <string>#coldfusion-script</string> - </dict> - <dict> - <key>include</key> - <string>#cffunction</string> - </dict> - <dict> - <key>begin</key> - <string>(?:^\s+)?&lt;((?i:style))\b(?![^&gt;]*/&gt;)</string> - <key>captures</key> + <key>end</key> + <string>(?=&gt;)</string> + <key>name</key> + <string>meta.tag.sgml.doctype.html</string> + <key>patterns</key> + <array> + <dict> + <key>match</key> + <string>"[^"&gt;]*"</string> + <key>name</key> + <string>string.quoted.double.doctype.identifiers-and-DTDs.html</string> + </dict> + </array> + </dict> + <dict> + <key>begin</key> + <string>\[CDATA\[</string> + <key>end</key> + <string>]](?=&gt;)</string> + <key>name</key> + <string>constant.other.inline-data.html</string> + </dict> + <dict> + <key>match</key> + <string>(\s*)(?!---|&gt;)\S(\s*)</string> + <key>name</key> + <string>invalid.illegal.bad-comments-or-CDATA.html</string> + </dict> + </array> + </dict> <dict> - <key>1</key> - <dict> - <key>name</key> - <string>entity.name.tag.style.html</string> - </dict> + <key>include</key> + <string>#coldfusion-script</string> </dict> - <key>end</key> - <string>&lt;/((?i:style))&gt;(?:\s*\n)?</string> - <key>name</key> - <string>source.css.embedded.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#tag-stuff</string> - </dict> - <dict> - <key>begin</key> - <string>&gt;</string> - <key>end</key> - <string>(?=&lt;/(?i:style))</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#embedded-code</string> - </dict> - <dict> - <key>include</key> - <string>source.css</string> - </dict> - </array> - </dict> - </array> - </dict> - <dict> - <key>begin</key> - <string>(?:^\s+)?&lt;((?i:cfquery))\b(?![^&gt;]*/&gt;)</string> - <key>captures</key> <dict> - <key>1</key> - <dict> - <key>name</key> - <string>entity.name.tag.cfquery.html</string> - </dict> + <key>include</key> + <string>#cffunction</string> </dict> - <key>end</key> - <string>&lt;/((?i:cfquery))&gt;(?:\s*\n)?</string> - <key>name</key> - <string>source.sql.embedded.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#tag-stuff</string> - </dict> - <dict> - <key>begin</key> - <string>&gt;</string> - <key>end</key> - <string>(?=&lt;/(?i:cfquery))</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#embedded-code</string> - </dict> - <dict> - <key>include</key> - <string>source.sql</string> - </dict> - </array> - </dict> - </array> - </dict> - <dict> - <key>begin</key> - <string>(?:^\s+)?&lt;((?i:script))\b(?![^&gt;]*/&gt;)</string> - <key>captures</key> <dict> - <key>1</key> + <key>begin</key> + <string>(?:^\s+)?&lt;((?i:style))\b(?![^&gt;]*/&gt;)</string> + <key>captures</key> <dict> - <key>name</key> - <string>entity.name.tag.script.html</string> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.style.html</string> + </dict> </dict> + <key>end</key> + <string>&lt;/((?i:style))&gt;(?:\s*\n)?</string> + <key>name</key> + <string>source.css.embedded.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + <dict> + <key>begin</key> + <string>&gt;</string> + <key>end</key> + <string>(?=&lt;/(?i:style))</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#embedded-code</string> + </dict> + <dict> + <key>include</key> + <string>source.css</string> + </dict> + </array> + </dict> + </array> </dict> - <key>end</key> - <string>(?&lt;=&lt;/(script|SCRIPT))&gt;(?:\s*\n)?</string> - <key>name</key> - <string>source.js.embedded.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#tag-stuff</string> - </dict> - <dict> - <key>begin</key> - <string>(?&lt;!&lt;/(?:script|SCRIPT))&gt;</string> - <key>end</key> - <string>&lt;/((?i:script))</string> - <key>patterns</key> - <array> - <dict> - <key>match</key> - <string>//.*?((?=&lt;/script)|$\n?)</string> - <key>name</key> - <string>comment.line.double-slash.js</string> - </dict> - <dict> - <key>begin</key> - <string>/\*</string> - <key>end</key> - <string>\*/|(?=&lt;/script)</string> - <key>name</key> - <string>comment.block.js</string> - </dict> - <dict> - <key>include</key> - <string>source.js</string> - </dict> - </array> - </dict> - </array> - </dict> - <dict> - <key>begin</key> - <string>(?:^\s+)?&lt;((?i:cfscript))\b(?![^&gt;]*/&gt;)</string> - <key>captures</key> <dict> - <key>1</key> + <key>begin</key> + <string>(?:^\s+)?&lt;((?i:cfquery))\b(?![^&gt;]*/&gt;)</string> + <key>captures</key> <dict> - <key>name</key> - <string>entity.name.tag.script.html</string> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.cfquery.html</string> + </dict> </dict> + <key>end</key> + <string>&lt;/((?i:cfquery))&gt;(?:\s*\n)?</string> + <key>name</key> + <string>source.sql.embedded.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + <dict> + <key>begin</key> + <string>&gt;</string> + <key>end</key> + <string>(?=&lt;/(?i:cfquery))</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#embedded-code</string> + </dict> + <dict> + <key>include</key> + <string>source.sql</string> + </dict> + </array> + </dict> + </array> </dict> - <key>end</key> - <string>(?&lt;=&lt;/(cfscript|CFSCRIPT))&gt;(?:\s*\n)?</string> - <key>name</key> - <string>source.js.embedded.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#tag-stuff</string> - </dict> - <dict> - <key>begin</key> - <string>(?&lt;!&lt;/(?:cfscript|CFSCRIPT))&gt;</string> - <key>end</key> - <string>&lt;/((?i:cfscript))</string> - <key>patterns</key> - <array> - <dict> - <key>match</key> - <string>//.*?((?=&lt;/cfscript)|$\n?)</string> - <key>name</key> - <string>comment.line.double-slash.js</string> - </dict> - <dict> - <key>begin</key> - <string>/\*</string> - <key>end</key> - <string>\*/|(?=&lt;/cfscript)</string> - <key>name</key> - <string>comment.block.js</string> - </dict> - <dict> - <key>include</key> - <string>source.js</string> - </dict> - </array> - </dict> - </array> - </dict> - <dict> - <key>begin</key> - <string>&lt;/?((?i:body|head|html)\b)</string> - <key>captures</key> <dict> - <key>1</key> + <key>begin</key> + <string>(?:^\s+)?&lt;((?i:script))\b(?![^&gt;]*/&gt;)</string> + <key>captures</key> <dict> - <key>name</key> - <string>entity.name.tag.structure.any.html</string> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.script.html</string> + </dict> </dict> + <key>end</key> + <string>(?&lt;=&lt;/(script|SCRIPT))&gt;(?:\s*\n)?</string> + <key>name</key> + <string>source.js.embedded.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + <dict> + <key>begin</key> + <string>(?&lt;!&lt;/(?:script|SCRIPT))&gt;</string> + <key>end</key> + <string>&lt;/((?i:script))</string> + <key>patterns</key> + <array> + <dict> + <key>match</key> + <string>//.*?((?=&lt;/script)|$\n?)</string> + <key>name</key> + <string>comment.line.double-slash.js</string> + </dict> + <dict> + <key>begin</key> + <string>/\*</string> + <key>end</key> + <string>\*/|(?=&lt;/script)</string> + <key>name</key> + <string>comment.block.js</string> + </dict> + <dict> + <key>include</key> + <string>source.js</string> + </dict> + </array> + </dict> + </array> </dict> - <key>end</key> - <string>&gt;</string> - <key>name</key> - <string>meta.tag.structure.any.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#tag-stuff</string> - </dict> - </array> - </dict> - <dict> - <key>begin</key> - <string>&lt;/?((?i:address|blockquote|dd|div|dl|dt|fieldset|form|frame|frameset|h1|h2 |h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|menu|pre)\ b)</string> - <key>captures</key> <dict> - <key>1</key> + <key>begin</key> + <string>(?:^\s+)?&lt;((?i:cfscript))\b(?![^&gt;]*/&gt;)</string> + <key>captures</key> <dict> - <key>name</key> - <string>entity.name.tag.block.any.html</string> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.script.html</string> + </dict> </dict> + <key>end</key> + <string>(?&lt;=&lt;/(cfscript|CFSCRIPT))&gt;(?:\s*\n)?</string> + <key>name</key> + <string>source.js.embedded.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + <dict> + <key>begin</key> + <string>(?&lt;!&lt;/(?:cfscript|CFSCRIPT))&gt;</string> + <key>end</key> + <string>&lt;/((?i:cfscript))</string> + <key>patterns</key> + <array> + <dict> + <key>match</key> + <string>//.*?((?=&lt;/cfscript)|$\n?)</string> + <key>name</key> + <string>comment.line.double-slash.js</string> + </dict> + <dict> + <key>begin</key> + <string>/\*</string> + <key>end</key> + <string>\*/|(?=&lt;/cfscript)</string> + <key>name</key> + <string>comment.block.js</string> + </dict> + <dict> + <key>include</key> + <string>source.js</string> + </dict> + </array> + </dict> + </array> </dict> - <key>end</key> - <string>&gt;</string> - <key>name</key> - <string>meta.tag.block.any.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#tag-stuff</string> - </dict> - </array> - </dict> - <dict> - <key>begin</key> - <string>&lt;/?((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite |code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|la bel|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script| select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot |th|thead|title|tr|tt|u|var)\b)</string> - <key>captures</key> <dict> - <key>1</key> + <key>begin</key> + <string>&lt;/?((?i:body|head|html)\b)</string> + <key>captures</key> <dict> - <key>name</key> - <string>entity.name.tag.inline.any.html</string> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.structure.any.html</string> + </dict> </dict> + <key>end</key> + <string>&gt;</string> + <key>name</key> + <string>meta.tag.structure.any.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + </array> </dict> - <key>end</key> - <string>&gt;</string> - <key>name</key> - <string>meta.tag.inline.any.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#tag-stuff</string> - </dict> - </array> - </dict> - <dict> - <key>begin</key> - <string>&lt;/?([a-zA-Z0-9:]+)</string> - <key>captures</key> <dict> - <key>1</key> + <key>begin</key> + <string>&lt;/?((?i:address|blockquote|dd|div|dl|dt|fieldset|form|frame|frameset|h1|h2 |h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|menu|pre)\ b)</string> + <key>captures</key> <dict> - <key>name</key> - <string>entity.name.tag.other.html</string> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.block.any.html</string> + </dict> </dict> + <key>end</key> + <string>&gt;</string> + <key>name</key> + <string>meta.tag.block.any.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + </array> </dict> - <key>end</key> - <string>&gt;</string> - <key>name</key> - <string>meta.tag.other.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#tag-stuff</string> - </dict> - </array> - </dict> - <dict> - <key>include</key> - <string>#entities</string> - </dict> - <dict> - <key>match</key> - <string>&lt;&gt;</string> - <key>name</key> - <string>invalid.illegal.incomplete.html</string> - </dict> - <dict> - <key>match</key> - <string>&lt;(?=\W)|&gt;</string> - <key>name</key> - <string>invalid.illegal.bad-angle-bracket.html</string> - </dict> - </array> - <key>repository</key> - <dict> - <key>cffunction</key> - <dict> - <key>begin</key> - <string>&lt;(cffunction)</string> - <key>captures</key> <dict> - <key>1</key> + <key>begin</key> + <string>&lt;/?((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite |code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|la bel|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script| select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot |th|thead|title|tr|tt|u|var)\b)</string> + <key>captures</key> <dict> - <key>name</key> - <string>entity.name.tag.cfml</string> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.inline.any.html</string> + </dict> </dict> + <key>end</key> + <string>&gt;</string> + <key>name</key> + <string>meta.tag.inline.any.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + </array> </dict> - <key>end</key> - <string>&gt;</string> - <key>name</key> - <string>meta.tag.language.cfml.function</string> - <key>patterns</key> - <array> + <dict> + <key>begin</key> + <string>&lt;/?([a-zA-Z0-9:]+)</string> + <key>captures</key> <dict> - <key>captures</key> + <key>1</key> <dict> - <key>0</key> - <dict> - <key>name</key> - <string>string.quoted.double.cfml</string> - </dict> - <key>1</key> - <dict> - <key>name</key> - <string>punctuation.definition.string.begin</string> - </dict> - <key>2</key> - <dict> - <key>name</key> - <string>entity.name.function.cfml</string> - </dict> - <key>3</key> - <dict> - <key>name</key> - <string>punctuation.definition.string.end</string> - </dict> + <key>name</key> + <string>entity.name.tag.other.html</string> </dict> - <key>match</key> - <string>(?&lt;=name=)(")([A-Za-z$_0-9]+)(")</string> - </dict> - <dict> - <key>include</key> - <string>source.cfml</string> - </dict> - <dict> - <key>include</key> - <string>#tag-stuff</string> - </dict> - </array> - </dict> - <key>coldfusion-script</key> - <dict> - <key>begin</key> - <string>#</string> - <key>end</key> - <string>\#</string> - <key>name</key> - <string>source.coldfusion.embedded.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#embedded-code</string> - </dict> - </array> - </dict> - <key>embedded-code</key> - <dict> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#php</string> - </dict> - <dict> - <key>include</key> - <string>#ruby</string> - </dict> - <dict> - <key>include</key> - <string>#smarty</string> - </dict> - <dict> - <key>include</key> - <string>#python</string> - </dict> - <dict> - <key>include</key> - <string>#javascript</string> - </dict> - </array> - </dict> - <key>entities</key> - <dict> - <key>patterns</key> - <array> - <dict> - <key>match</key> - <string>&amp;([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);</string> - <key>name</key> - <string>constant.character.entity.html</string> - </dict> - <dict> - <key>match</key> - <string>&amp;</string> - <key>name</key> - <string>invalid.illegal.bad-ampersand.html</string> - </dict> - </array> - </dict> - <key>string-double-quoted</key> - <dict> - <key>begin</key> - <string>"</string> - <key>end</key> - <string>"</string> - <key>name</key> - <string>string.quoted.double.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#embedded-code</string> </dict> - <dict> - <key>include</key> - <string>#entities</string> - </dict> - </array> - </dict> - <key>string-single-quoted</key> - <dict> - <key>begin</key> - <string>'</string> - <key>end</key> - <string>'</string> - <key>name</key> - <string>string.quoted.single.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#embedded-code</string> - </dict> - <dict> - <key>include</key> - <string>#entities</string> - </dict> - </array> - </dict> - <key>tag-generic-attribute</key> - <dict> - <key>match</key> - <string>\b([a-zA-Z\-:]+)</string> - <key>name</key> - <string>entity.other.attribute-name.html</string> - </dict> - <key>tag-id-attribute</key> - <dict> - <key>begin</key> - <string>\b(id)\b\s*=</string> - <key>captures</key> + <key>end</key> + <string>&gt;</string> + <key>name</key> + <string>meta.tag.other.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + </array> + </dict> <dict> - <key>1</key> - <dict> - <key>name</key> - <string>entity.other.attribute-name.id.html</string> - </dict> + <key>include</key> + <string>#entities</string> </dict> - <key>end</key> - <string>(?&lt;='|")</string> - <key>name</key> - <string>meta.attribute-with-value.id.html</string> - <key>patterns</key> - <array> - <dict> - <key>begin</key> - <string>"</string> - <key>contentName</key> - <string>meta.toc-list.id.html</string> - <key>end</key> - <string>"</string> - <key>name</key> - <string>string.quoted.double.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#embedded-code</string> - </dict> - <dict> - <key>include</key> - <string>#entities</string> - </dict> - </array> - </dict> - <dict> - <key>begin</key> - <string>'</string> - <key>contentName</key> - <string>meta.toc-list.id.html</string> - <key>end</key> - <string>'</string> - <key>name</key> - <string>string.quoted.single.html</string> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#embedded-code</string> - </dict> - <dict> - <key>include</key> - <string>#entities</string> - </dict> - </array> - </dict> - </array> - </dict> - <key>tag-stuff</key> + <dict> + <key>match</key> + <string>&lt;&gt;</string> + <key>name</key> + <string>invalid.illegal.incomplete.html</string> + </dict> + <dict> + <key>match</key> + <string>&lt;(?=\W)|&gt;</string> + <key>name</key> + <string>invalid.illegal.bad-angle-bracket.html</string> + </dict> + </array> + + <key>repository</key> <dict> - <key>patterns</key> - <array> - <dict> - <key>include</key> - <string>#tag-id-attribute</string> - </dict> - <dict> - <key>include</key> - <string>#tag-generic-attribute</string> - </dict> - <dict> - <key>include</key> - <string>#string-double-quoted</string> - </dict> - <dict> - <key>include</key> - <string>#string-single-quoted</string> - </dict> - <dict> - <key>include</key> - <string>#coldfusion-script</string> - </dict> - <dict> - <key>include</key> - <string>#embedded-code</string> - </dict> - <dict> - <key>match</key> - <string>.var\s</string> - <key>name</key> - <string>variable.other</string> - </dict> + <key>cffunction</key> + <dict> + <key>begin</key> + <string>&lt;(cffunction)</string> + + <key>captures</key> <dict> - <key>begin</key> - <string>.&lt;cffunction\sname=('|")1</string> - <key>contentName</key> - <string>entity.name.function</string> - <key>end</key> - <string>'|"1</string> - <key>name</key> - <string>meta.tag.other</string> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.cfml</string> + </dict> </dict> - <dict> - <key>begin</key> - <string>[^\#"'][a-zA-Z0-9\.]*.\(</string> - <key>contentName</key> - <string>support.function</string> - <key>end</key> - <string>\)+</string> - <key>name</key> - <string>support.function</string> - <key>patterns</key> - <array> + + <key>end</key> + <string>&gt;</string> + + <key>name</key> + <string>meta.tag.language.cfml.function</string> + + <key>patterns</key> + <array> + <!-- <dict> + <key>captures</key> <dict> - <key>match</key> - <string>("|')[^\.].+("|')</string> - <key>name</key> - <string>string</string> + <key>0</key> + <dict> + <key>name</key> + <string>string.quoted.double.cfml</string> + </dict> + + <key>1</key> + <dict> + <key>name</key> + <string>punctuation.definition.string.begin</string> + </dict> + + <key>2</key> + <dict> + <key>name</key> + <string>entity.name.function.cfml</string> + </dict> + + <key>3</key> + <dict> + <key>name</key> + <string>punctuation.definition.string.end</string> + </dict> </dict> + <key>match</key> + <string>(?&lt;=name=)(")([A-Za-z$_0-9]+)(")</string> + </dict> --> + + <dict> + <key>captures</key> <dict> - <key>match</key> - <string>,</string> - <key>name</key> - <string>meta.tag</string> + <key>0</key> + <dict> + <key>name</key> + <!-- <string>string.quoted.double.cfml</string> --> + <string>meta.tag.language.cfml.function</string> + </dict> + + <key>3</key> + <dict> + <key>name</key> + <string>punctuation.definition.string.begin</string> + </dict> + + <key>4</key> + <dict> + <key>name</key> + <string>entity.name.function.cfml</string> + </dict> + + <key>5</key> + <dict> + <key>name</key> + <string>punctuation.definition.string.end</string> + </dict> </dict> - </array> + <key>match</key> + <string>\b([nN][aA][mM][Ee])\b\s*(=)\s*(["'])([A-Za-z$_0-9]+)(["'])</string> + </dict> + + <dict> + <key>include</key> + <string>source.cfml</string> + </dict> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + </array> + </dict> + + <key>coldfusion-script</key> + <dict> + <key>begin</key> + <string>#</string> + <key>end</key> + <string>\#</string> + <key>name</key> + <string>source.coldfusion.embedded.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#embedded-code</string> + </dict> + </array> + </dict> + + <key>embedded-code</key> + <dict> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#php</string> + </dict> + <dict> + <key>include</key> + <string>#ruby</string> + </dict> + <dict> + <key>include</key> + <string>#smarty</string> + </dict> + <dict> + <key>include</key> + <string>#python</string> + </dict> + <dict> + <key>include</key> + <string>#javascript</string> + </dict> + </array> + </dict> + + <key>entities</key> + <dict> + <key>patterns</key> + <array> + <dict> + <key>match</key> + <string>&amp;([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);</string> + <key>name</key> + <string>constant.character.entity.html</string> + </dict> + <dict> + <key>match</key> + <string>&amp;</string> + <key>name</key> + <string>invalid.illegal.bad-ampersand.html</string> + </dict> + </array> + </dict> + + <key>string-double-quoted</key> + <dict> + <key>begin</key> + <string>"</string> + <key>end</key> + <string>"</string> + <key>name</key> + <string>string.quoted.double.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#embedded-code</string> + </dict> + <dict> + <key>include</key> + <string>#entities</string> + </dict> + </array> + </dict> + + <key>string-single-quoted</key> + <dict> + <key>begin</key> + <string>'</string> + <key>end</key> + <string>'</string> + <key>name</key> + <string>string.quoted.single.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#embedded-code</string> + </dict> + <dict> + <key>include</key> + <string>#entities</string> + </dict> + </array> + </dict> + + <key>tag-generic-attribute</key> + <dict> + <key>match</key> + <string>\b([a-zA-Z\-:]+)</string> + <key>name</key> + <string>entity.other.attribute-name.html</string> + </dict> + + <key>tag-id-attribute</key> + <dict> + <key>begin</key> + <string>\b(id)\b\s*=</string> + <key>captures</key> + <dict> + <key>1</key> + <dict> + <key>name</key> + <string>entity.other.attribute-name.id.html</string> + </dict> </dict> - </array> + <key>end</key> + <string>(?&lt;='|")</string> + <key>name</key> + <string>meta.attribute-with-value.id.html</string> + <key>patterns</key> + <array> + <dict> + <key>begin</key> + <string>"</string> + <key>contentName</key> + <string>meta.toc-list.id.html</string> + <key>end</key> + <string>"</string> + <key>name</key> + <string>string.quoted.double.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#embedded-code</string> + </dict> + <dict> + <key>include</key> + <string>#entities</string> + </dict> + </array> + </dict> + <dict> + <key>begin</key> + <string>'</string> + <key>contentName</key> + <string>meta.toc-list.id.html</string> + <key>end</key> + <string>'</string> + <key>name</key> + <string>string.quoted.single.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#embedded-code</string> + </dict> + <dict> + <key>include</key> + <string>#entities</string> + </dict> + </array> + </dict> + </array> + </dict> + + <key>tag-stuff</key> + <dict> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-id-attribute</string> + </dict> + <dict> + <key>include</key> + <string>#tag-generic-attribute</string> + </dict> + <dict> + <key>include</key> + <string>#string-double-quoted</string> + </dict> + <dict> + <key>include</key> + <string>#string-single-quoted</string> + </dict> + <dict> + <key>include</key> + <string>#coldfusion-script</string> + </dict> + <dict> + <key>include</key> + <string>#embedded-code</string> + </dict> + <dict> + <key>match</key> + <string>.var\s</string> + <key>name</key> + <string>variable.other</string> + </dict> + <dict> + <key>begin</key> + <string>.&lt;cffunction\sname=('|")1</string> + <key>contentName</key> + <string>entity.name.function</string> + <key>end</key> + <string>'|"1</string> + <key>name</key> + <string>meta.tag.other</string> + </dict> + <dict> + <key>begin</key> + <string>[^\#"'][a-zA-Z0-9\.]*.\(</string> + <key>contentName</key> + <string>support.function</string> + <key>end</key> + <string>\)+</string> + <key>name</key> + <string>support.function</string> + <key>patterns</key> + <array> + <dict> + <key>match</key> + <string>("|')[^\.].+("|')</string> + <key>name</key> + <string>string</string> + </dict> + <dict> + <key>match</key> + <string>,</string> + <key>name</key> + <string>meta.tag</string> + </dict> + </array> + </dict> + </array> + </dict> </dict> + + <key>scopeName</key> + <string>text.html.cfm</string> + + <key>uuid</key> + <string>97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14</string> </dict> - <key>scopeName</key> - <string>text.html.cfm</string> - <key>uuid</key> - <string>97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14</string> -</dict> </plist>
robrohan/coldfusion.tmbundle
c11330f5aa6ffbdd3e63976c3ec9b3ff3b3d94b6
Getting the auto complete of # work in most valid areas (script, html, cfml, sql, etc)
diff --git a/Preferences/ColdFusion Preferences.plist b/Preferences/ColdFusion Preferences.plist index 384cced..3c57317 100644 Binary files a/Preferences/ColdFusion Preferences.plist and b/Preferences/ColdFusion Preferences.plist differ
robrohan/coldfusion.tmbundle
16cc73257fda15be311c3972c291bb26282aae20
Fixing cfscript coloring a bit based on an example from Steve Ross
diff --git a/Syntaxes/ColdFusion.tmLanguage b/Syntaxes/ColdFusion.tmLanguage index b659043..a2d3431 100644 --- a/Syntaxes/ColdFusion.tmLanguage +++ b/Syntaxes/ColdFusion.tmLanguage @@ -1,435 +1,765 @@ <?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" - "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> - + <key>bundleUUID</key> + <string>1A09BE0B-E81A-4CB7-AF69-AFC845162D1F</string> <key>fileTypes</key> <array> <string>cfm</string> <string>cfml</string> <string>cfc</string> </array> - + <key>firstLineMatch</key> + <string>&lt;!DOCTYPE|&lt;(?i:html)</string> <key>foldingStartMarker</key> - <string>(?x) - (&lt;(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction)\b.*?&gt; - |&lt;!---(?!.*---\s*&gt;) - )</string> - + <string>(?x) +(&lt;(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script |ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction)\b.*?&gt; + |&lt;!---(?!.*---\s*&gt;) + )</string> <key>foldingStopMarker</key> - <string>(?x) - (&lt;/(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction)&gt; - |^(?!.*?&lt;!---).*?---\s*&gt; - )</string> - + <string>(?x) +(&lt;/(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|scrip t|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction)&gt; + |^(?!.*?&lt;!---).*?---\s*&gt; + )</string> <key>keyEquivalent</key> <string>^~@c</string> - <key>name</key> <string>ColdFusion</string> - <key>patterns</key> <array> - <!-- Bit of a Hack: Use Javascript to emulate cfscript --> - <!-- TODO: Put a bit more work into this --> <dict> <key>begin</key> - <string>(?:^\s+)?&lt;((?i:cfscript))\b(?![^&gt;]*/&gt;)</string> - - <key>captures</key> + <string>&lt;([a-zA-Z0-9:]+)(?=[^&gt;]*&gt;&lt;/\1&gt;)</string> + <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> - <string>entity.name.tag.script.html</string> + <string>entity.name.tag.html</string> </dict> </dict> - <key>end</key> - <string>(?&lt;=&lt;/(cfscript|CFSCRIPT))&gt;(?:\s*\n)?</string> - - <!-- for now just use JS for cfScript (mostly right) --> + <string>&gt;(&lt;)/(\1)&gt;</string> + <key>endCaptures</key> + <dict> + <key>1</key> + <dict> + <key>name</key> + <string>meta.scope.between-tag-pair.html</string> + </dict> + <key>2</key> + <dict> + <key>name</key> + <string>entity.name.tag.html</string> + </dict> + </dict> <key>name</key> - <string>source.js.embedded.html</string> - + <string>meta.tag.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> - + </array> + </dict> + <dict> + <key>begin</key> + <string>&lt;\?(xml)</string> + <key>captures</key> + <dict> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.xml.html</string> + </dict> + </dict> + <key>end</key> + <string>\?&gt;</string> + <key>name</key> + <string>meta.tag.preprocessor.xml.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-generic-attribute</string> + </dict> + <dict> + <key>include</key> + <string>#string-double-quoted</string> + </dict> + <dict> + <key>include</key> + <string>#string-single-quoted</string> + </dict> + </array> + </dict> + <dict> + <key>begin</key> + <string>&lt;!---</string> + <key>end</key> + <string>---\s*&gt;</string> + <key>name</key> + <string>comment.block.html</string> + <key>patterns</key> + <array> + <dict> + <key>match</key> + <string>---</string> + <key>name</key> + <string>invalid.illegal.bad-comments-or-CDATA.html</string> + </dict> + </array> + </dict> + <dict> + <key>begin</key> + <string>&lt;!</string> + <key>end</key> + <string>&gt;</string> + <key>name</key> + <string>meta.tag.sgml.html</string> + <key>patterns</key> + <array> <dict> <key>begin</key> - <string>(?&lt;!&lt;/(?i:cfscript))&gt;</string> - + <string>(DOCTYPE)</string> + <key>captures</key> + <dict> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.doctype.html</string> + </dict> + </dict> <key>end</key> - <string>&lt;/((?i:cfscript))</string> - + <string>(?=&gt;)</string> + <key>name</key> + <string>meta.tag.sgml.doctype.html</string> <key>patterns</key> <array> - <dict> - <key>include</key> - <string>source.js</string> - </dict> <dict> <key>match</key> - <string>//.*?((?=&lt;/cfscript)|$\n?)</string> - <key>name</key> - <string>comment.line.double-slash.js</string> - </dict> - <dict> - <key>begin</key> - <string>/\*</string> - <key>end</key> - <string>\*/|(?=&lt;/cfscript)</string> + <string>"[^"&gt;]*"</string> <key>name</key> - <string>comment.block.js</string> + <string>string.quoted.double.doctype.identifiers-and-DTDs.html</string> </dict> </array> </dict> + <dict> + <key>begin</key> + <string>\[CDATA\[</string> + <key>end</key> + <string>]](?=&gt;)</string> + <key>name</key> + <string>constant.other.inline-data.html</string> + </dict> + <dict> + <key>match</key> + <string>(\s*)(?!---|&gt;)\S(\s*)</string> + <key>name</key> + <string>invalid.illegal.bad-comments-or-CDATA.html</string> + </dict> </array> </dict> - - <!-- CFOUTPUT --> + <dict> + <key>include</key> + <string>#coldfusion-script</string> + </dict> + <dict> + <key>include</key> + <string>#cffunction</string> + </dict> <dict> <key>begin</key> - <string>(?:^\s+)?&lt;((?i:cfoutput))\b(?![^&gt;]*/&gt;)</string> - + <string>(?:^\s+)?&lt;((?i:style))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> - <string>entity.name.tag.cfoutput.cfm</string> + <string>entity.name.tag.style.html</string> </dict> </dict> - <key>end</key> - <string>&lt;/((?i:cfoutput))&gt;(?:\s*\n)?</string> - + <string>&lt;/((?i:style))&gt;(?:\s*\n)?</string> <key>name</key> - <string>meta.tag.cfoutput.cfm</string> - + <string>source.css.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> - <key>contentName</key> - <string>meta.scope.output.cfm</string> <key>end</key> - <string>(?=&lt;/(?i:cfoutput))</string> + <string>(?=&lt;/(?i:style))</string> <key>patterns</key> <array> <dict> <key>include</key> - <string>$self</string> + <string>#embedded-code</string> + </dict> + <dict> + <key>include</key> + <string>source.css</string> </dict> </array> </dict> </array> </dict> - - <!-- CFQUERY (SQL Embedded) --> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfquery))\b(?![^&gt;]*/&gt;)</string> - <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> - <string>entity.name.tag.cfquery.cfm</string> + <string>entity.name.tag.cfquery.html</string> </dict> </dict> - <key>end</key> <string>&lt;/((?i:cfquery))&gt;(?:\s*\n)?</string> - <key>name</key> - <string>meta.tag.cfquery.cfm</string> - + <string>source.sql.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> - <string>(?&lt;=&gt;)</string> + <string>&gt;</string> <key>end</key> <string>(?=&lt;/(?i:cfquery))</string> - <key>name</key> - <string>source.sql.embedded</string> <key>patterns</key> <array> + <dict> + <key>include</key> + <string>#embedded-code</string> + </dict> <dict> <key>include</key> <string>source.sql</string> </dict> </array> </dict> </array> </dict> - - <!-- Any ColdFusion tag --> <dict> <key>begin</key> - <string>&lt;/?((?i:cf)([a-zA-Z0-9]+))(?=[^&gt;]*&gt;)</string> - - <key>beginCaptures</key> + <string>(?:^\s+)?&lt;((?i:script))\b(?![^&gt;]*/&gt;)</string> + <key>captures</key> + <dict> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.script.html</string> + </dict> + </dict> + <key>end</key> + <string>(?&lt;=&lt;/(script|SCRIPT))&gt;(?:\s*\n)?</string> + <key>name</key> + <string>source.js.embedded.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + <dict> + <key>begin</key> + <string>(?&lt;!&lt;/(?:script|SCRIPT))&gt;</string> + <key>end</key> + <string>&lt;/((?i:script))</string> + <key>patterns</key> + <array> + <dict> + <key>match</key> + <string>//.*?((?=&lt;/script)|$\n?)</string> + <key>name</key> + <string>comment.line.double-slash.js</string> + </dict> + <dict> + <key>begin</key> + <string>/\*</string> + <key>end</key> + <string>\*/|(?=&lt;/script)</string> + <key>name</key> + <string>comment.block.js</string> + </dict> + <dict> + <key>include</key> + <string>source.js</string> + </dict> + </array> + </dict> + </array> + </dict> + <dict> + <key>begin</key> + <string>(?:^\s+)?&lt;((?i:cfscript))\b(?![^&gt;]*/&gt;)</string> + <key>captures</key> + <dict> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.script.html</string> + </dict> + </dict> + <key>end</key> + <string>(?&lt;=&lt;/(cfscript|CFSCRIPT))&gt;(?:\s*\n)?</string> + <key>name</key> + <string>source.js.embedded.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + <dict> + <key>begin</key> + <string>(?&lt;!&lt;/(?:cfscript|CFSCRIPT))&gt;</string> + <key>end</key> + <string>&lt;/((?i:cfscript))</string> + <key>patterns</key> + <array> + <dict> + <key>match</key> + <string>//.*?((?=&lt;/cfscript)|$\n?)</string> + <key>name</key> + <string>comment.line.double-slash.js</string> + </dict> + <dict> + <key>begin</key> + <string>/\*</string> + <key>end</key> + <string>\*/|(?=&lt;/cfscript)</string> + <key>name</key> + <string>comment.block.js</string> + </dict> + <dict> + <key>include</key> + <string>source.js</string> + </dict> + </array> + </dict> + </array> + </dict> + <dict> + <key>begin</key> + <string>&lt;/?((?i:body|head|html)\b)</string> + <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> - <string>entity.name.tag.cfm</string> + <string>entity.name.tag.structure.any.html</string> </dict> </dict> - <key>end</key> <string>&gt;</string> - <key>name</key> - <string>meta.tag.any.cfm</string> - + <string>meta.tag.structure.any.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> - - <!-- Coldfusion Comment --> <dict> - <key>include</key> - <string>#coldfusion-comment</string> + <key>begin</key> + <string>&lt;/?((?i:address|blockquote|dd|div|dl|dt|fieldset|form|frame|frameset|h1|h2 |h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|menu|pre)\ b)</string> + <key>captures</key> + <dict> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.block.any.html</string> + </dict> + </dict> + <key>end</key> + <string>&gt;</string> + <key>name</key> + <string>meta.tag.block.any.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + </array> + </dict> + <dict> + <key>begin</key> + <string>&lt;/?((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite |code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|la bel|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script| select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot |th|thead|title|tr|tt|u|var)\b)</string> + <key>captures</key> + <dict> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.inline.any.html</string> + </dict> + </dict> + <key>end</key> + <string>&gt;</string> + <key>name</key> + <string>meta.tag.inline.any.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + </array> + </dict> + <dict> + <key>begin</key> + <string>&lt;/?([a-zA-Z0-9:]+)</string> + <key>captures</key> + <dict> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.other.html</string> + </dict> + </dict> + <key>end</key> + <string>&gt;</string> + <key>name</key> + <string>meta.tag.other.html</string> + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + </array> </dict> - - <!-- Other Tags --> <dict> <key>include</key> - <string>text.html.basic</string> + <string>#entities</string> + </dict> + <dict> + <key>match</key> + <string>&lt;&gt;</string> + <key>name</key> + <string>invalid.illegal.incomplete.html</string> + </dict> + <dict> + <key>match</key> + <string>&lt;(?=\W)|&gt;</string> + <key>name</key> + <string>invalid.illegal.bad-angle-bracket.html</string> </dict> </array> - - <!-- Reused Partitions? --> <key>repository</key> <dict> - <key>coldfusion-comment</key> + <key>cffunction</key> <dict> <key>begin</key> - <string>&lt;!---</string> - + <string>&lt;(cffunction)</string> + <key>captures</key> + <dict> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.cfml</string> + </dict> + </dict> <key>end</key> - <string>---&gt;</string> - + <string>&gt;</string> <key>name</key> - <string>comment.block.cfm</string> - + <string>meta.tag.language.cfml.function</string> + <key>patterns</key> + <array> + <dict> + <key>captures</key> + <dict> + <key>0</key> + <dict> + <key>name</key> + <string>string.quoted.double.cfml</string> + </dict> + <key>1</key> + <dict> + <key>name</key> + <string>punctuation.definition.string.begin</string> + </dict> + <key>2</key> + <dict> + <key>name</key> + <string>entity.name.function.cfml</string> + </dict> + <key>3</key> + <dict> + <key>name</key> + <string>punctuation.definition.string.end</string> + </dict> + </dict> + <key>match</key> + <string>(?&lt;=name=)(")([A-Za-z$_0-9]+)(")</string> + </dict> + <dict> + <key>include</key> + <string>source.cfml</string> + </dict> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + </array> + </dict> + <key>coldfusion-script</key> + <dict> + <key>begin</key> + <string>#</string> + <key>end</key> + <string>\#</string> + <key>name</key> + <string>source.coldfusion.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> - <string>#coldfusion-comment</string> + <string>#embedded-code</string> </dict> </array> </dict> - <key>embedded-code</key> <dict> <key>patterns</key> - <array/> + <array> + <dict> + <key>include</key> + <string>#php</string> + </dict> + <dict> + <key>include</key> + <string>#ruby</string> + </dict> + <dict> + <key>include</key> + <string>#smarty</string> + </dict> + <dict> + <key>include</key> + <string>#python</string> + </dict> + <dict> + <key>include</key> + <string>#javascript</string> + </dict> + </array> </dict> - <key>entities</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>&amp;([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);</string> <key>name</key> <string>constant.character.entity.html</string> </dict> <dict> <key>match</key> <string>&amp;</string> <key>name</key> <string>invalid.illegal.bad-ampersand.html</string> </dict> </array> </dict> - <key>string-double-quoted</key> <dict> <key>begin</key> <string>"</string> - <key>end</key> <string>"</string> - <key>name</key> - <string>string.quoted.double.cfm</string> - + <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> - <key>string-single-quoted</key> <dict> <key>begin</key> <string>'</string> - <key>end</key> <string>'</string> - <key>name</key> - <string>string.quoted.single.cfm</string> - + <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> - <key>tag-generic-attribute</key> <dict> <key>match</key> <string>\b([a-zA-Z\-:]+)</string> - <key>name</key> - <string>entity.other.attribute-name.cfm</string> + <string>entity.other.attribute-name.html</string> </dict> - <key>tag-id-attribute</key> <dict> <key>begin</key> <string>\b(id)\b\s*=</string> - <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.other.attribute-name.id.html</string> </dict> </dict> - <key>end</key> <string>(?&lt;='|")</string> - <key>name</key> - <string>meta.attribute-with-value.id.cfm</string> - + <string>meta.attribute-with-value.id.html</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>"</string> - <key>contentName</key> - <string>meta.toc-list.id.cfm</string> - + <string>meta.toc-list.id.html</string> <key>end</key> <string>"</string> - <key>name</key> - <string>string.quoted.double.cfm</string> - + <string>string.quoted.double.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <dict> <key>begin</key> <string>'</string> <key>contentName</key> - <string>meta.toc-list.id.cfm</string> + <string>meta.toc-list.id.html</string> <key>end</key> <string>'</string> <key>name</key> - <string>string.quoted.single.cfm</string> + <string>string.quoted.single.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> </array> </dict> - <key>tag-stuff</key> <dict> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-id-attribute</string> </dict> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> + <dict> + <key>include</key> + <string>#coldfusion-script</string> + </dict> <dict> <key>include</key> <string>#embedded-code</string> </dict> + <dict> + <key>match</key> + <string>.var\s</string> + <key>name</key> + <string>variable.other</string> + </dict> + <dict> + <key>begin</key> + <string>.&lt;cffunction\sname=('|")1</string> + <key>contentName</key> + <string>entity.name.function</string> + <key>end</key> + <string>'|"1</string> + <key>name</key> + <string>meta.tag.other</string> + </dict> + <dict> + <key>begin</key> + <string>[^\#"'][a-zA-Z0-9\.]*.\(</string> + <key>contentName</key> + <string>support.function</string> + <key>end</key> + <string>\)+</string> + <key>name</key> + <string>support.function</string> + <key>patterns</key> + <array> + <dict> + <key>match</key> + <string>("|')[^\.].+("|')</string> + <key>name</key> + <string>string</string> + </dict> + <dict> + <key>match</key> + <string>,</string> + <key>name</key> + <string>meta.tag</string> + </dict> + </array> + </dict> </array> </dict> </dict> - <key>scopeName</key> <string>text.html.cfm</string> - <key>uuid</key> <string>97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14</string> </dict> </plist> diff --git a/info.plist b/info.plist index 58d57c6..525f8f1 100644 --- a/info.plist +++ b/info.plist @@ -1,615 +1,599 @@ <?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>contactEmailRot13</key> <string>[email protected]</string> - <key>contactName</key> <string>Rob Rohan</string> - <key>description</key> <string>Support for the ColdFusion web development environment.</string> - <key>mainMenu</key> <dict> <key>items</key> <array> - <!-- CF Tags --> <string>C8F9D7A6-D447-4C16-B566-BE46335B1067</string> - <!-- CF Functions --> <string>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</string> <string>------------------------------------</string> - <!-- second isdefined (not sure if we should keep this) --> <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> - <!-- form variable --> <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> - <!-- url variable --> <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> </array> - <key>submenus</key> <dict> <key>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</key> <dict> <key>items</key> <array> <string>0AF4E3E4-8638-4EAD-B182-A4FE571E9974</string> <string>38EB1CC2-4A1A-4C37-9D69-19D81129C5DC</string> <string>E0D7DCCA-9801-4DD5-9C26-3B607BEF7135</string> <string>241129A8-4AF3-4005-B276-6F431B5CB3F2</string> <string>8AE48664-E323-4DF9-BED2-CE700CAC7C15</string> <string>08392E18-5D55-41CB-BE64-7B091492E7BF</string> <string>9AEFE392-91BE-4968-8FF8-8A2C9D51D4CC</string> <string>67423190-2729-4C30-B10D-51B7DC3FAB85</string> <string>1B072993-0FFD-44B7-8C6D-3F9D60AF9E7B</string> <string>B8817D6A-B326-48F9-9E35-B28778A79412</string> <string>157C15A0-D535-4EAB-8173-6D6EB0906173</string> <string>0E400696-4C11-4072-9DAD-7BFF6F7789BE</string> <string>5A2941B5-2D73-4348-AB92-932665EB6E1D</string> <string>902C51B4-E4E3-4B2C-BA03-769FC6AC0867</string> <string>5CF87863-EBA1-49BE-AB51-016A2D0FDA80</string> <string>A72AC858-A593-4758-894F-266F9925990D</string> <string>6E59F119-65E3-4D1F-B393-121208A9A83F</string> <string>E336E487-B1EA-449C-9B32-4C5994136CEA</string> <string>90B1EE50-DAC5-4748-8415-5C3ABB38CFD5</string> <string>784AAEB3-2367-4275-95E0-DFDBE61E9423</string> <string>D5310F63-357F-4E8A-9583-26F569D309EB</string> <string>1ADF5606-9DC3-413F-8BC2-5E54E7BAC4FF</string> <string>28364618-9329-4501-98EC-852D28D2F59A</string> <string>EA2AA961-32E7-4B4B-85C8-0F458AC6E671</string> <string>A14677C7-FB24-4A35-B9F5-F764C2EFE00E</string> <string>5736162D-BDF6-4C94-8F3C-8F4CEB38E349</string> <string>C6C27604-1D24-4EC3-B40D-BD1FF6196DF8</string> <string>96D4FDBD-4A7D-42E4-BF7A-AB366E22758B</string> <string>E1BBA1F0-05C7-4EA0-87BA-FB0FC5D1CAED</string> <string>C8C2C389-AEE0-4CE2-8944-A7EEEFB9B680</string> <string>36F4B163-2ACD-48F1-8E72-365E54EB7811</string> <string>5D0E9DF4-6631-419C-AEEE-7710EE30502F</string> <string>0A3097F1-36A8-4009-8501-CC5B9349072E</string> <string>C28091B5-3245-4E3C-BC49-38AAB093D00F</string> <string>1D9BEE6E-907F-430A-BD62-2DF38A454B3E</string> <string>B8DC9CF1-AFF5-44E4-B9A8-42093D829889</string> <string>BEDB5CCC-7FF1-4C78-8169-2B58BFB2C449</string> <string>E6EE6F14-372D-469B-B31F-827A54CFC5E3</string> <string>DB5DE93A-DA9A-40E9-B469-EF8337A11CBE</string> <string>63B626CD-2818-42F2-BD90-DE112A8DEF7A</string> <string>5C3D7157-DFC0-4762-B059-C10F1A098089</string> <string>BD84E1FB-DCA2-493E-887E-1A1330DD6EA9</string> <string>CED5A340-3643-4F34-A8ED-A9FB99008300</string> <string>AB4A8782-7466-4B5D-A180-96E0BD19C050</string> <string>D01E4126-187A-4275-8583-DFA44FE3BB3C</string> <string>F9725187-DAE2-43BB-9209-BAF4F709AD72</string> <string>C83F3775-A62D-425B-B05E-C6A58C929399</string> <string>6674FAC2-9201-4D0D-BAA5-E35D64BDADDC</string> <string>53E1E9D3-8F53-4CFE-8ADD-83AC13969D24</string> <string>415DDDAF-1163-49E7-8D5B-3B6CD1A27A06</string> <string>B2FCBECB-D1E0-4BF4-B046-5A9C4A6475F9</string> <string>601BA2FE-EA4D-4B9C-A8EF-646A9E9626DD</string> <string>B14D6A84-2B4D-4FF8-99CB-E2B41B0E00BF</string> <string>29745C05-70EC-418A-A7E1-E60EE6042A95</string> <string>2FB6FDE3-F8F0-47A1-AE6D-AA3895A489CD</string> <string>0B69D306-8DF0-4494-87AC-B8E92091E0E6</string> <string>9AA75F85-02C0-4006-9D95-F7EC2728A050</string> <string>192D1402-A2E5-43F1-B0C5-990853DB5D98</string> <string>8BBB6187-A1D9-43AF-AF72-CDF3BB8B0A76</string> <string>DE1C603E-D791-469F-99D3-69E17B9B41EB</string> <string>FA01E47F-EB01-4FE1-9EB6-96FDEB923E70</string> <string>AA6262C5-CA32-415E-B666-D2FBF93E0905</string> <string>80B9754E-47ED-46D6-8BA5-80744B0FBE4B</string> <string>9A1343CB-5E9E-45A2-8D21-B4959C412B6E</string> <string>622A22FB-207B-4322-BC6C-C2B3D605AF00</string> <string>4DD466D2-0B15-4E06-8446-5AFBFC8B4128</string> <string>183709C1-9414-4A25-89FB-A0D9A7E59D27</string> <string>35060F61-EF40-4046-BF12-1AB2748884A1</string> <string>44EA1298-2450-498B-82F6-1BF1BC1FFE59</string> <string>29486C8D-7A9A-4EE0-B6A3-34C77A7D253E</string> <string>7F70512F-517F-4361-89ED-13E8C3BD98F0</string> <string>2A8760F9-6ED1-4066-B996-5E490B5A17EF</string> <string>9187A792-54F4-4773-A2D7-EB5D207D1A54</string> <string>F0AFF0A1-90FA-424F-A6AF-6EA6EC1BB225</string> <string>026FDCF1-E739-42E4-925D-59D80EE7FF05</string> <string>50182FB9-0179-4CF6-9AD7-4E7BC725C594</string> <string>3B19D8BC-5389-4263-A539-160170F7DFB1</string> <string>B096E910-EE96-4E63-BB46-EB12616C80F6</string> <string>08743309-6431-44D2-8A38-926516B04BEF</string> <string>A4876D40-55A7-44A0-9CDD-BCF62A621FC3</string> <string>5C441A88-2F12-4C54-83F8-81A62F735F88</string> <string>FDDBDC40-D1D9-4981-92DE-30CA475BC8FA</string> <string>3C93CAC9-0DC3-4371-8E5F-2727B0A282BD</string> <string>6F5A4D8F-DE7C-4663-9D39-7BF23D84769E</string> <string>75FFC09D-CB71-49CF-AB01-3DA8C44F29F3</string> <string>97DD90F8-5334-46A0-B973-C59F357D6C31</string> <string>3ED1297F-4C77-4187-9356-4262D3F28625</string> <string>F36E8F58-CDBD-4E42-A64F-9D05BE2D49B9</string> <string>1B6D6622-49BD-4EAB-B521-B3D1ACF2E4B1</string> <string>E09B46CF-DDE0-4B40-B7AF-93C005F23BAB</string> <string>A607B362-68CB-4AE3-BE72-575EB7CBA55A</string> <string>A57CC7BE-F39A-4B64-908D-44EA058C294F</string> <string>0C5234DB-A0F6-4BE2-AF28-5276ED3F81BB</string> <string>BC74CDF9-65E1-4FD0-A939-110CF53F3F67</string> <string>D6CFEC97-357A-4EBD-9D95-F89FECD4ED66</string> <string>293B3EF2-892E-4FF9-BB3B-82AE01FFA38D</string> <string>24AEB6C9-9CDE-478C-9C08-5CB1825321AE</string> <string>4417C4C8-F581-41FC-96FF-76A28A1F0640</string> <string>BC022681-5DE4-4E5C-8638-93EF655F7B0D</string> <string>47BD7B3C-4316-4C5B-AD7D-596D90D64A7C</string> <string>ED205418-D60B-41CE-9942-6855C78C65F6</string> <string>AEA7BB76-4231-41DC-829C-D093F7BF28E5</string> <string>F29A9DA7-B58E-4839-8664-2C99C5679384</string> <string>7423A717-6340-4CEC-9151-2B882D052CB9</string> <string>6E621AA5-5304-4DCE-82B9-820FDB78C5FE</string> <string>21B96169-6556-4436-B3B2-4556A6372567</string> <string>7A62D445-BDCF-4C67-8B71-35255FACC231</string> <string>9B25BE9A-A2E8-4BA6-A1CD-A545C6A3AEDE</string> <string>AD74D8BA-A774-4748-BF7E-22A6E94194ED</string> <string>8743E910-AD98-42C7-AC9D-4EBD26B54456</string> <string>5EB9976E-F76E-40FE-828F-22B393BA59AE</string> <string>8A82A0E0-7396-436B-A3FD-46680599A33A</string> <string>B36FA4B0-F6AE-4489-97D1-54BFE773A560</string> <string>281422A7-AF82-45BF-8707-4242A22FA908</string> <string>CD089D33-F3B3-4BC8-9650-B7CF29B877BF</string> <string>18A3925F-BF0F-4FAF-B45C-C02B2D4C4CB1</string> <string>7188A872-4A9F-4A05-ADCA-46D83E911D2D</string> <string>6322FE39-5B27-49EF-A632-A6073EDCE0C4</string> <string>BEC86CCF-C220-4B07-9ACD-320238D1FE48</string> <string>1F61F24F-166C-4D2E-98B0-7BA454B21619</string> <string>5BAF7E27-FEAB-43E0-899F-ABE9DA500FD0</string> <string>EE49E017-4812-4CAA-8CCC-29DAB3BE7B64</string> <string>97F31F3F-B885-4DE8-B784-5582990C21CD</string> <string>5D2DC339-C6E8-4919-9500-DD24DC9D2F73</string> <string>9E6E0847-D0DB-435D-A129-CA90BE6B9210</string> <string>82B42D60-DC77-47AA-B433-14969E2A2CEB</string> <string>DE1DB107-EC48-4128-B400-203B72AFD40F</string> <string>2051A0AE-51E2-413F-9CCB-92826FCD5C99</string> <string>2DD711BA-8C2D-4AF4-85C2-C42733743D0A</string> <string>5C998560-6284-4F59-A6F9-420962E130E2</string> <string>5DBF4A9D-7C3E-4FAD-B6DE-16AB145F081B</string> <string>C3F1BC8E-892F-4FB5-8A63-F8225B42CCFC</string> <string>3B7767FB-E117-4543-B27C-C178D5F451DF</string> <string>618D41F8-8A13-42B6-9000-551AA2DF9FA3</string> <string>ACB55DF1-EE3F-4B20-A3CA-3DC63018212B</string> <string>466D3581-0875-4E99-952A-0650CB84D33D</string> <string>17CFEC94-0BF5-40CD-97DD-79A2CAECB041</string> <string>5C46558A-599C-427F-8A7E-0343F1BED079</string> <string>D2675FE6-79EF-40C6-A864-A5C6F092BA4C</string> <string>D61CD41D-9838-4169-A754-424345AC4601</string> <string>4C31384B-2B27-4C39-B2BB-CC2CA57B659A</string> <string>02261555-8147-43DF-9D49-AEE4F58E1619</string> <string>3757F0B8-F3B0-4272-9F6E-8968CE670387</string> <string>3514ADDF-C60D-4A16-9346-11EB7A2AA61A</string> <string>90E0EBD1-EC9F-425B-ACC3-06EFAB5F1F69</string> <string>41ED9831-365B-4D4F-AF8D-2864343E271F</string> <string>696A8BD3-EF4F-4A4C-A264-93BE6781D657</string> <string>40051E46-ECE8-4A07-B600-934A3B482EFC</string> <string>2016AF2A-1AC1-45A8-BCA0-A52F23142863</string> <string>FD148128-FF2A-4CFE-99F6-FF43653FE8EA</string> <string>6C79157D-36F9-4F91-B012-BDD27622FF9B</string> <string>E45A3C54-88D7-4E4A-8092-56854FE825BE</string> <string>49443738-7978-4865-A1AC-7358A0BEE2DE</string> <string>C17555B3-A84A-404B-AECA-3F11CA9ABF0D</string> <string>22ECD416-BC42-4C13-8BAF-F435A144A56E</string> <string>E0363D86-A148-44D2-9AF9-45A2A57D1676</string> <string>9992024A-E07D-4E29-9B35-F85038E890AF</string> <string>23E6B8AA-CA8F-4CCC-BC29-76A027849595</string> <string>28FE5A03-F962-4ECE-AF92-EE3436D20664</string> <string>0D55F7C2-16A2-4B78-B390-EF780FF0F2EC</string> <string>D9676E4C-3E0A-4886-8F2A-03E25DB4D44C</string> <string>2C83D486-C0A5-4493-8562-BEA824BAD2D7</string> <string>817F3C02-47AD-4553-9DE2-BDB0EC97BC9F</string> <string>FEF3A4E6-7B4E-47B6-A529-ED41EDA41002</string> <string>917BA410-EC71-492D-8472-A3C2CED279FA</string> <string>6C78FA7D-0B84-4E9A-A063-77490073E99F</string> <string>0F018E42-BB09-4631-B11E-EDDD267C8DFF</string> <string>068FD2EE-B721-4DE3-A4E2-F98476C0530A</string> <string>9A231D17-D36C-4081-B1EE-E3F5016040C1</string> <string>E648C975-48FA-4818-89B6-34913675E41D</string> <string>E7FD5C33-5516-4DB0-A553-B832515D17D4</string> <string>F3102771-3AA4-492D-AD42-2FDB4F686662</string> <string>C3AE011B-75E2-45AF-B427-864997717FE2</string> <string>519D474D-FE82-4419-9D5F-AA88D817EDE6</string> <string>6816281D-E43D-4DEC-AC2B-0E0756A00EEB</string> <string>25ACCCC1-401C-4084-80DE-6CFFF6FDEA20</string> <string>41E4F63F-C59D-4712-B29A-9CC83D717469</string> <string>63CA1E9E-34AB-4EDD-B6CC-16C22EA5B777</string> <string>2B8BC0E7-93C3-4DE2-957E-8212F6E373C3</string> <string>19400E23-B260-4E85-AFFD-109708545A80</string> <string>312DD333-8664-4C27-9C67-ED8B285579D4</string> <string>9BDE4AC0-BEC2-4585-AEC7-AD60767AFBEE</string> <string>9D47F8B3-B009-418B-8AB9-0E72D33F137D</string> <string>79EDA618-F9E9-4A72-8A7F-DDC0D6826C19</string> <string>0BA580D0-B978-48C0-8CEB-F78042E9F58F</string> <string>AE303AF0-FAE2-4C2F-A5BF-0745D3161289</string> <string>228F7B63-E8C8-48EF-9613-A32CAB3FF100</string> <string>CB454D76-239A-40D2-B194-43CA6DDD9B8D</string> <string>CBEAE712-0FC9-4210-B157-DC5C264BFCBF</string> <string>8F41DFB0-285F-4FA7-A21D-210832BEBD60</string> <string>81541C90-0980-47A1-9B9B-9F3E750016C7</string> <string>E651A0E3-0EC3-45AC-B7D0-92E2DAD1F733</string> <string>8D4E0C06-8D06-4871-9D92-5C72B18A5562</string> <string>D455BE22-95B8-477F-BA2B-22C8C33D2C85</string> <string>1262430C-CE62-4585-9EFC-7D5D001C5F24</string> <string>5A00FE89-14AB-4DCA-B601-5FEA6C36F8F4</string> <string>F82AABEA-89D3-4DE6-8B6C-3B7BDC194667</string> <string>DEB3845A-FE19-4B41-84AD-EAA44A4BD1DB</string> <string>3B74EAA8-B431-423C-971B-09349375FE3E</string> <string>FA705D08-0DFD-4C3B-AB79-FF7719E9258D</string> <string>C02F0BE6-CDE7-489F-8B1D-C63CD15AEEC6</string> <string>2559432A-5071-4C85-B71B-A546326C4DE6</string> <string>2358C3ED-39E9-4CB1-BBE0-C2C0419F4E9C</string> <string>C91A69A3-2ECA-4F98-8777-E142F6777683</string> <string>F78D0262-1B71-4AD6-8BB5-C2E9DC9BB083</string> <string>8FC4AFD0-98E2-414D-8F80-ED36E5BD977A</string> <string>80ECE03A-C2E3-4334-8F7B-2A2ED7BC80A7</string> <string>0A20DB84-AAEF-4B95-A19F-18D6F3694798</string> <string>31B2DCFD-1049-49CF-BCA8-FAE5D0D4917D</string> <string>DDE93618-33D9-494A-93F0-1E0CAC672042</string> <string>DD2F9E4A-E204-4CEF-ADCD-18B523A65966</string> <string>44379253-BF02-4341-8BB2-B40CD39ED593</string> <string>DF3F5402-8B88-40D3-81F4-B960A6174610</string> <string>C22A5FC3-65EA-4234-85F2-2B43DFF811FF</string> <string>041E3434-05CD-49B2-BFC3-4E3BE5643A65</string> <string>829C9A8E-323D-44DA-BD6F-72AC150755A1</string> <string>E55FC014-0F85-4A3E-884D-F7C4F3179659</string> <string>C4D060C7-FF47-4799-AD06-108B3A757EB6</string> <string>FB98EFB0-2C9C-4037-96CF-5C0644041281</string> <string>8330E508-BE78-4713-BF73-2C8B08C02883</string> <string>2452CEE2-65EC-4FF1-8E1E-C77876F1D14E</string> <string>1B854256-5B23-4FCC-8367-2330D94D200E</string> <string>BCF434DF-79AB-4F95-83E0-8D9B0163956B</string> <string>F93D53FB-7669-4780-B53A-16276844A5BD</string> <string>89150D95-04F4-4A3B-B885-20A9C95E3FBA</string> <string>4F0429B6-0FB1-4CF6-BCB8-6350EBD89C35</string> <string>998B082A-A679-4494-B66C-69AA8256E4D2</string> <string>E03C0C8A-5CBA-4654-A4BD-EB6500901709</string> <string>62B6DE6D-751C-4599-8094-6F3EA39F2517</string> <string>ED3D3507-B8D9-4A83-88B7-CAD0F46A664A</string> <string>958C7148-B01A-4FE8-AA42-88CADB026CBA</string> <string>DEF118D7-4325-45E5-9AFC-77C80839A76F</string> <string>AB98AFE4-E946-4CC6-B453-B6E478590152</string> <string>3B4924D7-1FCB-4D61-85C8-63E69BFC808F</string> <string>4640A976-0C9E-45AA-912F-AD2EEF351E60</string> <string>5A3FFFCD-C7A2-457E-8D6E-151680293EBD</string> <string>CA44FB3A-353F-418C-AC80-1DC89F4D65BF</string> <string>0CC8642F-3BE7-45DA-86CB-179A4AE9C264</string> <string>FD813CA3-8050-4E6A-815A-9F083D80A2F8</string> <string>28CCC198-2A33-4677-8B8E-4774BF542C54</string> <string>9038D5E1-01AC-41B8-BEB2-681702E589FF</string> <string>8B3912D3-1C28-4DF2-8883-6C4B05377278</string> <string>4C10EFDF-A3CE-48E3-8B9B-5174B0163EC2</string> <string>24F07D3F-9B21-4035-A519-CF84DA5DB543</string> <string>A0B83920-09E1-4361-8597-5B05BA1A23F9</string> <string>5C8F03CB-AAD6-42F4-B20B-705D101354C7</string> <string>C25BD8B9-99B8-429E-9499-BEA2C3C2F8C0</string> <string>849C7A84-7E2B-4420-AE9D-FEFB11CA4A3F</string> <string>67A5B7BD-0E56-477D-A38C-B101A2719988</string> <string>56525EF4-4A5C-4415-B2D9-9D135CA32157</string> <string>9C179D97-C855-420C-8689-642EB11AC767</string> <string>F0FB9A33-FFB9-43D3-847D-AEF559D86B68</string> <string>7B0D2A4C-CF10-4985-AEE3-212D3C479C38</string> <string>ADA257DD-BB15-4CFD-BB53-55C7E1A30365</string> <string>7F5D11B3-45DE-41E6-B5D1-71F370315500</string> <string>92F58CD9-AE3E-4553-BA7B-B10FD1376B2F</string> <string>259B5FFC-6CB8-4141-8270-CCEF88550A04</string> <string>C953538A-5B40-4D20-B920-EE242B415A21</string> <string>C6B47D42-9614-4C5A-A862-81A4E59EFC55</string> <string>AAC6EB2B-2BE9-4CF5-995A-09C4632E5809</string> <string>F8CE823F-8C57-4DAF-957A-C2370F49EB8D</string> <string>DA3FB6A9-6C8A-47F1-932B-76E9AC9FF4A8</string> <string>30468398-BDF8-4221-B8C1-108D660B5462</string> <string>317DCAFC-B419-43D1-9516-CB020D48FE08</string> <string>7FFE3035-50A2-43BC-9A6A-D3392DD711DA</string> <string>67FC60DD-74BC-40D8-96F5-77E90D45E820</string> <string>BE836A4A-003B-43B6-845D-E19A813D7E57</string> <string>523CD084-3B13-46DB-AB6F-8961EC5914CB</string> <string>5FA14C8D-B9CA-4635-B0ED-A9F6E8133716</string> <string>DF07EEE5-5D1C-4226-921C-862390ED60D9</string> <string>02288997-F2FE-4F78-86B5-7EB341820E31</string> <string>09B68D0D-9DF3-4183-A57C-12352C1F992A</string> <string>B040F5CB-43F8-442C-88D7-0C8B8FDB8989</string> <string>BA93AEF3-2AF9-4987-820C-71788DE2DEF3</string> <string>A28980B1-0C97-4C38-AC73-788170AE1D32</string> <string>4A1ADF4A-5EDD-4D82-8141-B91E66BFD80D</string> <string>6D88583E-821E-4921-AABD-997C5738F059</string> <string>EC3B9C82-CD02-4EDE-B292-457CC8774E41</string> <string>AE66DCD8-09E8-4EED-BAA6-031BACF237A0</string> <string>A56B5F64-EF48-4000-B7D4-78B6C0E04CC1</string> <string>11346CB0-A4DE-4DFF-BB31-E2D4DCDD14FC</string> <string>206C70C1-010B-43F9-BC75-0CA766DB2DD3</string> <string>B97E295E-62AD-4DD6-9E2D-625B016CC5AA</string> <string>17180447-13E1-4330-A9DD-18D9DD6B8C2B</string> <string>DAF8DD98-B342-4746-B017-EA3AA8861EE9</string> <string>2FD9FC81-619B-4256-AFDB-4E1B4EB3B479</string> <string>65714417-FFB2-441B-8A92-E660882D3A9B</string> <string>CA71EDF5-8BDC-4CEF-A25B-91AD55BA9C07</string> <string>A0DFAD24-FBA0-4867-841C-2DDA8B863454</string> <string>E1F8DF31-6867-4D7B-96C1-842A860C3CF1</string> <string>A8EEDB00-F4F2-4EC3-AB22-14A5E331D89C</string> <string>C4BE4DC7-045B-470E-9BEE-6438C19D6D51</string> <string>E411CA38-BF07-480C-AA82-864F2AF548B6</string> <string>300C9DE5-E673-4A8F-B678-8A86E6AC24F6</string> <string>31A1B000-84FE-4FC6-B941-B2080F6908E9</string> <string>4554BD19-8A33-460E-BDC8-B2E4525D508F</string> <string>48BF60D2-E9C1-4F1E-9FF8-BB08FC6F7A32</string> <string>B09C244B-F8E0-4069-A4FF-5029DA586F72</string> <string>6D3C12F2-DF3C-40F8-B47E-381FDD0A981A</string> <string>60F3E813-2319-4310-9985-B7B50C0A9A33</string> <string>32B99607-5DE8-4560-8079-2D84CD4E0001</string> <string>F34A2296-6FF0-4090-ABAB-2C9D6F7EF482</string> <string>14E4A176-FB73-41C7-BCF5-B11F90733CE9</string> <string>D000FBCE-5C70-45C2-B9D2-86C42500568C</string> <string>6DB8C1A2-09F5-4C4E-B4D8-A75F5E3D76FF</string> <string>07A7E990-237A-43F9-A87E-8EA14DD81333</string> <string>C245FB6E-95C2-4D6E-935F-A7F470328E49</string> <string>0528B454-B8BC-466B-9AF9-BE68BC77E4E1</string> <string>3D9D15C5-2E00-4332-9169-FC35542D1BEB</string> <string>96265680-CFE2-404F-B614-B83B78AC1A0C</string> <string>245A194E-803F-4951-BF63-19D639AA99FB</string> <string>4B02989E-5D1A-497D-8FC1-561E4F2B67AB</string> <string>9CA961D9-F34C-489F-865A-EB20A896C0F6</string> <string>0FA5ADFC-C4D7-45D8-B745-2C0BC538179B</string> <string>696428FC-070E-4D23-ACFD-0469CCC70079</string> <string>2EDD4802-B07E-4CC2-9A88-B563FF05146E</string> <string>286B13D0-E6C9-423C-B593-CD4B59A87E8F</string> <string>041AC446-491D-4416-8E14-E60C8018A0D5</string> <string>EB8C4DE1-8A2A-4C1B-AE5D-57D3FC8281CC</string> <string>5BD2B7EB-5452-420D-BF49-B33C1D4E8706</string> <string>268F708E-DBD4-4E38-9194-7063950783D7</string> <string>DCAD363E-492B-49FD-B84F-43A3F77118CD</string> <string>9072A654-06FA-42D6-950D-90E33975B2EB</string> <string>3F07F52E-724D-4D8D-84E4-D4E87220B020</string> <string>9DE5A98B-BEB2-4F3E-997C-4851CDAD76C5</string> <string>FFADDBFF-B24E-4C06-8C4C-B28F6BD42349</string> <string>538BB22C-E30C-45E4-92D1-F837360785AF</string> <string>40BC17A0-BC89-4D08-A1C0-A54C85E90B46</string> <string>509BDA8F-1AE1-4B62-9E5C-3742AE06167B</string> <string>3F56DF3C-E73E-4133-B4D0-6EA5926E61B3</string> <string>E50E3BBE-8581-4EC4-8875-717CA123463E</string> <string>4E3ABBC1-20D2-4D0F-BC10-A128F85AD5BE</string> <string>BF26D328-E8B2-4255-AB7E-E139FD8161CE</string> <string>087457F5-B8B2-4673-8E60-92430D951D4C</string> <string>A79C2E63-7CBD-453A-AD1A-B4B15A554C6B</string> <string>8FC0283E-CE94-450F-9560-9990FB253D95</string> <string>3FA1DAF0-1259-41F5-B642-872D9FD60297</string> <string>21ADF248-F14F-469F-956B-14251B78B83A</string> <string>92CA447A-F1ED-4C5A-B999-DFE13C587B8C</string> <string>4F173886-8EF8-422A-A368-8E2F1B3699C0</string> <string>FA4CAE63-B259-4A38-943B-88F1444835DB</string> <string>452C6FF5-FF58-4799-841F-786BB2386B5C</string> <string>12C986E9-3511-4179-AA1A-204BF3AC0EBB</string> <string>9C53FE15-1C26-41B5-8ADE-EA902A7FCD89</string> <string>606B7B7B-236D-42DE-AF65-5C9CBE79EDF5</string> <string>C9DDCAF9-7A94-40B8-A355-17CBFD9FB0CB</string> <string>80797385-06D3-45A6-A034-8C5BE53A5419</string> <string>B8181ACC-5FBB-4813-BCBD-42326F575D16</string> <string>C1E197A3-22AB-4EA7-8D06-E53478B70CD6</string> <string>6D8B302B-3980-4B6D-AB18-0642220A1D09</string> <string>4B4BAF15-6DDF-4AEC-A949-C09DF23D3A0E</string> <string>70B7E6F1-FB81-4741-87D7-6E2CDBEBE6CA</string> <string>2A358D34-E286-48DB-8FE4-34957124FE4B</string> <string>F99266AC-C47B-4662-8140-91FC9CD83CD1</string> <string>1F895B4D-8226-4945-9AFB-7680E54A8AF6</string> <string>0CABE9A1-3E50-4516-9EE2-2189D1D87724</string> <string>6DBA82BD-A1CE-40CA-B200-23E82562ACB5</string> <string>956A0059-FFF9-4B14-9072-9B66B8D85BC7</string> <string>65E81A15-9D95-4CE8-B2D1-9952FEF5226F</string> <string>37710819-E241-495B-8EED-4FDCD9BE6A22</string> <string>229077E7-4284-4085-A449-3C5AA8DCF41B</string> <string>710BC149-0A06-48FE-87A7-4CABA810A519</string> <string>A8B0343F-CD2C-41E7-BFE5-133C9AE9675F</string> <string>A67CBED1-95F6-4920-A8D7-E84E650520ED</string> <string>56173E05-CA6A-4773-AB05-050A3BBF0F49</string> <string>40D70647-3C75-4588-9CFC-3448A881F79E</string> <string>67D98396-31F6-4821-BF31-F75F08A92850</string> <string>7E41534A-A1FF-4214-A106-2B721FB1A920</string> <string>B01C3BE2-956D-4E5A-9DE0-2FA6B544DA25</string> <string>96F76523-E10D-4366-BFF0-918D22BA37E9</string> <string>DCBE259C-2268-4194-A4FE-03E53A232FBD</string> <string>F61A0D68-C33F-48F6-B045-B1B3C4EF9525</string> <string>B3617124-733D-47EC-9B2A-FAD4C0397831</string> <string>BD44D578-30A0-4ECF-A8E2-4A23C36BD8DE</string> <string>8AF8F6D9-32FD-4AAB-8453-7A2FDE3FD382</string> <string>4AEAA48E-D914-4EB4-B917-01D00D0C8E0B</string> <string>1CF0F70D-B223-4B80-8454-4AEC0B5A10D2</string> <string>7830F906-A21D-441D-BA1D-E37635247542</string> <string>085B8E6C-388F-456F-882C-B8D3392D61FA</string> <string>A75D991D-240C-43AA-B9A6-553AC44F76FA</string> <string>53B9B5E7-D897-49E4-AEEC-DE94F781AA2B</string> <string>6B126A42-3320-4978-8ADF-F53C600B5795</string> <string>00DA1390-C91E-4583-B83B-CC16F8892239</string> <string>EC7BC99A-B82D-43EC-AEF2-8EB54041CDE6</string> <string>3B195EF9-CCC3-4B2D-91D3-15D514E5F4BF</string> <string>6521B870-750F-4109-8BBF-2910D584C525</string> <string>16F25A48-3166-4E7C-8F80-DC9E61C65645</string> <string>018DC512-CE52-4DCC-B556-DA3A9AD96FE6</string> <string>94993BC1-CB55-4F02-9705-70ABCED8CFC9</string> <string>5622EC10-8A81-4C9F-87C3-E3B6A9B4D96B</string> <string>498615E3-E82E-4CD3-A526-EBAE9F68C7EF</string> <string>217C9FA9-BB27-403B-8CBD-659B64FA6CF4</string> <string>102E8B00-3629-43A3-A2D4-864C6CF0CD32</string> <string>4B01C66D-8A74-4433-A07D-8FE705C7A352</string> <string>9924DCE9-8C1C-4CAE-B232-E9FD07E1B53E</string> <string>9A1B4C8F-EC35-4F05-8AB0-8122EB4B9A93</string> <string>01E0876B-4D91-49AF-937A-7EC39DDDEE79</string> <string>774B14A7-EDC4-4855-9915-6AB8B15D2F68</string> <string>D8D50F69-36E3-45DA-807E-29D1E5914DD8</string> <string>1CFD7E53-FFF7-46A8-9149-49E9F5088E55</string> <string>3E572472-BBF1-4DDA-AFCF-D52B95B0ADFB</string> <string>EBCC36A0-38E4-438D-BB39-6D3AC690C8AF</string> <string>4158361F-D366-4BAA-8CC5-DC46AD449229</string> <string>EE1507E5-F01B-4D73-8EE6-CCFECE98C3F4</string> <string>C280847F-1A0C-47CC-9EE5-168B9973A8BB</string> <string>F54727CC-8F88-4D17-AC6A-B5E4C8AC872F</string> <string>FA9F757A-290F-4E33-92FC-9E6214113E58</string> <string>C772C456-6B38-4987-87CF-D10486D185A9</string> <string>1A402F7D-1B17-4090-BFD6-42BD426FF0A6</string> <string>A80FF473-4E66-4DBF-89E2-3BC1AFC00A0D</string> <string>6A325FC2-6C57-4B2C-9326-3244EAC96A47</string> <string>87D35E2A-FCC1-4496-9198-8BC85C16E97F</string> <string>63538655-54A5-465E-9E8D-9F57ABA5E40D</string> <string>BA7CE17D-DDC3-4394-808D-6D58588C329C</string> <string>EF439919-653A-4250-B8B6-9337DA8DD851</string> <string>0A58EA58-3BBC-4A07-80FF-366933CF24A7</string> <string>B00CB7C5-C864-493C-9C6E-DCF759CE3B6A</string> </array> - <key>name</key> <string>ColdFusion Functions</string> </dict> - <key>C8F9D7A6-D447-4C16-B566-BE46335B1067</key> <dict> <key>items</key> <array> <string>97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14</string> <string>862EDD04-D606-4EDB-8D01-425D8024CF1B</string> <string>0AF4E3E4-8638-4EAD-B182-A4FE571E9974</string> <string>38EB1CC2-4A1A-4C37-9D69-19D81129C5DC</string> <string>E0D7DCCA-9801-4DD5-9C26-3B607BEF7135</string> <string>241129A8-4AF3-4005-B276-6F431B5CB3F2</string> <string>8AE48664-E323-4DF9-BED2-CE700CAC7C15</string> <string>08392E18-5D55-41CB-BE64-7B091492E7BF</string> <string>9AEFE392-91BE-4968-8FF8-8A2C9D51D4CC</string> <string>67423190-2729-4C30-B10D-51B7DC3FAB85</string> <string>1B072993-0FFD-44B7-8C6D-3F9D60AF9E7B</string> <string>B8817D6A-B326-48F9-9E35-B28778A79412</string> <string>157C15A0-D535-4EAB-8173-6D6EB0906173</string> <string>0E400696-4C11-4072-9DAD-7BFF6F7789BE</string> <string>5A2941B5-2D73-4348-AB92-932665EB6E1D</string> <string>902C51B4-E4E3-4B2C-BA03-769FC6AC0867</string> <string>5CF87863-EBA1-49BE-AB51-016A2D0FDA80</string> <string>A72AC858-A593-4758-894F-266F9925990D</string> <string>6E59F119-65E3-4D1F-B393-121208A9A83F</string> <string>E336E487-B1EA-449C-9B32-4C5994136CEA</string> <string>90B1EE50-DAC5-4748-8415-5C3ABB38CFD5</string> <string>784AAEB3-2367-4275-95E0-DFDBE61E9423</string> <string>D5310F63-357F-4E8A-9583-26F569D309EB</string> <string>1ADF5606-9DC3-413F-8BC2-5E54E7BAC4FF</string> <string>28364618-9329-4501-98EC-852D28D2F59A</string> <string>EA2AA961-32E7-4B4B-85C8-0F458AC6E671</string> <string>A14677C7-FB24-4A35-B9F5-F764C2EFE00E</string> <string>5736162D-BDF6-4C94-8F3C-8F4CEB38E349</string> <string>C6C27604-1D24-4EC3-B40D-BD1FF6196DF8</string> <string>96D4FDBD-4A7D-42E4-BF7A-AB366E22758B</string> <string>E1BBA1F0-05C7-4EA0-87BA-FB0FC5D1CAED</string> <string>C8C2C389-AEE0-4CE2-8944-A7EEEFB9B680</string> <string>36F4B163-2ACD-48F1-8E72-365E54EB7811</string> <string>5D0E9DF4-6631-419C-AEEE-7710EE30502F</string> <string>0A3097F1-36A8-4009-8501-CC5B9349072E</string> <string>C28091B5-3245-4E3C-BC49-38AAB093D00F</string> <string>1D9BEE6E-907F-430A-BD62-2DF38A454B3E</string> <string>B8DC9CF1-AFF5-44E4-B9A8-42093D829889</string> <string>BEDB5CCC-7FF1-4C78-8169-2B58BFB2C449</string> <string>E6EE6F14-372D-469B-B31F-827A54CFC5E3</string> <string>DB5DE93A-DA9A-40E9-B469-EF8337A11CBE</string> <string>63B626CD-2818-42F2-BD90-DE112A8DEF7A</string> <string>5C3D7157-DFC0-4762-B059-C10F1A098089</string> <string>BD84E1FB-DCA2-493E-887E-1A1330DD6EA9</string> <string>CED5A340-3643-4F34-A8ED-A9FB99008300</string> <string>AB4A8782-7466-4B5D-A180-96E0BD19C050</string> <string>D01E4126-187A-4275-8583-DFA44FE3BB3C</string> <string>F9725187-DAE2-43BB-9209-BAF4F709AD72</string> <string>C83F3775-A62D-425B-B05E-C6A58C929399</string> <string>6674FAC2-9201-4D0D-BAA5-E35D64BDADDC</string> <string>53E1E9D3-8F53-4CFE-8ADD-83AC13969D24</string> <string>415DDDAF-1163-49E7-8D5B-3B6CD1A27A06</string> <string>B2FCBECB-D1E0-4BF4-B046-5A9C4A6475F9</string> <string>601BA2FE-EA4D-4B9C-A8EF-646A9E9626DD</string> <string>B14D6A84-2B4D-4FF8-99CB-E2B41B0E00BF</string> <string>29745C05-70EC-418A-A7E1-E60EE6042A95</string> <string>2FB6FDE3-F8F0-47A1-AE6D-AA3895A489CD</string> <string>0B69D306-8DF0-4494-87AC-B8E92091E0E6</string> <string>9AA75F85-02C0-4006-9D95-F7EC2728A050</string> <string>192D1402-A2E5-43F1-B0C5-990853DB5D98</string> <string>8BBB6187-A1D9-43AF-AF72-CDF3BB8B0A76</string> <string>DE1C603E-D791-469F-99D3-69E17B9B41EB</string> <string>FA01E47F-EB01-4FE1-9EB6-96FDEB923E70</string> <string>AA6262C5-CA32-415E-B666-D2FBF93E0905</string> <string>80B9754E-47ED-46D6-8BA5-80744B0FBE4B</string> <string>9A1343CB-5E9E-45A2-8D21-B4959C412B6E</string> <string>622A22FB-207B-4322-BC6C-C2B3D605AF00</string> <string>4DD466D2-0B15-4E06-8446-5AFBFC8B4128</string> <string>183709C1-9414-4A25-89FB-A0D9A7E59D27</string> <string>35060F61-EF40-4046-BF12-1AB2748884A1</string> <string>44EA1298-2450-498B-82F6-1BF1BC1FFE59</string> <string>29486C8D-7A9A-4EE0-B6A3-34C77A7D253E</string> <string>7F70512F-517F-4361-89ED-13E8C3BD98F0</string> <string>2A8760F9-6ED1-4066-B996-5E490B5A17EF</string> <string>9187A792-54F4-4773-A2D7-EB5D207D1A54</string> <string>F0AFF0A1-90FA-424F-A6AF-6EA6EC1BB225</string> <string>026FDCF1-E739-42E4-925D-59D80EE7FF05</string> <string>50182FB9-0179-4CF6-9AD7-4E7BC725C594</string> <string>3B19D8BC-5389-4263-A539-160170F7DFB1</string> <string>B096E910-EE96-4E63-BB46-EB12616C80F6</string> <string>08743309-6431-44D2-8A38-926516B04BEF</string> <string>A4876D40-55A7-44A0-9CDD-BCF62A621FC3</string> <string>5C441A88-2F12-4C54-83F8-81A62F735F88</string> <string>FDDBDC40-D1D9-4981-92DE-30CA475BC8FA</string> <string>3C93CAC9-0DC3-4371-8E5F-2727B0A282BD</string> <string>6F5A4D8F-DE7C-4663-9D39-7BF23D84769E</string> <string>75FFC09D-CB71-49CF-AB01-3DA8C44F29F3</string> <string>97DD90F8-5334-46A0-B973-C59F357D6C31</string> <string>3ED1297F-4C77-4187-9356-4262D3F28625</string> <string>F36E8F58-CDBD-4E42-A64F-9D05BE2D49B9</string> <string>1B6D6622-49BD-4EAB-B521-B3D1ACF2E4B1</string> <string>E09B46CF-DDE0-4B40-B7AF-93C005F23BAB</string> <string>A607B362-68CB-4AE3-BE72-575EB7CBA55A</string> <string>A57CC7BE-F39A-4B64-908D-44EA058C294F</string> <string>0C5234DB-A0F6-4BE2-AF28-5276ED3F81BB</string> <string>BC74CDF9-65E1-4FD0-A939-110CF53F3F67</string> <string>D6CFEC97-357A-4EBD-9D95-F89FECD4ED66</string> <string>293B3EF2-892E-4FF9-BB3B-82AE01FFA38D</string> <string>24AEB6C9-9CDE-478C-9C08-5CB1825321AE</string> <string>4417C4C8-F581-41FC-96FF-76A28A1F0640</string> <string>BC022681-5DE4-4E5C-8638-93EF655F7B0D</string> <string>47BD7B3C-4316-4C5B-AD7D-596D90D64A7C</string> <string>ED205418-D60B-41CE-9942-6855C78C65F6</string> <string>AEA7BB76-4231-41DC-829C-D093F7BF28E5</string> <string>F29A9DA7-B58E-4839-8664-2C99C5679384</string> <string>7423A717-6340-4CEC-9151-2B882D052CB9</string> <string>6E621AA5-5304-4DCE-82B9-820FDB78C5FE</string> <string>21B96169-6556-4436-B3B2-4556A6372567</string> <string>7A62D445-BDCF-4C67-8B71-35255FACC231</string> <string>9B25BE9A-A2E8-4BA6-A1CD-A545C6A3AEDE</string> <string>AD74D8BA-A774-4748-BF7E-22A6E94194ED</string> <string>8743E910-AD98-42C7-AC9D-4EBD26B54456</string> <string>5EB9976E-F76E-40FE-828F-22B393BA59AE</string> <string>8A82A0E0-7396-436B-A3FD-46680599A33A</string> <string>B36FA4B0-F6AE-4489-97D1-54BFE773A560</string> <string>281422A7-AF82-45BF-8707-4242A22FA908</string> <string>CD089D33-F3B3-4BC8-9650-B7CF29B877BF</string> <string>18A3925F-BF0F-4FAF-B45C-C02B2D4C4CB1</string> <string>7188A872-4A9F-4A05-ADCA-46D83E911D2D</string> <string>6322FE39-5B27-49EF-A632-A6073EDCE0C4</string> <string>BEC86CCF-C220-4B07-9ACD-320238D1FE48</string> <string>1F61F24F-166C-4D2E-98B0-7BA454B21619</string> <string>5BAF7E27-FEAB-43E0-899F-ABE9DA500FD0</string> <string>EE49E017-4812-4CAA-8CCC-29DAB3BE7B64</string> <string>97F31F3F-B885-4DE8-B784-5582990C21CD</string> <string>5D2DC339-C6E8-4919-9500-DD24DC9D2F73</string> <string>9E6E0847-D0DB-435D-A129-CA90BE6B9210</string> <string>82B42D60-DC77-47AA-B433-14969E2A2CEB</string> <string>DE1DB107-EC48-4128-B400-203B72AFD40F</string> <string>2051A0AE-51E2-413F-9CCB-92826FCD5C99</string> </array> <key>name</key> <string>ColdFusion Tags</string> </dict> </dict> </dict> - <key>name</key> <string>ColdFusion</string> - <key>ordering</key> <array> - <!-- Matching types ([##]), etc --> <string>00D00AD7-3C05-46E0-B8B9-0F5CCAC04F57</string> - <!-- Coldfusion comment --> <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> </array> - <key>uuid</key> <string>1A09BE0B-E81A-4CB7-AF69-AFC845162D1F</string> </dict> </plist>
robrohan/coldfusion.tmbundle
59347f2ae7836f60d2551fd746063167e5909e8b
Trying to get cfscript to color properly
diff --git a/Syntaxes/ColdFusion.tmLanguage b/Syntaxes/ColdFusion.tmLanguage index 7badec5..b659043 100644 --- a/Syntaxes/ColdFusion.tmLanguage +++ b/Syntaxes/ColdFusion.tmLanguage @@ -1,436 +1,435 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>fileTypes</key> <array> <string>cfm</string> <string>cfml</string> <string>cfc</string> </array> <key>foldingStartMarker</key> <string>(?x) (&lt;(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction)\b.*?&gt; |&lt;!---(?!.*---\s*&gt;) )</string> <key>foldingStopMarker</key> <string>(?x) (&lt;/(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction)&gt; |^(?!.*?&lt;!---).*?---\s*&gt; )</string> <key>keyEquivalent</key> <string>^~@c</string> <key>name</key> <string>ColdFusion</string> - <!-- CFOUTPUT --> <key>patterns</key> <array> - <!-- CFOUTPUT --> + <!-- Bit of a Hack: Use Javascript to emulate cfscript --> + <!-- TODO: Put a bit more work into this --> <dict> <key>begin</key> - <string>(?:^\s+)?&lt;((?i:cfoutput))\b(?![^&gt;]*/&gt;)</string> + <string>(?:^\s+)?&lt;((?i:cfscript))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> - <string>entity.name.tag.cfoutput.cfm</string> + <string>entity.name.tag.script.html</string> </dict> </dict> <key>end</key> - <string>&lt;/((?i:cfoutput))&gt;(?:\s*\n)?</string> + <string>(?&lt;=&lt;/(cfscript|CFSCRIPT))&gt;(?:\s*\n)?</string> + <!-- for now just use JS for cfScript (mostly right) --> <key>name</key> - <string>meta.tag.cfoutput.cfm</string> + <string>source.js.embedded.html</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> + <dict> <key>begin</key> - <string>&gt;</string> - <key>contentName</key> - <string>meta.scope.output.cfm</string> + <string>(?&lt;!&lt;/(?i:cfscript))&gt;</string> + <key>end</key> - <string>(?=&lt;/(?i:cfoutput))</string> + <string>&lt;/((?i:cfscript))</string> + <key>patterns</key> <array> <dict> <key>include</key> - <string>$self</string> + <string>source.js</string> + </dict> + <dict> + <key>match</key> + <string>//.*?((?=&lt;/cfscript)|$\n?)</string> + <key>name</key> + <string>comment.line.double-slash.js</string> + </dict> + <dict> + <key>begin</key> + <string>/\*</string> + <key>end</key> + <string>\*/|(?=&lt;/cfscript)</string> + <key>name</key> + <string>comment.block.js</string> </dict> </array> </dict> </array> </dict> - <!-- CFQUERY (SQL Embedded) --> + <!-- CFOUTPUT --> <dict> <key>begin</key> - <string>(?:^\s+)?&lt;((?i:cfquery))\b(?![^&gt;]*/&gt;)</string> + <string>(?:^\s+)?&lt;((?i:cfoutput))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> - <string>entity.name.tag.cfquery.cfm</string> + <string>entity.name.tag.cfoutput.cfm</string> </dict> </dict> <key>end</key> - <string>&lt;/((?i:cfquery))&gt;(?:\s*\n)?</string> + <string>&lt;/((?i:cfoutput))&gt;(?:\s*\n)?</string> <key>name</key> - <string>meta.tag.cfquery.cfm</string> + <string>meta.tag.cfoutput.cfm</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> - <string>(?&lt;=&gt;)</string> + <string>&gt;</string> + <key>contentName</key> + <string>meta.scope.output.cfm</string> <key>end</key> - <string>(?=&lt;/(?i:cfquery))</string> - <key>name</key> - <string>source.sql.embedded</string> + <string>(?=&lt;/(?i:cfoutput))</string> <key>patterns</key> <array> <dict> <key>include</key> - <string>source.sql</string> + <string>$self</string> </dict> </array> </dict> </array> </dict> - <!-- Bit of a Hack: Use Javascript to emulate cfscript --> - <!-- TODO: Put a bit more work into this --> + <!-- CFQUERY (SQL Embedded) --> <dict> <key>begin</key> - <string>(?:^\s+)?&lt;((?i:cfscript))\b(?![^&gt;]*/&gt;)</string> + <string>(?:^\s+)?&lt;((?i:cfquery))\b(?![^&gt;]*/&gt;)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> - <string>entity.name.tag.cfscript.html</string> + <string>entity.name.tag.cfquery.cfm</string> </dict> </dict> <key>end</key> - <string>(?&lt;=&lt;/(cfscript|CFSCRIPT))&gt;(?:\s*\n)?</string> + <string>&lt;/((?i:cfquery))&gt;(?:\s*\n)?</string> - <!-- for now just use JS for cfScript (mostly right) --> <key>name</key> - <string>source.js.embedded.html</string> + <string>meta.tag.cfquery.cfm</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> - <dict> <key>begin</key> - <string>(?&lt;!&lt;/(?i:cfscript))&gt;</string> - + <string>(?&lt;=&gt;)</string> <key>end</key> - <string>&lt;/((?i:cfscript))</string> - + <string>(?=&lt;/(?i:cfquery))</string> + <key>name</key> + <string>source.sql.embedded</string> <key>patterns</key> <array> - <dict> - <key>match</key> - <string>//.*?((?=&lt;/cfscript)|$\n?)</string> - <key>name</key> - <string>comment.line.double-slash.js</string> - </dict> - <dict> - <key>begin</key> - <string>/\*</string> - <key>end</key> - <string>\*/|(?=&lt;/cfscript)</string> - <key>name</key> - <string>comment.block.js</string> - </dict> <dict> <key>include</key> - <string>source.js</string> + <string>source.sql</string> </dict> </array> </dict> </array> </dict> <!-- Any ColdFusion tag --> <dict> <key>begin</key> <string>&lt;/?((?i:cf)([a-zA-Z0-9]+))(?=[^&gt;]*&gt;)</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.cfm</string> </dict> </dict> <key>end</key> <string>&gt;</string> <key>name</key> <string>meta.tag.any.cfm</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> <!-- Coldfusion Comment --> <dict> <key>include</key> <string>#coldfusion-comment</string> </dict> <!-- Other Tags --> <dict> <key>include</key> <string>text.html.basic</string> </dict> </array> <!-- Reused Partitions? --> <key>repository</key> <dict> <key>coldfusion-comment</key> <dict> <key>begin</key> <string>&lt;!---</string> <key>end</key> <string>---&gt;</string> <key>name</key> <string>comment.block.cfm</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#coldfusion-comment</string> </dict> </array> </dict> <key>embedded-code</key> <dict> <key>patterns</key> <array/> </dict> <key>entities</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>&amp;([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);</string> <key>name</key> <string>constant.character.entity.html</string> </dict> <dict> <key>match</key> <string>&amp;</string> <key>name</key> <string>invalid.illegal.bad-ampersand.html</string> </dict> </array> </dict> <key>string-double-quoted</key> <dict> <key>begin</key> <string>"</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.cfm</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <key>string-single-quoted</key> <dict> <key>begin</key> <string>'</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.cfm</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <key>tag-generic-attribute</key> <dict> <key>match</key> <string>\b([a-zA-Z\-:]+)</string> <key>name</key> <string>entity.other.attribute-name.cfm</string> </dict> <key>tag-id-attribute</key> <dict> <key>begin</key> <string>\b(id)\b\s*=</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.other.attribute-name.id.html</string> </dict> </dict> <key>end</key> <string>(?&lt;='|")</string> <key>name</key> <string>meta.attribute-with-value.id.cfm</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>"</string> <key>contentName</key> <string>meta.toc-list.id.cfm</string> <key>end</key> <string>"</string> <key>name</key> <string>string.quoted.double.cfm</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <dict> <key>begin</key> <string>'</string> <key>contentName</key> <string>meta.toc-list.id.cfm</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.cfm</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> </array> </dict> <key>tag-stuff</key> <dict> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-id-attribute</string> </dict> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> <dict> <key>include</key> <string>#embedded-code</string> </dict> </array> </dict> </dict> <key>scopeName</key> <string>text.html.cfm</string> <key>uuid</key> <string>97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14</string> </dict> </plist>
robrohan/coldfusion.tmbundle
7332740f39b68bbefe1c80a6a9c7486b4373f7d7
Cleaned up the info.plist a bit (and the menu structure in the gear icon). Also added in auto complete for the # character. I also added in code folding for cffunction, but that might have been on the last commit.
diff --git a/Preferences/ColdFusion Preferences.plist b/Preferences/ColdFusion Preferences.plist new file mode 100644 index 0000000..384cced Binary files /dev/null and b/Preferences/ColdFusion Preferences.plist differ diff --git a/Preferences/Comment.tmPreferences b/Preferences/Comment.tmPreferences new file mode 100644 index 0000000..863cd58 --- /dev/null +++ b/Preferences/Comment.tmPreferences @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>name</key> + <string>Comments</string> + + <key>scope</key> + <string>text.html.cfm</string> + + <key>settings</key> + <dict> + <key>shellVariables</key> + <array> + <dict> + <key>name</key> + <string>TM_COMMENT_START</string> + <key>value</key> + <string>&lt;!--- </string> + </dict> + <dict> + <key>name</key> + <string>TM_COMMENT_END</string> + <key>value</key> + <string> ---&gt;</string> + </dict> + </array> + </dict> + + <key>uuid</key> + <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> +</dict> +</plist> diff --git a/Preferences/Smart Typing Pairs.tmPreferences b/Preferences/Smart Typing Pairs.tmPreferences deleted file mode 100644 index 09ec66f..0000000 --- a/Preferences/Smart Typing Pairs.tmPreferences +++ /dev/null @@ -1,22 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> -<plist version="1.0"> -<dict> - <key>name</key> - <string>Smart Typing Pairs</string> - <key>scope</key> - <string>meta.scope.output.cfm, string.quoted.double.cfm</string> - <key>settings</key> - <dict> - <key>smartTypingPairs</key> - <array> - <array> - <string>#</string> - <string>#</string> - </array> - </array> - </dict> - <key>uuid</key> - <string>862EDD04-D606-4EDB-8D01-425D8024CF1B</string> -</dict> -</plist> diff --git a/Preferences/comment.tmPreferences b/Preferences/comment.tmPreferences index 9a78dfb..863cd58 100644 --- a/Preferences/comment.tmPreferences +++ b/Preferences/comment.tmPreferences @@ -1,30 +1,33 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>name</key> <string>Comments</string> + <key>scope</key> <string>text.html.cfm</string> + <key>settings</key> <dict> <key>shellVariables</key> <array> <dict> <key>name</key> <string>TM_COMMENT_START</string> <key>value</key> <string>&lt;!--- </string> </dict> <dict> <key>name</key> <string>TM_COMMENT_END</string> <key>value</key> <string> ---&gt;</string> </dict> </array> </dict> + <key>uuid</key> <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> </dict> </plist> diff --git a/Snippets/isDefined.tmSnippet b/Snippets/isDefined.tmSnippet index 516ad9a..29aaed0 100644 --- a/Snippets/isDefined.tmSnippet +++ b/Snippets/isDefined.tmSnippet @@ -1,16 +1,16 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>content</key> - <string>isDefined("$1")$2</string> - <key>keyEquivalent</key> - <string>^I</string> + <string>IsDefined(${1:"variable_name"})$0</string> <key>name</key> - <string>isDefined</string> + <string>isdefined</string> <key>scope</key> <string>text.html.cfm</string> + <key>tabTrigger</key> + <string>isdefined</string> <key>uuid</key> - <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> + <string>30468398-BDF8-4221-B8C1-108D660B5462</string> </dict> </plist> diff --git a/Snippets/isdefined 2.tmSnippet b/Snippets/isdefined.tmSnippet similarity index 100% rename from Snippets/isdefined 2.tmSnippet rename to Snippets/isdefined.tmSnippet diff --git a/Snippets/form variable.tmSnippet b/Snippets/x_form-variable.tmSnippet similarity index 93% rename from Snippets/form variable.tmSnippet rename to Snippets/x_form-variable.tmSnippet index b33bfaf..7ea03c0 100644 --- a/Snippets/form variable.tmSnippet +++ b/Snippets/x_form-variable.tmSnippet @@ -1,16 +1,16 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>content</key> <string>#${1:trim}(form.$2)#</string> <key>keyEquivalent</key> <string>^F</string> <key>name</key> - <string>form variable</string> + <string>Form Variable</string> <key>scope</key> <string>text.html.cfm</string> <key>uuid</key> <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> </dict> </plist> diff --git a/Snippets/x_isDefined.tmSnippet b/Snippets/x_isDefined.tmSnippet new file mode 100644 index 0000000..6a7e9f9 --- /dev/null +++ b/Snippets/x_isDefined.tmSnippet @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>content</key> + <string>isDefined("$1")$2</string> + <key>keyEquivalent</key> + <string>^I</string> + <key>name</key> + <string>IsDefined</string> + <key>scope</key> + <string>text.html.cfm</string> + <key>uuid</key> + <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> +</dict> +</plist> diff --git a/Snippets/url variable.tmSnippet b/Snippets/x_url-variable.tmSnippet similarity index 93% rename from Snippets/url variable.tmSnippet rename to Snippets/x_url-variable.tmSnippet index a459fc4..3d5bd13 100644 --- a/Snippets/url variable.tmSnippet +++ b/Snippets/x_url-variable.tmSnippet @@ -1,16 +1,16 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>content</key> <string>#${1:trim}(url.$2)#</string> <key>keyEquivalent</key> <string>^U</string> <key>name</key> - <string>url variable</string> + <string>URL Variable</string> <key>scope</key> <string>text.html.cfm</string> <key>uuid</key> <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> </dict> </plist> diff --git a/info.plist b/info.plist index 8fb09a5..58d57c6 100644 --- a/info.plist +++ b/info.plist @@ -1,612 +1,615 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>contactEmailRot13</key> <string>[email protected]</string> <key>contactName</key> <string>Rob Rohan</string> <key>description</key> <string>Support for the ColdFusion web development environment.</string> <key>mainMenu</key> <dict> <key>items</key> <array> + <!-- CF Tags --> <string>C8F9D7A6-D447-4C16-B566-BE46335B1067</string> + <!-- CF Functions --> <string>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</string> - <!-- + <string>------------------------------------</string> + <!-- second isdefined (not sure if we should keep this) --> <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> + <!-- form variable --> <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> + <!-- url variable --> <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> - <string>2DD711BA-8C2D-4AF4-85C2-C42733743D0A</string> - <string>5C998560-6284-4F59-A6F9-420962E130E2</string> --> </array> <key>submenus</key> <dict> <key>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</key> <dict> <key>items</key> <array> <string>0AF4E3E4-8638-4EAD-B182-A4FE571E9974</string> <string>38EB1CC2-4A1A-4C37-9D69-19D81129C5DC</string> <string>E0D7DCCA-9801-4DD5-9C26-3B607BEF7135</string> <string>241129A8-4AF3-4005-B276-6F431B5CB3F2</string> <string>8AE48664-E323-4DF9-BED2-CE700CAC7C15</string> <string>08392E18-5D55-41CB-BE64-7B091492E7BF</string> <string>9AEFE392-91BE-4968-8FF8-8A2C9D51D4CC</string> <string>67423190-2729-4C30-B10D-51B7DC3FAB85</string> <string>1B072993-0FFD-44B7-8C6D-3F9D60AF9E7B</string> <string>B8817D6A-B326-48F9-9E35-B28778A79412</string> <string>157C15A0-D535-4EAB-8173-6D6EB0906173</string> <string>0E400696-4C11-4072-9DAD-7BFF6F7789BE</string> <string>5A2941B5-2D73-4348-AB92-932665EB6E1D</string> <string>902C51B4-E4E3-4B2C-BA03-769FC6AC0867</string> <string>5CF87863-EBA1-49BE-AB51-016A2D0FDA80</string> <string>A72AC858-A593-4758-894F-266F9925990D</string> <string>6E59F119-65E3-4D1F-B393-121208A9A83F</string> <string>E336E487-B1EA-449C-9B32-4C5994136CEA</string> <string>90B1EE50-DAC5-4748-8415-5C3ABB38CFD5</string> <string>784AAEB3-2367-4275-95E0-DFDBE61E9423</string> <string>D5310F63-357F-4E8A-9583-26F569D309EB</string> <string>1ADF5606-9DC3-413F-8BC2-5E54E7BAC4FF</string> <string>28364618-9329-4501-98EC-852D28D2F59A</string> <string>EA2AA961-32E7-4B4B-85C8-0F458AC6E671</string> <string>A14677C7-FB24-4A35-B9F5-F764C2EFE00E</string> <string>5736162D-BDF6-4C94-8F3C-8F4CEB38E349</string> <string>C6C27604-1D24-4EC3-B40D-BD1FF6196DF8</string> <string>96D4FDBD-4A7D-42E4-BF7A-AB366E22758B</string> <string>E1BBA1F0-05C7-4EA0-87BA-FB0FC5D1CAED</string> <string>C8C2C389-AEE0-4CE2-8944-A7EEEFB9B680</string> <string>36F4B163-2ACD-48F1-8E72-365E54EB7811</string> <string>5D0E9DF4-6631-419C-AEEE-7710EE30502F</string> <string>0A3097F1-36A8-4009-8501-CC5B9349072E</string> <string>C28091B5-3245-4E3C-BC49-38AAB093D00F</string> <string>1D9BEE6E-907F-430A-BD62-2DF38A454B3E</string> <string>B8DC9CF1-AFF5-44E4-B9A8-42093D829889</string> <string>BEDB5CCC-7FF1-4C78-8169-2B58BFB2C449</string> <string>E6EE6F14-372D-469B-B31F-827A54CFC5E3</string> <string>DB5DE93A-DA9A-40E9-B469-EF8337A11CBE</string> <string>63B626CD-2818-42F2-BD90-DE112A8DEF7A</string> <string>5C3D7157-DFC0-4762-B059-C10F1A098089</string> <string>BD84E1FB-DCA2-493E-887E-1A1330DD6EA9</string> <string>CED5A340-3643-4F34-A8ED-A9FB99008300</string> <string>AB4A8782-7466-4B5D-A180-96E0BD19C050</string> <string>D01E4126-187A-4275-8583-DFA44FE3BB3C</string> <string>F9725187-DAE2-43BB-9209-BAF4F709AD72</string> <string>C83F3775-A62D-425B-B05E-C6A58C929399</string> <string>6674FAC2-9201-4D0D-BAA5-E35D64BDADDC</string> <string>53E1E9D3-8F53-4CFE-8ADD-83AC13969D24</string> <string>415DDDAF-1163-49E7-8D5B-3B6CD1A27A06</string> <string>B2FCBECB-D1E0-4BF4-B046-5A9C4A6475F9</string> <string>601BA2FE-EA4D-4B9C-A8EF-646A9E9626DD</string> <string>B14D6A84-2B4D-4FF8-99CB-E2B41B0E00BF</string> <string>29745C05-70EC-418A-A7E1-E60EE6042A95</string> <string>2FB6FDE3-F8F0-47A1-AE6D-AA3895A489CD</string> <string>0B69D306-8DF0-4494-87AC-B8E92091E0E6</string> <string>9AA75F85-02C0-4006-9D95-F7EC2728A050</string> <string>192D1402-A2E5-43F1-B0C5-990853DB5D98</string> <string>8BBB6187-A1D9-43AF-AF72-CDF3BB8B0A76</string> <string>DE1C603E-D791-469F-99D3-69E17B9B41EB</string> <string>FA01E47F-EB01-4FE1-9EB6-96FDEB923E70</string> <string>AA6262C5-CA32-415E-B666-D2FBF93E0905</string> <string>80B9754E-47ED-46D6-8BA5-80744B0FBE4B</string> <string>9A1343CB-5E9E-45A2-8D21-B4959C412B6E</string> <string>622A22FB-207B-4322-BC6C-C2B3D605AF00</string> - <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> <string>4DD466D2-0B15-4E06-8446-5AFBFC8B4128</string> <string>183709C1-9414-4A25-89FB-A0D9A7E59D27</string> <string>35060F61-EF40-4046-BF12-1AB2748884A1</string> <string>44EA1298-2450-498B-82F6-1BF1BC1FFE59</string> <string>29486C8D-7A9A-4EE0-B6A3-34C77A7D253E</string> <string>7F70512F-517F-4361-89ED-13E8C3BD98F0</string> <string>2A8760F9-6ED1-4066-B996-5E490B5A17EF</string> <string>9187A792-54F4-4773-A2D7-EB5D207D1A54</string> <string>F0AFF0A1-90FA-424F-A6AF-6EA6EC1BB225</string> <string>026FDCF1-E739-42E4-925D-59D80EE7FF05</string> <string>50182FB9-0179-4CF6-9AD7-4E7BC725C594</string> <string>3B19D8BC-5389-4263-A539-160170F7DFB1</string> <string>B096E910-EE96-4E63-BB46-EB12616C80F6</string> <string>08743309-6431-44D2-8A38-926516B04BEF</string> <string>A4876D40-55A7-44A0-9CDD-BCF62A621FC3</string> <string>5C441A88-2F12-4C54-83F8-81A62F735F88</string> <string>FDDBDC40-D1D9-4981-92DE-30CA475BC8FA</string> <string>3C93CAC9-0DC3-4371-8E5F-2727B0A282BD</string> <string>6F5A4D8F-DE7C-4663-9D39-7BF23D84769E</string> <string>75FFC09D-CB71-49CF-AB01-3DA8C44F29F3</string> <string>97DD90F8-5334-46A0-B973-C59F357D6C31</string> <string>3ED1297F-4C77-4187-9356-4262D3F28625</string> <string>F36E8F58-CDBD-4E42-A64F-9D05BE2D49B9</string> <string>1B6D6622-49BD-4EAB-B521-B3D1ACF2E4B1</string> <string>E09B46CF-DDE0-4B40-B7AF-93C005F23BAB</string> <string>A607B362-68CB-4AE3-BE72-575EB7CBA55A</string> <string>A57CC7BE-F39A-4B64-908D-44EA058C294F</string> <string>0C5234DB-A0F6-4BE2-AF28-5276ED3F81BB</string> <string>BC74CDF9-65E1-4FD0-A939-110CF53F3F67</string> <string>D6CFEC97-357A-4EBD-9D95-F89FECD4ED66</string> <string>293B3EF2-892E-4FF9-BB3B-82AE01FFA38D</string> <string>24AEB6C9-9CDE-478C-9C08-5CB1825321AE</string> <string>4417C4C8-F581-41FC-96FF-76A28A1F0640</string> <string>BC022681-5DE4-4E5C-8638-93EF655F7B0D</string> <string>47BD7B3C-4316-4C5B-AD7D-596D90D64A7C</string> <string>ED205418-D60B-41CE-9942-6855C78C65F6</string> <string>AEA7BB76-4231-41DC-829C-D093F7BF28E5</string> <string>F29A9DA7-B58E-4839-8664-2C99C5679384</string> <string>7423A717-6340-4CEC-9151-2B882D052CB9</string> <string>6E621AA5-5304-4DCE-82B9-820FDB78C5FE</string> <string>21B96169-6556-4436-B3B2-4556A6372567</string> <string>7A62D445-BDCF-4C67-8B71-35255FACC231</string> <string>9B25BE9A-A2E8-4BA6-A1CD-A545C6A3AEDE</string> <string>AD74D8BA-A774-4748-BF7E-22A6E94194ED</string> <string>8743E910-AD98-42C7-AC9D-4EBD26B54456</string> <string>5EB9976E-F76E-40FE-828F-22B393BA59AE</string> <string>8A82A0E0-7396-436B-A3FD-46680599A33A</string> <string>B36FA4B0-F6AE-4489-97D1-54BFE773A560</string> <string>281422A7-AF82-45BF-8707-4242A22FA908</string> <string>CD089D33-F3B3-4BC8-9650-B7CF29B877BF</string> <string>18A3925F-BF0F-4FAF-B45C-C02B2D4C4CB1</string> <string>7188A872-4A9F-4A05-ADCA-46D83E911D2D</string> <string>6322FE39-5B27-49EF-A632-A6073EDCE0C4</string> <string>BEC86CCF-C220-4B07-9ACD-320238D1FE48</string> <string>1F61F24F-166C-4D2E-98B0-7BA454B21619</string> <string>5BAF7E27-FEAB-43E0-899F-ABE9DA500FD0</string> <string>EE49E017-4812-4CAA-8CCC-29DAB3BE7B64</string> <string>97F31F3F-B885-4DE8-B784-5582990C21CD</string> <string>5D2DC339-C6E8-4919-9500-DD24DC9D2F73</string> <string>9E6E0847-D0DB-435D-A129-CA90BE6B9210</string> <string>82B42D60-DC77-47AA-B433-14969E2A2CEB</string> <string>DE1DB107-EC48-4128-B400-203B72AFD40F</string> <string>2051A0AE-51E2-413F-9CCB-92826FCD5C99</string> - <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> - <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> <string>2DD711BA-8C2D-4AF4-85C2-C42733743D0A</string> <string>5C998560-6284-4F59-A6F9-420962E130E2</string> <string>5DBF4A9D-7C3E-4FAD-B6DE-16AB145F081B</string> <string>C3F1BC8E-892F-4FB5-8A63-F8225B42CCFC</string> <string>3B7767FB-E117-4543-B27C-C178D5F451DF</string> <string>618D41F8-8A13-42B6-9000-551AA2DF9FA3</string> <string>ACB55DF1-EE3F-4B20-A3CA-3DC63018212B</string> <string>466D3581-0875-4E99-952A-0650CB84D33D</string> <string>17CFEC94-0BF5-40CD-97DD-79A2CAECB041</string> <string>5C46558A-599C-427F-8A7E-0343F1BED079</string> <string>D2675FE6-79EF-40C6-A864-A5C6F092BA4C</string> <string>D61CD41D-9838-4169-A754-424345AC4601</string> <string>4C31384B-2B27-4C39-B2BB-CC2CA57B659A</string> <string>02261555-8147-43DF-9D49-AEE4F58E1619</string> <string>3757F0B8-F3B0-4272-9F6E-8968CE670387</string> <string>3514ADDF-C60D-4A16-9346-11EB7A2AA61A</string> <string>90E0EBD1-EC9F-425B-ACC3-06EFAB5F1F69</string> <string>41ED9831-365B-4D4F-AF8D-2864343E271F</string> <string>696A8BD3-EF4F-4A4C-A264-93BE6781D657</string> <string>40051E46-ECE8-4A07-B600-934A3B482EFC</string> <string>2016AF2A-1AC1-45A8-BCA0-A52F23142863</string> <string>FD148128-FF2A-4CFE-99F6-FF43653FE8EA</string> <string>6C79157D-36F9-4F91-B012-BDD27622FF9B</string> <string>E45A3C54-88D7-4E4A-8092-56854FE825BE</string> <string>49443738-7978-4865-A1AC-7358A0BEE2DE</string> <string>C17555B3-A84A-404B-AECA-3F11CA9ABF0D</string> <string>22ECD416-BC42-4C13-8BAF-F435A144A56E</string> <string>E0363D86-A148-44D2-9AF9-45A2A57D1676</string> <string>9992024A-E07D-4E29-9B35-F85038E890AF</string> <string>23E6B8AA-CA8F-4CCC-BC29-76A027849595</string> <string>28FE5A03-F962-4ECE-AF92-EE3436D20664</string> <string>0D55F7C2-16A2-4B78-B390-EF780FF0F2EC</string> <string>D9676E4C-3E0A-4886-8F2A-03E25DB4D44C</string> <string>2C83D486-C0A5-4493-8562-BEA824BAD2D7</string> <string>817F3C02-47AD-4553-9DE2-BDB0EC97BC9F</string> <string>FEF3A4E6-7B4E-47B6-A529-ED41EDA41002</string> <string>917BA410-EC71-492D-8472-A3C2CED279FA</string> <string>6C78FA7D-0B84-4E9A-A063-77490073E99F</string> <string>0F018E42-BB09-4631-B11E-EDDD267C8DFF</string> <string>068FD2EE-B721-4DE3-A4E2-F98476C0530A</string> <string>9A231D17-D36C-4081-B1EE-E3F5016040C1</string> <string>E648C975-48FA-4818-89B6-34913675E41D</string> <string>E7FD5C33-5516-4DB0-A553-B832515D17D4</string> <string>F3102771-3AA4-492D-AD42-2FDB4F686662</string> <string>C3AE011B-75E2-45AF-B427-864997717FE2</string> <string>519D474D-FE82-4419-9D5F-AA88D817EDE6</string> <string>6816281D-E43D-4DEC-AC2B-0E0756A00EEB</string> <string>25ACCCC1-401C-4084-80DE-6CFFF6FDEA20</string> <string>41E4F63F-C59D-4712-B29A-9CC83D717469</string> <string>63CA1E9E-34AB-4EDD-B6CC-16C22EA5B777</string> <string>2B8BC0E7-93C3-4DE2-957E-8212F6E373C3</string> <string>19400E23-B260-4E85-AFFD-109708545A80</string> <string>312DD333-8664-4C27-9C67-ED8B285579D4</string> <string>9BDE4AC0-BEC2-4585-AEC7-AD60767AFBEE</string> <string>9D47F8B3-B009-418B-8AB9-0E72D33F137D</string> <string>79EDA618-F9E9-4A72-8A7F-DDC0D6826C19</string> <string>0BA580D0-B978-48C0-8CEB-F78042E9F58F</string> <string>AE303AF0-FAE2-4C2F-A5BF-0745D3161289</string> <string>228F7B63-E8C8-48EF-9613-A32CAB3FF100</string> <string>CB454D76-239A-40D2-B194-43CA6DDD9B8D</string> <string>CBEAE712-0FC9-4210-B157-DC5C264BFCBF</string> <string>8F41DFB0-285F-4FA7-A21D-210832BEBD60</string> <string>81541C90-0980-47A1-9B9B-9F3E750016C7</string> <string>E651A0E3-0EC3-45AC-B7D0-92E2DAD1F733</string> <string>8D4E0C06-8D06-4871-9D92-5C72B18A5562</string> <string>D455BE22-95B8-477F-BA2B-22C8C33D2C85</string> <string>1262430C-CE62-4585-9EFC-7D5D001C5F24</string> <string>5A00FE89-14AB-4DCA-B601-5FEA6C36F8F4</string> <string>F82AABEA-89D3-4DE6-8B6C-3B7BDC194667</string> <string>DEB3845A-FE19-4B41-84AD-EAA44A4BD1DB</string> <string>3B74EAA8-B431-423C-971B-09349375FE3E</string> <string>FA705D08-0DFD-4C3B-AB79-FF7719E9258D</string> <string>C02F0BE6-CDE7-489F-8B1D-C63CD15AEEC6</string> <string>2559432A-5071-4C85-B71B-A546326C4DE6</string> <string>2358C3ED-39E9-4CB1-BBE0-C2C0419F4E9C</string> <string>C91A69A3-2ECA-4F98-8777-E142F6777683</string> <string>F78D0262-1B71-4AD6-8BB5-C2E9DC9BB083</string> <string>8FC4AFD0-98E2-414D-8F80-ED36E5BD977A</string> <string>80ECE03A-C2E3-4334-8F7B-2A2ED7BC80A7</string> <string>0A20DB84-AAEF-4B95-A19F-18D6F3694798</string> <string>31B2DCFD-1049-49CF-BCA8-FAE5D0D4917D</string> <string>DDE93618-33D9-494A-93F0-1E0CAC672042</string> <string>DD2F9E4A-E204-4CEF-ADCD-18B523A65966</string> <string>44379253-BF02-4341-8BB2-B40CD39ED593</string> <string>DF3F5402-8B88-40D3-81F4-B960A6174610</string> <string>C22A5FC3-65EA-4234-85F2-2B43DFF811FF</string> <string>041E3434-05CD-49B2-BFC3-4E3BE5643A65</string> <string>829C9A8E-323D-44DA-BD6F-72AC150755A1</string> <string>E55FC014-0F85-4A3E-884D-F7C4F3179659</string> <string>C4D060C7-FF47-4799-AD06-108B3A757EB6</string> <string>FB98EFB0-2C9C-4037-96CF-5C0644041281</string> <string>8330E508-BE78-4713-BF73-2C8B08C02883</string> <string>2452CEE2-65EC-4FF1-8E1E-C77876F1D14E</string> <string>1B854256-5B23-4FCC-8367-2330D94D200E</string> <string>BCF434DF-79AB-4F95-83E0-8D9B0163956B</string> <string>F93D53FB-7669-4780-B53A-16276844A5BD</string> <string>89150D95-04F4-4A3B-B885-20A9C95E3FBA</string> <string>4F0429B6-0FB1-4CF6-BCB8-6350EBD89C35</string> <string>998B082A-A679-4494-B66C-69AA8256E4D2</string> <string>E03C0C8A-5CBA-4654-A4BD-EB6500901709</string> <string>62B6DE6D-751C-4599-8094-6F3EA39F2517</string> <string>ED3D3507-B8D9-4A83-88B7-CAD0F46A664A</string> <string>958C7148-B01A-4FE8-AA42-88CADB026CBA</string> <string>DEF118D7-4325-45E5-9AFC-77C80839A76F</string> <string>AB98AFE4-E946-4CC6-B453-B6E478590152</string> <string>3B4924D7-1FCB-4D61-85C8-63E69BFC808F</string> <string>4640A976-0C9E-45AA-912F-AD2EEF351E60</string> <string>5A3FFFCD-C7A2-457E-8D6E-151680293EBD</string> <string>CA44FB3A-353F-418C-AC80-1DC89F4D65BF</string> <string>0CC8642F-3BE7-45DA-86CB-179A4AE9C264</string> <string>FD813CA3-8050-4E6A-815A-9F083D80A2F8</string> <string>28CCC198-2A33-4677-8B8E-4774BF542C54</string> <string>9038D5E1-01AC-41B8-BEB2-681702E589FF</string> <string>8B3912D3-1C28-4DF2-8883-6C4B05377278</string> <string>4C10EFDF-A3CE-48E3-8B9B-5174B0163EC2</string> <string>24F07D3F-9B21-4035-A519-CF84DA5DB543</string> <string>A0B83920-09E1-4361-8597-5B05BA1A23F9</string> <string>5C8F03CB-AAD6-42F4-B20B-705D101354C7</string> <string>C25BD8B9-99B8-429E-9499-BEA2C3C2F8C0</string> <string>849C7A84-7E2B-4420-AE9D-FEFB11CA4A3F</string> <string>67A5B7BD-0E56-477D-A38C-B101A2719988</string> <string>56525EF4-4A5C-4415-B2D9-9D135CA32157</string> <string>9C179D97-C855-420C-8689-642EB11AC767</string> <string>F0FB9A33-FFB9-43D3-847D-AEF559D86B68</string> <string>7B0D2A4C-CF10-4985-AEE3-212D3C479C38</string> <string>ADA257DD-BB15-4CFD-BB53-55C7E1A30365</string> <string>7F5D11B3-45DE-41E6-B5D1-71F370315500</string> <string>92F58CD9-AE3E-4553-BA7B-B10FD1376B2F</string> <string>259B5FFC-6CB8-4141-8270-CCEF88550A04</string> <string>C953538A-5B40-4D20-B920-EE242B415A21</string> <string>C6B47D42-9614-4C5A-A862-81A4E59EFC55</string> <string>AAC6EB2B-2BE9-4CF5-995A-09C4632E5809</string> <string>F8CE823F-8C57-4DAF-957A-C2370F49EB8D</string> <string>DA3FB6A9-6C8A-47F1-932B-76E9AC9FF4A8</string> <string>30468398-BDF8-4221-B8C1-108D660B5462</string> <string>317DCAFC-B419-43D1-9516-CB020D48FE08</string> <string>7FFE3035-50A2-43BC-9A6A-D3392DD711DA</string> <string>67FC60DD-74BC-40D8-96F5-77E90D45E820</string> <string>BE836A4A-003B-43B6-845D-E19A813D7E57</string> <string>523CD084-3B13-46DB-AB6F-8961EC5914CB</string> <string>5FA14C8D-B9CA-4635-B0ED-A9F6E8133716</string> <string>DF07EEE5-5D1C-4226-921C-862390ED60D9</string> <string>02288997-F2FE-4F78-86B5-7EB341820E31</string> <string>09B68D0D-9DF3-4183-A57C-12352C1F992A</string> <string>B040F5CB-43F8-442C-88D7-0C8B8FDB8989</string> <string>BA93AEF3-2AF9-4987-820C-71788DE2DEF3</string> <string>A28980B1-0C97-4C38-AC73-788170AE1D32</string> <string>4A1ADF4A-5EDD-4D82-8141-B91E66BFD80D</string> <string>6D88583E-821E-4921-AABD-997C5738F059</string> <string>EC3B9C82-CD02-4EDE-B292-457CC8774E41</string> <string>AE66DCD8-09E8-4EED-BAA6-031BACF237A0</string> <string>A56B5F64-EF48-4000-B7D4-78B6C0E04CC1</string> <string>11346CB0-A4DE-4DFF-BB31-E2D4DCDD14FC</string> <string>206C70C1-010B-43F9-BC75-0CA766DB2DD3</string> <string>B97E295E-62AD-4DD6-9E2D-625B016CC5AA</string> <string>17180447-13E1-4330-A9DD-18D9DD6B8C2B</string> <string>DAF8DD98-B342-4746-B017-EA3AA8861EE9</string> <string>2FD9FC81-619B-4256-AFDB-4E1B4EB3B479</string> <string>65714417-FFB2-441B-8A92-E660882D3A9B</string> <string>CA71EDF5-8BDC-4CEF-A25B-91AD55BA9C07</string> <string>A0DFAD24-FBA0-4867-841C-2DDA8B863454</string> <string>E1F8DF31-6867-4D7B-96C1-842A860C3CF1</string> <string>A8EEDB00-F4F2-4EC3-AB22-14A5E331D89C</string> <string>C4BE4DC7-045B-470E-9BEE-6438C19D6D51</string> <string>E411CA38-BF07-480C-AA82-864F2AF548B6</string> <string>300C9DE5-E673-4A8F-B678-8A86E6AC24F6</string> <string>31A1B000-84FE-4FC6-B941-B2080F6908E9</string> <string>4554BD19-8A33-460E-BDC8-B2E4525D508F</string> <string>48BF60D2-E9C1-4F1E-9FF8-BB08FC6F7A32</string> <string>B09C244B-F8E0-4069-A4FF-5029DA586F72</string> <string>6D3C12F2-DF3C-40F8-B47E-381FDD0A981A</string> <string>60F3E813-2319-4310-9985-B7B50C0A9A33</string> <string>32B99607-5DE8-4560-8079-2D84CD4E0001</string> <string>F34A2296-6FF0-4090-ABAB-2C9D6F7EF482</string> <string>14E4A176-FB73-41C7-BCF5-B11F90733CE9</string> <string>D000FBCE-5C70-45C2-B9D2-86C42500568C</string> <string>6DB8C1A2-09F5-4C4E-B4D8-A75F5E3D76FF</string> <string>07A7E990-237A-43F9-A87E-8EA14DD81333</string> <string>C245FB6E-95C2-4D6E-935F-A7F470328E49</string> <string>0528B454-B8BC-466B-9AF9-BE68BC77E4E1</string> <string>3D9D15C5-2E00-4332-9169-FC35542D1BEB</string> <string>96265680-CFE2-404F-B614-B83B78AC1A0C</string> <string>245A194E-803F-4951-BF63-19D639AA99FB</string> <string>4B02989E-5D1A-497D-8FC1-561E4F2B67AB</string> <string>9CA961D9-F34C-489F-865A-EB20A896C0F6</string> <string>0FA5ADFC-C4D7-45D8-B745-2C0BC538179B</string> <string>696428FC-070E-4D23-ACFD-0469CCC70079</string> <string>2EDD4802-B07E-4CC2-9A88-B563FF05146E</string> <string>286B13D0-E6C9-423C-B593-CD4B59A87E8F</string> <string>041AC446-491D-4416-8E14-E60C8018A0D5</string> <string>EB8C4DE1-8A2A-4C1B-AE5D-57D3FC8281CC</string> <string>5BD2B7EB-5452-420D-BF49-B33C1D4E8706</string> <string>268F708E-DBD4-4E38-9194-7063950783D7</string> <string>DCAD363E-492B-49FD-B84F-43A3F77118CD</string> <string>9072A654-06FA-42D6-950D-90E33975B2EB</string> <string>3F07F52E-724D-4D8D-84E4-D4E87220B020</string> <string>9DE5A98B-BEB2-4F3E-997C-4851CDAD76C5</string> <string>FFADDBFF-B24E-4C06-8C4C-B28F6BD42349</string> <string>538BB22C-E30C-45E4-92D1-F837360785AF</string> <string>40BC17A0-BC89-4D08-A1C0-A54C85E90B46</string> <string>509BDA8F-1AE1-4B62-9E5C-3742AE06167B</string> <string>3F56DF3C-E73E-4133-B4D0-6EA5926E61B3</string> <string>E50E3BBE-8581-4EC4-8875-717CA123463E</string> <string>4E3ABBC1-20D2-4D0F-BC10-A128F85AD5BE</string> <string>BF26D328-E8B2-4255-AB7E-E139FD8161CE</string> <string>087457F5-B8B2-4673-8E60-92430D951D4C</string> <string>A79C2E63-7CBD-453A-AD1A-B4B15A554C6B</string> <string>8FC0283E-CE94-450F-9560-9990FB253D95</string> <string>3FA1DAF0-1259-41F5-B642-872D9FD60297</string> <string>21ADF248-F14F-469F-956B-14251B78B83A</string> <string>92CA447A-F1ED-4C5A-B999-DFE13C587B8C</string> <string>4F173886-8EF8-422A-A368-8E2F1B3699C0</string> <string>FA4CAE63-B259-4A38-943B-88F1444835DB</string> <string>452C6FF5-FF58-4799-841F-786BB2386B5C</string> <string>12C986E9-3511-4179-AA1A-204BF3AC0EBB</string> <string>9C53FE15-1C26-41B5-8ADE-EA902A7FCD89</string> <string>606B7B7B-236D-42DE-AF65-5C9CBE79EDF5</string> <string>C9DDCAF9-7A94-40B8-A355-17CBFD9FB0CB</string> <string>80797385-06D3-45A6-A034-8C5BE53A5419</string> <string>B8181ACC-5FBB-4813-BCBD-42326F575D16</string> <string>C1E197A3-22AB-4EA7-8D06-E53478B70CD6</string> <string>6D8B302B-3980-4B6D-AB18-0642220A1D09</string> <string>4B4BAF15-6DDF-4AEC-A949-C09DF23D3A0E</string> <string>70B7E6F1-FB81-4741-87D7-6E2CDBEBE6CA</string> <string>2A358D34-E286-48DB-8FE4-34957124FE4B</string> <string>F99266AC-C47B-4662-8140-91FC9CD83CD1</string> <string>1F895B4D-8226-4945-9AFB-7680E54A8AF6</string> <string>0CABE9A1-3E50-4516-9EE2-2189D1D87724</string> <string>6DBA82BD-A1CE-40CA-B200-23E82562ACB5</string> <string>956A0059-FFF9-4B14-9072-9B66B8D85BC7</string> <string>65E81A15-9D95-4CE8-B2D1-9952FEF5226F</string> <string>37710819-E241-495B-8EED-4FDCD9BE6A22</string> <string>229077E7-4284-4085-A449-3C5AA8DCF41B</string> <string>710BC149-0A06-48FE-87A7-4CABA810A519</string> <string>A8B0343F-CD2C-41E7-BFE5-133C9AE9675F</string> <string>A67CBED1-95F6-4920-A8D7-E84E650520ED</string> <string>56173E05-CA6A-4773-AB05-050A3BBF0F49</string> <string>40D70647-3C75-4588-9CFC-3448A881F79E</string> <string>67D98396-31F6-4821-BF31-F75F08A92850</string> <string>7E41534A-A1FF-4214-A106-2B721FB1A920</string> <string>B01C3BE2-956D-4E5A-9DE0-2FA6B544DA25</string> <string>96F76523-E10D-4366-BFF0-918D22BA37E9</string> <string>DCBE259C-2268-4194-A4FE-03E53A232FBD</string> <string>F61A0D68-C33F-48F6-B045-B1B3C4EF9525</string> <string>B3617124-733D-47EC-9B2A-FAD4C0397831</string> <string>BD44D578-30A0-4ECF-A8E2-4A23C36BD8DE</string> <string>8AF8F6D9-32FD-4AAB-8453-7A2FDE3FD382</string> <string>4AEAA48E-D914-4EB4-B917-01D00D0C8E0B</string> <string>1CF0F70D-B223-4B80-8454-4AEC0B5A10D2</string> <string>7830F906-A21D-441D-BA1D-E37635247542</string> <string>085B8E6C-388F-456F-882C-B8D3392D61FA</string> <string>A75D991D-240C-43AA-B9A6-553AC44F76FA</string> <string>53B9B5E7-D897-49E4-AEEC-DE94F781AA2B</string> <string>6B126A42-3320-4978-8ADF-F53C600B5795</string> <string>00DA1390-C91E-4583-B83B-CC16F8892239</string> <string>EC7BC99A-B82D-43EC-AEF2-8EB54041CDE6</string> <string>3B195EF9-CCC3-4B2D-91D3-15D514E5F4BF</string> <string>6521B870-750F-4109-8BBF-2910D584C525</string> <string>16F25A48-3166-4E7C-8F80-DC9E61C65645</string> <string>018DC512-CE52-4DCC-B556-DA3A9AD96FE6</string> <string>94993BC1-CB55-4F02-9705-70ABCED8CFC9</string> <string>5622EC10-8A81-4C9F-87C3-E3B6A9B4D96B</string> <string>498615E3-E82E-4CD3-A526-EBAE9F68C7EF</string> <string>217C9FA9-BB27-403B-8CBD-659B64FA6CF4</string> <string>102E8B00-3629-43A3-A2D4-864C6CF0CD32</string> <string>4B01C66D-8A74-4433-A07D-8FE705C7A352</string> <string>9924DCE9-8C1C-4CAE-B232-E9FD07E1B53E</string> <string>9A1B4C8F-EC35-4F05-8AB0-8122EB4B9A93</string> <string>01E0876B-4D91-49AF-937A-7EC39DDDEE79</string> <string>774B14A7-EDC4-4855-9915-6AB8B15D2F68</string> <string>D8D50F69-36E3-45DA-807E-29D1E5914DD8</string> <string>1CFD7E53-FFF7-46A8-9149-49E9F5088E55</string> <string>3E572472-BBF1-4DDA-AFCF-D52B95B0ADFB</string> <string>EBCC36A0-38E4-438D-BB39-6D3AC690C8AF</string> <string>4158361F-D366-4BAA-8CC5-DC46AD449229</string> <string>EE1507E5-F01B-4D73-8EE6-CCFECE98C3F4</string> <string>C280847F-1A0C-47CC-9EE5-168B9973A8BB</string> <string>F54727CC-8F88-4D17-AC6A-B5E4C8AC872F</string> <string>FA9F757A-290F-4E33-92FC-9E6214113E58</string> <string>C772C456-6B38-4987-87CF-D10486D185A9</string> <string>1A402F7D-1B17-4090-BFD6-42BD426FF0A6</string> <string>A80FF473-4E66-4DBF-89E2-3BC1AFC00A0D</string> <string>6A325FC2-6C57-4B2C-9326-3244EAC96A47</string> <string>87D35E2A-FCC1-4496-9198-8BC85C16E97F</string> <string>63538655-54A5-465E-9E8D-9F57ABA5E40D</string> <string>BA7CE17D-DDC3-4394-808D-6D58588C329C</string> <string>EF439919-653A-4250-B8B6-9337DA8DD851</string> <string>0A58EA58-3BBC-4A07-80FF-366933CF24A7</string> <string>B00CB7C5-C864-493C-9C6E-DCF759CE3B6A</string> </array> <key>name</key> <string>ColdFusion Functions</string> </dict> <key>C8F9D7A6-D447-4C16-B566-BE46335B1067</key> <dict> <key>items</key> <array> <string>97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14</string> - <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> <string>862EDD04-D606-4EDB-8D01-425D8024CF1B</string> <string>0AF4E3E4-8638-4EAD-B182-A4FE571E9974</string> <string>38EB1CC2-4A1A-4C37-9D69-19D81129C5DC</string> <string>E0D7DCCA-9801-4DD5-9C26-3B607BEF7135</string> <string>241129A8-4AF3-4005-B276-6F431B5CB3F2</string> <string>8AE48664-E323-4DF9-BED2-CE700CAC7C15</string> <string>08392E18-5D55-41CB-BE64-7B091492E7BF</string> <string>9AEFE392-91BE-4968-8FF8-8A2C9D51D4CC</string> <string>67423190-2729-4C30-B10D-51B7DC3FAB85</string> <string>1B072993-0FFD-44B7-8C6D-3F9D60AF9E7B</string> <string>B8817D6A-B326-48F9-9E35-B28778A79412</string> <string>157C15A0-D535-4EAB-8173-6D6EB0906173</string> <string>0E400696-4C11-4072-9DAD-7BFF6F7789BE</string> <string>5A2941B5-2D73-4348-AB92-932665EB6E1D</string> <string>902C51B4-E4E3-4B2C-BA03-769FC6AC0867</string> <string>5CF87863-EBA1-49BE-AB51-016A2D0FDA80</string> <string>A72AC858-A593-4758-894F-266F9925990D</string> <string>6E59F119-65E3-4D1F-B393-121208A9A83F</string> <string>E336E487-B1EA-449C-9B32-4C5994136CEA</string> <string>90B1EE50-DAC5-4748-8415-5C3ABB38CFD5</string> <string>784AAEB3-2367-4275-95E0-DFDBE61E9423</string> <string>D5310F63-357F-4E8A-9583-26F569D309EB</string> <string>1ADF5606-9DC3-413F-8BC2-5E54E7BAC4FF</string> <string>28364618-9329-4501-98EC-852D28D2F59A</string> <string>EA2AA961-32E7-4B4B-85C8-0F458AC6E671</string> <string>A14677C7-FB24-4A35-B9F5-F764C2EFE00E</string> <string>5736162D-BDF6-4C94-8F3C-8F4CEB38E349</string> <string>C6C27604-1D24-4EC3-B40D-BD1FF6196DF8</string> <string>96D4FDBD-4A7D-42E4-BF7A-AB366E22758B</string> <string>E1BBA1F0-05C7-4EA0-87BA-FB0FC5D1CAED</string> <string>C8C2C389-AEE0-4CE2-8944-A7EEEFB9B680</string> <string>36F4B163-2ACD-48F1-8E72-365E54EB7811</string> <string>5D0E9DF4-6631-419C-AEEE-7710EE30502F</string> <string>0A3097F1-36A8-4009-8501-CC5B9349072E</string> <string>C28091B5-3245-4E3C-BC49-38AAB093D00F</string> <string>1D9BEE6E-907F-430A-BD62-2DF38A454B3E</string> <string>B8DC9CF1-AFF5-44E4-B9A8-42093D829889</string> <string>BEDB5CCC-7FF1-4C78-8169-2B58BFB2C449</string> <string>E6EE6F14-372D-469B-B31F-827A54CFC5E3</string> <string>DB5DE93A-DA9A-40E9-B469-EF8337A11CBE</string> <string>63B626CD-2818-42F2-BD90-DE112A8DEF7A</string> <string>5C3D7157-DFC0-4762-B059-C10F1A098089</string> <string>BD84E1FB-DCA2-493E-887E-1A1330DD6EA9</string> <string>CED5A340-3643-4F34-A8ED-A9FB99008300</string> <string>AB4A8782-7466-4B5D-A180-96E0BD19C050</string> <string>D01E4126-187A-4275-8583-DFA44FE3BB3C</string> <string>F9725187-DAE2-43BB-9209-BAF4F709AD72</string> <string>C83F3775-A62D-425B-B05E-C6A58C929399</string> <string>6674FAC2-9201-4D0D-BAA5-E35D64BDADDC</string> <string>53E1E9D3-8F53-4CFE-8ADD-83AC13969D24</string> <string>415DDDAF-1163-49E7-8D5B-3B6CD1A27A06</string> <string>B2FCBECB-D1E0-4BF4-B046-5A9C4A6475F9</string> <string>601BA2FE-EA4D-4B9C-A8EF-646A9E9626DD</string> <string>B14D6A84-2B4D-4FF8-99CB-E2B41B0E00BF</string> <string>29745C05-70EC-418A-A7E1-E60EE6042A95</string> <string>2FB6FDE3-F8F0-47A1-AE6D-AA3895A489CD</string> <string>0B69D306-8DF0-4494-87AC-B8E92091E0E6</string> <string>9AA75F85-02C0-4006-9D95-F7EC2728A050</string> <string>192D1402-A2E5-43F1-B0C5-990853DB5D98</string> <string>8BBB6187-A1D9-43AF-AF72-CDF3BB8B0A76</string> <string>DE1C603E-D791-469F-99D3-69E17B9B41EB</string> <string>FA01E47F-EB01-4FE1-9EB6-96FDEB923E70</string> <string>AA6262C5-CA32-415E-B666-D2FBF93E0905</string> <string>80B9754E-47ED-46D6-8BA5-80744B0FBE4B</string> <string>9A1343CB-5E9E-45A2-8D21-B4959C412B6E</string> <string>622A22FB-207B-4322-BC6C-C2B3D605AF00</string> <string>4DD466D2-0B15-4E06-8446-5AFBFC8B4128</string> <string>183709C1-9414-4A25-89FB-A0D9A7E59D27</string> <string>35060F61-EF40-4046-BF12-1AB2748884A1</string> <string>44EA1298-2450-498B-82F6-1BF1BC1FFE59</string> <string>29486C8D-7A9A-4EE0-B6A3-34C77A7D253E</string> <string>7F70512F-517F-4361-89ED-13E8C3BD98F0</string> <string>2A8760F9-6ED1-4066-B996-5E490B5A17EF</string> <string>9187A792-54F4-4773-A2D7-EB5D207D1A54</string> <string>F0AFF0A1-90FA-424F-A6AF-6EA6EC1BB225</string> <string>026FDCF1-E739-42E4-925D-59D80EE7FF05</string> <string>50182FB9-0179-4CF6-9AD7-4E7BC725C594</string> <string>3B19D8BC-5389-4263-A539-160170F7DFB1</string> <string>B096E910-EE96-4E63-BB46-EB12616C80F6</string> <string>08743309-6431-44D2-8A38-926516B04BEF</string> <string>A4876D40-55A7-44A0-9CDD-BCF62A621FC3</string> <string>5C441A88-2F12-4C54-83F8-81A62F735F88</string> <string>FDDBDC40-D1D9-4981-92DE-30CA475BC8FA</string> <string>3C93CAC9-0DC3-4371-8E5F-2727B0A282BD</string> <string>6F5A4D8F-DE7C-4663-9D39-7BF23D84769E</string> <string>75FFC09D-CB71-49CF-AB01-3DA8C44F29F3</string> <string>97DD90F8-5334-46A0-B973-C59F357D6C31</string> <string>3ED1297F-4C77-4187-9356-4262D3F28625</string> <string>F36E8F58-CDBD-4E42-A64F-9D05BE2D49B9</string> <string>1B6D6622-49BD-4EAB-B521-B3D1ACF2E4B1</string> <string>E09B46CF-DDE0-4B40-B7AF-93C005F23BAB</string> <string>A607B362-68CB-4AE3-BE72-575EB7CBA55A</string> <string>A57CC7BE-F39A-4B64-908D-44EA058C294F</string> <string>0C5234DB-A0F6-4BE2-AF28-5276ED3F81BB</string> <string>BC74CDF9-65E1-4FD0-A939-110CF53F3F67</string> <string>D6CFEC97-357A-4EBD-9D95-F89FECD4ED66</string> <string>293B3EF2-892E-4FF9-BB3B-82AE01FFA38D</string> <string>24AEB6C9-9CDE-478C-9C08-5CB1825321AE</string> <string>4417C4C8-F581-41FC-96FF-76A28A1F0640</string> <string>BC022681-5DE4-4E5C-8638-93EF655F7B0D</string> <string>47BD7B3C-4316-4C5B-AD7D-596D90D64A7C</string> <string>ED205418-D60B-41CE-9942-6855C78C65F6</string> <string>AEA7BB76-4231-41DC-829C-D093F7BF28E5</string> <string>F29A9DA7-B58E-4839-8664-2C99C5679384</string> <string>7423A717-6340-4CEC-9151-2B882D052CB9</string> <string>6E621AA5-5304-4DCE-82B9-820FDB78C5FE</string> <string>21B96169-6556-4436-B3B2-4556A6372567</string> <string>7A62D445-BDCF-4C67-8B71-35255FACC231</string> <string>9B25BE9A-A2E8-4BA6-A1CD-A545C6A3AEDE</string> <string>AD74D8BA-A774-4748-BF7E-22A6E94194ED</string> <string>8743E910-AD98-42C7-AC9D-4EBD26B54456</string> <string>5EB9976E-F76E-40FE-828F-22B393BA59AE</string> <string>8A82A0E0-7396-436B-A3FD-46680599A33A</string> <string>B36FA4B0-F6AE-4489-97D1-54BFE773A560</string> <string>281422A7-AF82-45BF-8707-4242A22FA908</string> <string>CD089D33-F3B3-4BC8-9650-B7CF29B877BF</string> <string>18A3925F-BF0F-4FAF-B45C-C02B2D4C4CB1</string> <string>7188A872-4A9F-4A05-ADCA-46D83E911D2D</string> <string>6322FE39-5B27-49EF-A632-A6073EDCE0C4</string> <string>BEC86CCF-C220-4B07-9ACD-320238D1FE48</string> <string>1F61F24F-166C-4D2E-98B0-7BA454B21619</string> <string>5BAF7E27-FEAB-43E0-899F-ABE9DA500FD0</string> <string>EE49E017-4812-4CAA-8CCC-29DAB3BE7B64</string> <string>97F31F3F-B885-4DE8-B784-5582990C21CD</string> <string>5D2DC339-C6E8-4919-9500-DD24DC9D2F73</string> <string>9E6E0847-D0DB-435D-A129-CA90BE6B9210</string> <string>82B42D60-DC77-47AA-B433-14969E2A2CEB</string> <string>DE1DB107-EC48-4128-B400-203B72AFD40F</string> <string>2051A0AE-51E2-413F-9CCB-92826FCD5C99</string> </array> <key>name</key> <string>ColdFusion Tags</string> </dict> </dict> </dict> <key>name</key> <string>ColdFusion</string> <key>ordering</key> <array> + <!-- Matching types ([##]), etc --> + <string>00D00AD7-3C05-46E0-B8B9-0F5CCAC04F57</string> + <!-- Coldfusion comment --> + <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> </array> <key>uuid</key> <string>1A09BE0B-E81A-4CB7-AF69-AFC845162D1F</string> </dict> </plist>
robrohan/coldfusion.tmbundle
fb749955b6c99c7da0489bc5a26a7ba0423f8912
Adding in folding on cffunction and adding in cfscript coloring using Javascript rules
diff --git a/Syntaxes/ColdFusion.tmLanguage b/Syntaxes/ColdFusion.tmLanguage index c4fe7c2..7badec5 100644 --- a/Syntaxes/ColdFusion.tmLanguage +++ b/Syntaxes/ColdFusion.tmLanguage @@ -1,317 +1,436 @@ <?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" + "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> + <key>fileTypes</key> <array> <string>cfm</string> <string>cfml</string> <string>cfc</string> </array> + <key>foldingStartMarker</key> <string>(?x) - (&lt;(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent)\b.*?&gt; + (&lt;(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction)\b.*?&gt; |&lt;!---(?!.*---\s*&gt;) )</string> + <key>foldingStopMarker</key> <string>(?x) - (&lt;/(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent)&gt; + (&lt;/(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script|ul|ol|form|dl|cfloop|cfif|cfswitch|cfcomponent|cffunction)&gt; |^(?!.*?&lt;!---).*?---\s*&gt; )</string> + <key>keyEquivalent</key> - <string>^~C</string> + <string>^~@c</string> + <key>name</key> <string>ColdFusion</string> + + <!-- CFOUTPUT --> <key>patterns</key> <array> + <!-- CFOUTPUT --> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfoutput))\b(?![^&gt;]*/&gt;)</string> + <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.cfoutput.cfm</string> </dict> </dict> + <key>end</key> <string>&lt;/((?i:cfoutput))&gt;(?:\s*\n)?</string> + <key>name</key> <string>meta.tag.cfoutput.cfm</string> + <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>&gt;</string> <key>contentName</key> <string>meta.scope.output.cfm</string> <key>end</key> <string>(?=&lt;/(?i:cfoutput))</string> <key>patterns</key> <array> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> </array> </dict> + + <!-- CFQUERY (SQL Embedded) --> <dict> <key>begin</key> <string>(?:^\s+)?&lt;((?i:cfquery))\b(?![^&gt;]*/&gt;)</string> + <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.cfquery.cfm</string> </dict> </dict> + <key>end</key> <string>&lt;/((?i:cfquery))&gt;(?:\s*\n)?</string> + <key>name</key> <string>meta.tag.cfquery.cfm</string> + <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> <dict> <key>begin</key> <string>(?&lt;=&gt;)</string> <key>end</key> <string>(?=&lt;/(?i:cfquery))</string> <key>name</key> <string>source.sql.embedded</string> <key>patterns</key> <array> <dict> <key>include</key> <string>source.sql</string> </dict> </array> </dict> </array> </dict> + + <!-- Bit of a Hack: Use Javascript to emulate cfscript --> + <!-- TODO: Put a bit more work into this --> + <dict> + <key>begin</key> + <string>(?:^\s+)?&lt;((?i:cfscript))\b(?![^&gt;]*/&gt;)</string> + + <key>captures</key> + <dict> + <key>1</key> + <dict> + <key>name</key> + <string>entity.name.tag.cfscript.html</string> + </dict> + </dict> + + <key>end</key> + <string>(?&lt;=&lt;/(cfscript|CFSCRIPT))&gt;(?:\s*\n)?</string> + + <!-- for now just use JS for cfScript (mostly right) --> + <key>name</key> + <string>source.js.embedded.html</string> + + <key>patterns</key> + <array> + <dict> + <key>include</key> + <string>#tag-stuff</string> + </dict> + + <dict> + <key>begin</key> + <string>(?&lt;!&lt;/(?i:cfscript))&gt;</string> + + <key>end</key> + <string>&lt;/((?i:cfscript))</string> + + <key>patterns</key> + <array> + <dict> + <key>match</key> + <string>//.*?((?=&lt;/cfscript)|$\n?)</string> + <key>name</key> + <string>comment.line.double-slash.js</string> + </dict> + <dict> + <key>begin</key> + <string>/\*</string> + <key>end</key> + <string>\*/|(?=&lt;/cfscript)</string> + <key>name</key> + <string>comment.block.js</string> + </dict> + <dict> + <key>include</key> + <string>source.js</string> + </dict> + </array> + </dict> + </array> + </dict> + + <!-- Any ColdFusion tag --> <dict> <key>begin</key> <string>&lt;/?((?i:cf)([a-zA-Z0-9]+))(?=[^&gt;]*&gt;)</string> + <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.tag.cfm</string> </dict> </dict> + <key>end</key> <string>&gt;</string> + <key>name</key> <string>meta.tag.any.cfm</string> + <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-stuff</string> </dict> </array> </dict> + + <!-- Coldfusion Comment --> <dict> <key>include</key> <string>#coldfusion-comment</string> </dict> + + <!-- Other Tags --> <dict> <key>include</key> <string>text.html.basic</string> </dict> </array> + + <!-- Reused Partitions? --> <key>repository</key> <dict> <key>coldfusion-comment</key> <dict> <key>begin</key> <string>&lt;!---</string> + <key>end</key> <string>---&gt;</string> + <key>name</key> <string>comment.block.cfm</string> + <key>patterns</key> <array> <dict> <key>include</key> <string>#coldfusion-comment</string> </dict> </array> </dict> + <key>embedded-code</key> <dict> <key>patterns</key> <array/> </dict> + <key>entities</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>&amp;([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);</string> <key>name</key> <string>constant.character.entity.html</string> </dict> <dict> <key>match</key> <string>&amp;</string> <key>name</key> <string>invalid.illegal.bad-ampersand.html</string> </dict> </array> </dict> + <key>string-double-quoted</key> <dict> <key>begin</key> <string>"</string> + <key>end</key> <string>"</string> + <key>name</key> <string>string.quoted.double.cfm</string> + <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> + <key>string-single-quoted</key> <dict> <key>begin</key> <string>'</string> + <key>end</key> <string>'</string> + <key>name</key> <string>string.quoted.single.cfm</string> + <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> + <key>tag-generic-attribute</key> <dict> <key>match</key> <string>\b([a-zA-Z\-:]+)</string> + <key>name</key> <string>entity.other.attribute-name.cfm</string> </dict> + <key>tag-id-attribute</key> <dict> <key>begin</key> <string>\b(id)\b\s*=</string> + <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.other.attribute-name.id.html</string> </dict> </dict> + <key>end</key> <string>(?&lt;='|")</string> + <key>name</key> <string>meta.attribute-with-value.id.cfm</string> + <key>patterns</key> <array> <dict> <key>begin</key> <string>"</string> + <key>contentName</key> <string>meta.toc-list.id.cfm</string> + <key>end</key> <string>"</string> + <key>name</key> <string>string.quoted.double.cfm</string> + <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> <dict> <key>begin</key> <string>'</string> <key>contentName</key> <string>meta.toc-list.id.cfm</string> <key>end</key> <string>'</string> <key>name</key> <string>string.quoted.single.cfm</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#embedded-code</string> </dict> <dict> <key>include</key> <string>#entities</string> </dict> </array> </dict> </array> </dict> + <key>tag-stuff</key> <dict> <key>patterns</key> <array> <dict> <key>include</key> <string>#tag-id-attribute</string> </dict> <dict> <key>include</key> <string>#tag-generic-attribute</string> </dict> <dict> <key>include</key> <string>#string-double-quoted</string> </dict> <dict> <key>include</key> <string>#string-single-quoted</string> </dict> <dict> <key>include</key> <string>#embedded-code</string> </dict> </array> </dict> </dict> + <key>scopeName</key> <string>text.html.cfm</string> + <key>uuid</key> <string>97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14</string> </dict> </plist> diff --git a/info.plist b/info.plist index 8d8890b..8fb09a5 100644 --- a/info.plist +++ b/info.plist @@ -1,601 +1,612 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>contactEmailRot13</key> <string>[email protected]</string> + <key>contactName</key> <string>Rob Rohan</string> + <key>description</key> - <string>Support for the &lt;a href="http://www.adobe.com/products/coldfusion/"&gt;ColdFusion&lt;/a&gt; web development environment from Adobe.</string> + <string>Support for the ColdFusion web development environment.</string> + <key>mainMenu</key> <dict> <key>items</key> <array> <string>C8F9D7A6-D447-4C16-B566-BE46335B1067</string> <string>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</string> + <!-- <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> <string>2DD711BA-8C2D-4AF4-85C2-C42733743D0A</string> - <string>5C998560-6284-4F59-A6F9-420962E130E2</string> + <string>5C998560-6284-4F59-A6F9-420962E130E2</string> --> </array> + <key>submenus</key> <dict> <key>1202B1E1-6A18-4C9E-AB30-70A0E046CDB7</key> <dict> <key>items</key> - <array/> + <array> + <string>0AF4E3E4-8638-4EAD-B182-A4FE571E9974</string> + <string>38EB1CC2-4A1A-4C37-9D69-19D81129C5DC</string> + <string>E0D7DCCA-9801-4DD5-9C26-3B607BEF7135</string> + <string>241129A8-4AF3-4005-B276-6F431B5CB3F2</string> + <string>8AE48664-E323-4DF9-BED2-CE700CAC7C15</string> + <string>08392E18-5D55-41CB-BE64-7B091492E7BF</string> + <string>9AEFE392-91BE-4968-8FF8-8A2C9D51D4CC</string> + <string>67423190-2729-4C30-B10D-51B7DC3FAB85</string> + <string>1B072993-0FFD-44B7-8C6D-3F9D60AF9E7B</string> + <string>B8817D6A-B326-48F9-9E35-B28778A79412</string> + <string>157C15A0-D535-4EAB-8173-6D6EB0906173</string> + <string>0E400696-4C11-4072-9DAD-7BFF6F7789BE</string> + <string>5A2941B5-2D73-4348-AB92-932665EB6E1D</string> + <string>902C51B4-E4E3-4B2C-BA03-769FC6AC0867</string> + <string>5CF87863-EBA1-49BE-AB51-016A2D0FDA80</string> + <string>A72AC858-A593-4758-894F-266F9925990D</string> + <string>6E59F119-65E3-4D1F-B393-121208A9A83F</string> + <string>E336E487-B1EA-449C-9B32-4C5994136CEA</string> + <string>90B1EE50-DAC5-4748-8415-5C3ABB38CFD5</string> + <string>784AAEB3-2367-4275-95E0-DFDBE61E9423</string> + <string>D5310F63-357F-4E8A-9583-26F569D309EB</string> + <string>1ADF5606-9DC3-413F-8BC2-5E54E7BAC4FF</string> + <string>28364618-9329-4501-98EC-852D28D2F59A</string> + <string>EA2AA961-32E7-4B4B-85C8-0F458AC6E671</string> + <string>A14677C7-FB24-4A35-B9F5-F764C2EFE00E</string> + <string>5736162D-BDF6-4C94-8F3C-8F4CEB38E349</string> + <string>C6C27604-1D24-4EC3-B40D-BD1FF6196DF8</string> + <string>96D4FDBD-4A7D-42E4-BF7A-AB366E22758B</string> + <string>E1BBA1F0-05C7-4EA0-87BA-FB0FC5D1CAED</string> + <string>C8C2C389-AEE0-4CE2-8944-A7EEEFB9B680</string> + <string>36F4B163-2ACD-48F1-8E72-365E54EB7811</string> + <string>5D0E9DF4-6631-419C-AEEE-7710EE30502F</string> + <string>0A3097F1-36A8-4009-8501-CC5B9349072E</string> + <string>C28091B5-3245-4E3C-BC49-38AAB093D00F</string> + <string>1D9BEE6E-907F-430A-BD62-2DF38A454B3E</string> + <string>B8DC9CF1-AFF5-44E4-B9A8-42093D829889</string> + <string>BEDB5CCC-7FF1-4C78-8169-2B58BFB2C449</string> + <string>E6EE6F14-372D-469B-B31F-827A54CFC5E3</string> + <string>DB5DE93A-DA9A-40E9-B469-EF8337A11CBE</string> + <string>63B626CD-2818-42F2-BD90-DE112A8DEF7A</string> + <string>5C3D7157-DFC0-4762-B059-C10F1A098089</string> + <string>BD84E1FB-DCA2-493E-887E-1A1330DD6EA9</string> + <string>CED5A340-3643-4F34-A8ED-A9FB99008300</string> + <string>AB4A8782-7466-4B5D-A180-96E0BD19C050</string> + <string>D01E4126-187A-4275-8583-DFA44FE3BB3C</string> + <string>F9725187-DAE2-43BB-9209-BAF4F709AD72</string> + <string>C83F3775-A62D-425B-B05E-C6A58C929399</string> + <string>6674FAC2-9201-4D0D-BAA5-E35D64BDADDC</string> + <string>53E1E9D3-8F53-4CFE-8ADD-83AC13969D24</string> + <string>415DDDAF-1163-49E7-8D5B-3B6CD1A27A06</string> + <string>B2FCBECB-D1E0-4BF4-B046-5A9C4A6475F9</string> + <string>601BA2FE-EA4D-4B9C-A8EF-646A9E9626DD</string> + <string>B14D6A84-2B4D-4FF8-99CB-E2B41B0E00BF</string> + <string>29745C05-70EC-418A-A7E1-E60EE6042A95</string> + <string>2FB6FDE3-F8F0-47A1-AE6D-AA3895A489CD</string> + <string>0B69D306-8DF0-4494-87AC-B8E92091E0E6</string> + <string>9AA75F85-02C0-4006-9D95-F7EC2728A050</string> + <string>192D1402-A2E5-43F1-B0C5-990853DB5D98</string> + <string>8BBB6187-A1D9-43AF-AF72-CDF3BB8B0A76</string> + <string>DE1C603E-D791-469F-99D3-69E17B9B41EB</string> + <string>FA01E47F-EB01-4FE1-9EB6-96FDEB923E70</string> + <string>AA6262C5-CA32-415E-B666-D2FBF93E0905</string> + <string>80B9754E-47ED-46D6-8BA5-80744B0FBE4B</string> + <string>9A1343CB-5E9E-45A2-8D21-B4959C412B6E</string> + <string>622A22FB-207B-4322-BC6C-C2B3D605AF00</string> + <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> + <string>4DD466D2-0B15-4E06-8446-5AFBFC8B4128</string> + <string>183709C1-9414-4A25-89FB-A0D9A7E59D27</string> + <string>35060F61-EF40-4046-BF12-1AB2748884A1</string> + <string>44EA1298-2450-498B-82F6-1BF1BC1FFE59</string> + <string>29486C8D-7A9A-4EE0-B6A3-34C77A7D253E</string> + <string>7F70512F-517F-4361-89ED-13E8C3BD98F0</string> + <string>2A8760F9-6ED1-4066-B996-5E490B5A17EF</string> + <string>9187A792-54F4-4773-A2D7-EB5D207D1A54</string> + <string>F0AFF0A1-90FA-424F-A6AF-6EA6EC1BB225</string> + <string>026FDCF1-E739-42E4-925D-59D80EE7FF05</string> + <string>50182FB9-0179-4CF6-9AD7-4E7BC725C594</string> + <string>3B19D8BC-5389-4263-A539-160170F7DFB1</string> + <string>B096E910-EE96-4E63-BB46-EB12616C80F6</string> + <string>08743309-6431-44D2-8A38-926516B04BEF</string> + <string>A4876D40-55A7-44A0-9CDD-BCF62A621FC3</string> + <string>5C441A88-2F12-4C54-83F8-81A62F735F88</string> + <string>FDDBDC40-D1D9-4981-92DE-30CA475BC8FA</string> + <string>3C93CAC9-0DC3-4371-8E5F-2727B0A282BD</string> + <string>6F5A4D8F-DE7C-4663-9D39-7BF23D84769E</string> + <string>75FFC09D-CB71-49CF-AB01-3DA8C44F29F3</string> + <string>97DD90F8-5334-46A0-B973-C59F357D6C31</string> + <string>3ED1297F-4C77-4187-9356-4262D3F28625</string> + <string>F36E8F58-CDBD-4E42-A64F-9D05BE2D49B9</string> + <string>1B6D6622-49BD-4EAB-B521-B3D1ACF2E4B1</string> + <string>E09B46CF-DDE0-4B40-B7AF-93C005F23BAB</string> + <string>A607B362-68CB-4AE3-BE72-575EB7CBA55A</string> + <string>A57CC7BE-F39A-4B64-908D-44EA058C294F</string> + <string>0C5234DB-A0F6-4BE2-AF28-5276ED3F81BB</string> + <string>BC74CDF9-65E1-4FD0-A939-110CF53F3F67</string> + <string>D6CFEC97-357A-4EBD-9D95-F89FECD4ED66</string> + <string>293B3EF2-892E-4FF9-BB3B-82AE01FFA38D</string> + <string>24AEB6C9-9CDE-478C-9C08-5CB1825321AE</string> + <string>4417C4C8-F581-41FC-96FF-76A28A1F0640</string> + <string>BC022681-5DE4-4E5C-8638-93EF655F7B0D</string> + <string>47BD7B3C-4316-4C5B-AD7D-596D90D64A7C</string> + <string>ED205418-D60B-41CE-9942-6855C78C65F6</string> + <string>AEA7BB76-4231-41DC-829C-D093F7BF28E5</string> + <string>F29A9DA7-B58E-4839-8664-2C99C5679384</string> + <string>7423A717-6340-4CEC-9151-2B882D052CB9</string> + <string>6E621AA5-5304-4DCE-82B9-820FDB78C5FE</string> + <string>21B96169-6556-4436-B3B2-4556A6372567</string> + <string>7A62D445-BDCF-4C67-8B71-35255FACC231</string> + <string>9B25BE9A-A2E8-4BA6-A1CD-A545C6A3AEDE</string> + <string>AD74D8BA-A774-4748-BF7E-22A6E94194ED</string> + <string>8743E910-AD98-42C7-AC9D-4EBD26B54456</string> + <string>5EB9976E-F76E-40FE-828F-22B393BA59AE</string> + <string>8A82A0E0-7396-436B-A3FD-46680599A33A</string> + <string>B36FA4B0-F6AE-4489-97D1-54BFE773A560</string> + <string>281422A7-AF82-45BF-8707-4242A22FA908</string> + <string>CD089D33-F3B3-4BC8-9650-B7CF29B877BF</string> + <string>18A3925F-BF0F-4FAF-B45C-C02B2D4C4CB1</string> + <string>7188A872-4A9F-4A05-ADCA-46D83E911D2D</string> + <string>6322FE39-5B27-49EF-A632-A6073EDCE0C4</string> + <string>BEC86CCF-C220-4B07-9ACD-320238D1FE48</string> + <string>1F61F24F-166C-4D2E-98B0-7BA454B21619</string> + <string>5BAF7E27-FEAB-43E0-899F-ABE9DA500FD0</string> + <string>EE49E017-4812-4CAA-8CCC-29DAB3BE7B64</string> + <string>97F31F3F-B885-4DE8-B784-5582990C21CD</string> + <string>5D2DC339-C6E8-4919-9500-DD24DC9D2F73</string> + <string>9E6E0847-D0DB-435D-A129-CA90BE6B9210</string> + <string>82B42D60-DC77-47AA-B433-14969E2A2CEB</string> + <string>DE1DB107-EC48-4128-B400-203B72AFD40F</string> + <string>2051A0AE-51E2-413F-9CCB-92826FCD5C99</string> + <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> + <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> + <string>2DD711BA-8C2D-4AF4-85C2-C42733743D0A</string> + <string>5C998560-6284-4F59-A6F9-420962E130E2</string> + <string>5DBF4A9D-7C3E-4FAD-B6DE-16AB145F081B</string> + <string>C3F1BC8E-892F-4FB5-8A63-F8225B42CCFC</string> + <string>3B7767FB-E117-4543-B27C-C178D5F451DF</string> + <string>618D41F8-8A13-42B6-9000-551AA2DF9FA3</string> + <string>ACB55DF1-EE3F-4B20-A3CA-3DC63018212B</string> + <string>466D3581-0875-4E99-952A-0650CB84D33D</string> + <string>17CFEC94-0BF5-40CD-97DD-79A2CAECB041</string> + <string>5C46558A-599C-427F-8A7E-0343F1BED079</string> + <string>D2675FE6-79EF-40C6-A864-A5C6F092BA4C</string> + <string>D61CD41D-9838-4169-A754-424345AC4601</string> + <string>4C31384B-2B27-4C39-B2BB-CC2CA57B659A</string> + <string>02261555-8147-43DF-9D49-AEE4F58E1619</string> + <string>3757F0B8-F3B0-4272-9F6E-8968CE670387</string> + <string>3514ADDF-C60D-4A16-9346-11EB7A2AA61A</string> + <string>90E0EBD1-EC9F-425B-ACC3-06EFAB5F1F69</string> + <string>41ED9831-365B-4D4F-AF8D-2864343E271F</string> + <string>696A8BD3-EF4F-4A4C-A264-93BE6781D657</string> + <string>40051E46-ECE8-4A07-B600-934A3B482EFC</string> + <string>2016AF2A-1AC1-45A8-BCA0-A52F23142863</string> + <string>FD148128-FF2A-4CFE-99F6-FF43653FE8EA</string> + <string>6C79157D-36F9-4F91-B012-BDD27622FF9B</string> + <string>E45A3C54-88D7-4E4A-8092-56854FE825BE</string> + <string>49443738-7978-4865-A1AC-7358A0BEE2DE</string> + <string>C17555B3-A84A-404B-AECA-3F11CA9ABF0D</string> + <string>22ECD416-BC42-4C13-8BAF-F435A144A56E</string> + <string>E0363D86-A148-44D2-9AF9-45A2A57D1676</string> + <string>9992024A-E07D-4E29-9B35-F85038E890AF</string> + <string>23E6B8AA-CA8F-4CCC-BC29-76A027849595</string> + <string>28FE5A03-F962-4ECE-AF92-EE3436D20664</string> + <string>0D55F7C2-16A2-4B78-B390-EF780FF0F2EC</string> + <string>D9676E4C-3E0A-4886-8F2A-03E25DB4D44C</string> + <string>2C83D486-C0A5-4493-8562-BEA824BAD2D7</string> + <string>817F3C02-47AD-4553-9DE2-BDB0EC97BC9F</string> + <string>FEF3A4E6-7B4E-47B6-A529-ED41EDA41002</string> + <string>917BA410-EC71-492D-8472-A3C2CED279FA</string> + <string>6C78FA7D-0B84-4E9A-A063-77490073E99F</string> + <string>0F018E42-BB09-4631-B11E-EDDD267C8DFF</string> + <string>068FD2EE-B721-4DE3-A4E2-F98476C0530A</string> + <string>9A231D17-D36C-4081-B1EE-E3F5016040C1</string> + <string>E648C975-48FA-4818-89B6-34913675E41D</string> + <string>E7FD5C33-5516-4DB0-A553-B832515D17D4</string> + <string>F3102771-3AA4-492D-AD42-2FDB4F686662</string> + <string>C3AE011B-75E2-45AF-B427-864997717FE2</string> + <string>519D474D-FE82-4419-9D5F-AA88D817EDE6</string> + <string>6816281D-E43D-4DEC-AC2B-0E0756A00EEB</string> + <string>25ACCCC1-401C-4084-80DE-6CFFF6FDEA20</string> + <string>41E4F63F-C59D-4712-B29A-9CC83D717469</string> + <string>63CA1E9E-34AB-4EDD-B6CC-16C22EA5B777</string> + <string>2B8BC0E7-93C3-4DE2-957E-8212F6E373C3</string> + <string>19400E23-B260-4E85-AFFD-109708545A80</string> + <string>312DD333-8664-4C27-9C67-ED8B285579D4</string> + <string>9BDE4AC0-BEC2-4585-AEC7-AD60767AFBEE</string> + <string>9D47F8B3-B009-418B-8AB9-0E72D33F137D</string> + <string>79EDA618-F9E9-4A72-8A7F-DDC0D6826C19</string> + <string>0BA580D0-B978-48C0-8CEB-F78042E9F58F</string> + <string>AE303AF0-FAE2-4C2F-A5BF-0745D3161289</string> + <string>228F7B63-E8C8-48EF-9613-A32CAB3FF100</string> + <string>CB454D76-239A-40D2-B194-43CA6DDD9B8D</string> + <string>CBEAE712-0FC9-4210-B157-DC5C264BFCBF</string> + <string>8F41DFB0-285F-4FA7-A21D-210832BEBD60</string> + <string>81541C90-0980-47A1-9B9B-9F3E750016C7</string> + <string>E651A0E3-0EC3-45AC-B7D0-92E2DAD1F733</string> + <string>8D4E0C06-8D06-4871-9D92-5C72B18A5562</string> + <string>D455BE22-95B8-477F-BA2B-22C8C33D2C85</string> + <string>1262430C-CE62-4585-9EFC-7D5D001C5F24</string> + <string>5A00FE89-14AB-4DCA-B601-5FEA6C36F8F4</string> + <string>F82AABEA-89D3-4DE6-8B6C-3B7BDC194667</string> + <string>DEB3845A-FE19-4B41-84AD-EAA44A4BD1DB</string> + <string>3B74EAA8-B431-423C-971B-09349375FE3E</string> + <string>FA705D08-0DFD-4C3B-AB79-FF7719E9258D</string> + <string>C02F0BE6-CDE7-489F-8B1D-C63CD15AEEC6</string> + <string>2559432A-5071-4C85-B71B-A546326C4DE6</string> + <string>2358C3ED-39E9-4CB1-BBE0-C2C0419F4E9C</string> + <string>C91A69A3-2ECA-4F98-8777-E142F6777683</string> + <string>F78D0262-1B71-4AD6-8BB5-C2E9DC9BB083</string> + <string>8FC4AFD0-98E2-414D-8F80-ED36E5BD977A</string> + <string>80ECE03A-C2E3-4334-8F7B-2A2ED7BC80A7</string> + <string>0A20DB84-AAEF-4B95-A19F-18D6F3694798</string> + <string>31B2DCFD-1049-49CF-BCA8-FAE5D0D4917D</string> + <string>DDE93618-33D9-494A-93F0-1E0CAC672042</string> + <string>DD2F9E4A-E204-4CEF-ADCD-18B523A65966</string> + <string>44379253-BF02-4341-8BB2-B40CD39ED593</string> + <string>DF3F5402-8B88-40D3-81F4-B960A6174610</string> + <string>C22A5FC3-65EA-4234-85F2-2B43DFF811FF</string> + <string>041E3434-05CD-49B2-BFC3-4E3BE5643A65</string> + <string>829C9A8E-323D-44DA-BD6F-72AC150755A1</string> + <string>E55FC014-0F85-4A3E-884D-F7C4F3179659</string> + <string>C4D060C7-FF47-4799-AD06-108B3A757EB6</string> + <string>FB98EFB0-2C9C-4037-96CF-5C0644041281</string> + <string>8330E508-BE78-4713-BF73-2C8B08C02883</string> + <string>2452CEE2-65EC-4FF1-8E1E-C77876F1D14E</string> + <string>1B854256-5B23-4FCC-8367-2330D94D200E</string> + <string>BCF434DF-79AB-4F95-83E0-8D9B0163956B</string> + <string>F93D53FB-7669-4780-B53A-16276844A5BD</string> + <string>89150D95-04F4-4A3B-B885-20A9C95E3FBA</string> + <string>4F0429B6-0FB1-4CF6-BCB8-6350EBD89C35</string> + <string>998B082A-A679-4494-B66C-69AA8256E4D2</string> + <string>E03C0C8A-5CBA-4654-A4BD-EB6500901709</string> + <string>62B6DE6D-751C-4599-8094-6F3EA39F2517</string> + <string>ED3D3507-B8D9-4A83-88B7-CAD0F46A664A</string> + <string>958C7148-B01A-4FE8-AA42-88CADB026CBA</string> + <string>DEF118D7-4325-45E5-9AFC-77C80839A76F</string> + <string>AB98AFE4-E946-4CC6-B453-B6E478590152</string> + <string>3B4924D7-1FCB-4D61-85C8-63E69BFC808F</string> + <string>4640A976-0C9E-45AA-912F-AD2EEF351E60</string> + <string>5A3FFFCD-C7A2-457E-8D6E-151680293EBD</string> + <string>CA44FB3A-353F-418C-AC80-1DC89F4D65BF</string> + <string>0CC8642F-3BE7-45DA-86CB-179A4AE9C264</string> + <string>FD813CA3-8050-4E6A-815A-9F083D80A2F8</string> + <string>28CCC198-2A33-4677-8B8E-4774BF542C54</string> + <string>9038D5E1-01AC-41B8-BEB2-681702E589FF</string> + <string>8B3912D3-1C28-4DF2-8883-6C4B05377278</string> + <string>4C10EFDF-A3CE-48E3-8B9B-5174B0163EC2</string> + <string>24F07D3F-9B21-4035-A519-CF84DA5DB543</string> + <string>A0B83920-09E1-4361-8597-5B05BA1A23F9</string> + <string>5C8F03CB-AAD6-42F4-B20B-705D101354C7</string> + <string>C25BD8B9-99B8-429E-9499-BEA2C3C2F8C0</string> + <string>849C7A84-7E2B-4420-AE9D-FEFB11CA4A3F</string> + <string>67A5B7BD-0E56-477D-A38C-B101A2719988</string> + <string>56525EF4-4A5C-4415-B2D9-9D135CA32157</string> + <string>9C179D97-C855-420C-8689-642EB11AC767</string> + <string>F0FB9A33-FFB9-43D3-847D-AEF559D86B68</string> + <string>7B0D2A4C-CF10-4985-AEE3-212D3C479C38</string> + <string>ADA257DD-BB15-4CFD-BB53-55C7E1A30365</string> + <string>7F5D11B3-45DE-41E6-B5D1-71F370315500</string> + <string>92F58CD9-AE3E-4553-BA7B-B10FD1376B2F</string> + <string>259B5FFC-6CB8-4141-8270-CCEF88550A04</string> + <string>C953538A-5B40-4D20-B920-EE242B415A21</string> + <string>C6B47D42-9614-4C5A-A862-81A4E59EFC55</string> + <string>AAC6EB2B-2BE9-4CF5-995A-09C4632E5809</string> + <string>F8CE823F-8C57-4DAF-957A-C2370F49EB8D</string> + <string>DA3FB6A9-6C8A-47F1-932B-76E9AC9FF4A8</string> + <string>30468398-BDF8-4221-B8C1-108D660B5462</string> + <string>317DCAFC-B419-43D1-9516-CB020D48FE08</string> + <string>7FFE3035-50A2-43BC-9A6A-D3392DD711DA</string> + <string>67FC60DD-74BC-40D8-96F5-77E90D45E820</string> + <string>BE836A4A-003B-43B6-845D-E19A813D7E57</string> + <string>523CD084-3B13-46DB-AB6F-8961EC5914CB</string> + <string>5FA14C8D-B9CA-4635-B0ED-A9F6E8133716</string> + <string>DF07EEE5-5D1C-4226-921C-862390ED60D9</string> + <string>02288997-F2FE-4F78-86B5-7EB341820E31</string> + <string>09B68D0D-9DF3-4183-A57C-12352C1F992A</string> + <string>B040F5CB-43F8-442C-88D7-0C8B8FDB8989</string> + <string>BA93AEF3-2AF9-4987-820C-71788DE2DEF3</string> + <string>A28980B1-0C97-4C38-AC73-788170AE1D32</string> + <string>4A1ADF4A-5EDD-4D82-8141-B91E66BFD80D</string> + <string>6D88583E-821E-4921-AABD-997C5738F059</string> + <string>EC3B9C82-CD02-4EDE-B292-457CC8774E41</string> + <string>AE66DCD8-09E8-4EED-BAA6-031BACF237A0</string> + <string>A56B5F64-EF48-4000-B7D4-78B6C0E04CC1</string> + <string>11346CB0-A4DE-4DFF-BB31-E2D4DCDD14FC</string> + <string>206C70C1-010B-43F9-BC75-0CA766DB2DD3</string> + <string>B97E295E-62AD-4DD6-9E2D-625B016CC5AA</string> + <string>17180447-13E1-4330-A9DD-18D9DD6B8C2B</string> + <string>DAF8DD98-B342-4746-B017-EA3AA8861EE9</string> + <string>2FD9FC81-619B-4256-AFDB-4E1B4EB3B479</string> + <string>65714417-FFB2-441B-8A92-E660882D3A9B</string> + <string>CA71EDF5-8BDC-4CEF-A25B-91AD55BA9C07</string> + <string>A0DFAD24-FBA0-4867-841C-2DDA8B863454</string> + <string>E1F8DF31-6867-4D7B-96C1-842A860C3CF1</string> + <string>A8EEDB00-F4F2-4EC3-AB22-14A5E331D89C</string> + <string>C4BE4DC7-045B-470E-9BEE-6438C19D6D51</string> + <string>E411CA38-BF07-480C-AA82-864F2AF548B6</string> + <string>300C9DE5-E673-4A8F-B678-8A86E6AC24F6</string> + <string>31A1B000-84FE-4FC6-B941-B2080F6908E9</string> + <string>4554BD19-8A33-460E-BDC8-B2E4525D508F</string> + <string>48BF60D2-E9C1-4F1E-9FF8-BB08FC6F7A32</string> + <string>B09C244B-F8E0-4069-A4FF-5029DA586F72</string> + <string>6D3C12F2-DF3C-40F8-B47E-381FDD0A981A</string> + <string>60F3E813-2319-4310-9985-B7B50C0A9A33</string> + <string>32B99607-5DE8-4560-8079-2D84CD4E0001</string> + <string>F34A2296-6FF0-4090-ABAB-2C9D6F7EF482</string> + <string>14E4A176-FB73-41C7-BCF5-B11F90733CE9</string> + <string>D000FBCE-5C70-45C2-B9D2-86C42500568C</string> + <string>6DB8C1A2-09F5-4C4E-B4D8-A75F5E3D76FF</string> + <string>07A7E990-237A-43F9-A87E-8EA14DD81333</string> + <string>C245FB6E-95C2-4D6E-935F-A7F470328E49</string> + <string>0528B454-B8BC-466B-9AF9-BE68BC77E4E1</string> + <string>3D9D15C5-2E00-4332-9169-FC35542D1BEB</string> + <string>96265680-CFE2-404F-B614-B83B78AC1A0C</string> + <string>245A194E-803F-4951-BF63-19D639AA99FB</string> + <string>4B02989E-5D1A-497D-8FC1-561E4F2B67AB</string> + <string>9CA961D9-F34C-489F-865A-EB20A896C0F6</string> + <string>0FA5ADFC-C4D7-45D8-B745-2C0BC538179B</string> + <string>696428FC-070E-4D23-ACFD-0469CCC70079</string> + <string>2EDD4802-B07E-4CC2-9A88-B563FF05146E</string> + <string>286B13D0-E6C9-423C-B593-CD4B59A87E8F</string> + <string>041AC446-491D-4416-8E14-E60C8018A0D5</string> + <string>EB8C4DE1-8A2A-4C1B-AE5D-57D3FC8281CC</string> + <string>5BD2B7EB-5452-420D-BF49-B33C1D4E8706</string> + <string>268F708E-DBD4-4E38-9194-7063950783D7</string> + <string>DCAD363E-492B-49FD-B84F-43A3F77118CD</string> + <string>9072A654-06FA-42D6-950D-90E33975B2EB</string> + <string>3F07F52E-724D-4D8D-84E4-D4E87220B020</string> + <string>9DE5A98B-BEB2-4F3E-997C-4851CDAD76C5</string> + <string>FFADDBFF-B24E-4C06-8C4C-B28F6BD42349</string> + <string>538BB22C-E30C-45E4-92D1-F837360785AF</string> + <string>40BC17A0-BC89-4D08-A1C0-A54C85E90B46</string> + <string>509BDA8F-1AE1-4B62-9E5C-3742AE06167B</string> + <string>3F56DF3C-E73E-4133-B4D0-6EA5926E61B3</string> + <string>E50E3BBE-8581-4EC4-8875-717CA123463E</string> + <string>4E3ABBC1-20D2-4D0F-BC10-A128F85AD5BE</string> + <string>BF26D328-E8B2-4255-AB7E-E139FD8161CE</string> + <string>087457F5-B8B2-4673-8E60-92430D951D4C</string> + <string>A79C2E63-7CBD-453A-AD1A-B4B15A554C6B</string> + <string>8FC0283E-CE94-450F-9560-9990FB253D95</string> + <string>3FA1DAF0-1259-41F5-B642-872D9FD60297</string> + <string>21ADF248-F14F-469F-956B-14251B78B83A</string> + <string>92CA447A-F1ED-4C5A-B999-DFE13C587B8C</string> + <string>4F173886-8EF8-422A-A368-8E2F1B3699C0</string> + <string>FA4CAE63-B259-4A38-943B-88F1444835DB</string> + <string>452C6FF5-FF58-4799-841F-786BB2386B5C</string> + <string>12C986E9-3511-4179-AA1A-204BF3AC0EBB</string> + <string>9C53FE15-1C26-41B5-8ADE-EA902A7FCD89</string> + <string>606B7B7B-236D-42DE-AF65-5C9CBE79EDF5</string> + <string>C9DDCAF9-7A94-40B8-A355-17CBFD9FB0CB</string> + <string>80797385-06D3-45A6-A034-8C5BE53A5419</string> + <string>B8181ACC-5FBB-4813-BCBD-42326F575D16</string> + <string>C1E197A3-22AB-4EA7-8D06-E53478B70CD6</string> + <string>6D8B302B-3980-4B6D-AB18-0642220A1D09</string> + <string>4B4BAF15-6DDF-4AEC-A949-C09DF23D3A0E</string> + <string>70B7E6F1-FB81-4741-87D7-6E2CDBEBE6CA</string> + <string>2A358D34-E286-48DB-8FE4-34957124FE4B</string> + <string>F99266AC-C47B-4662-8140-91FC9CD83CD1</string> + <string>1F895B4D-8226-4945-9AFB-7680E54A8AF6</string> + <string>0CABE9A1-3E50-4516-9EE2-2189D1D87724</string> + <string>6DBA82BD-A1CE-40CA-B200-23E82562ACB5</string> + <string>956A0059-FFF9-4B14-9072-9B66B8D85BC7</string> + <string>65E81A15-9D95-4CE8-B2D1-9952FEF5226F</string> + <string>37710819-E241-495B-8EED-4FDCD9BE6A22</string> + <string>229077E7-4284-4085-A449-3C5AA8DCF41B</string> + <string>710BC149-0A06-48FE-87A7-4CABA810A519</string> + <string>A8B0343F-CD2C-41E7-BFE5-133C9AE9675F</string> + <string>A67CBED1-95F6-4920-A8D7-E84E650520ED</string> + <string>56173E05-CA6A-4773-AB05-050A3BBF0F49</string> + <string>40D70647-3C75-4588-9CFC-3448A881F79E</string> + <string>67D98396-31F6-4821-BF31-F75F08A92850</string> + <string>7E41534A-A1FF-4214-A106-2B721FB1A920</string> + <string>B01C3BE2-956D-4E5A-9DE0-2FA6B544DA25</string> + <string>96F76523-E10D-4366-BFF0-918D22BA37E9</string> + <string>DCBE259C-2268-4194-A4FE-03E53A232FBD</string> + <string>F61A0D68-C33F-48F6-B045-B1B3C4EF9525</string> + <string>B3617124-733D-47EC-9B2A-FAD4C0397831</string> + <string>BD44D578-30A0-4ECF-A8E2-4A23C36BD8DE</string> + <string>8AF8F6D9-32FD-4AAB-8453-7A2FDE3FD382</string> + <string>4AEAA48E-D914-4EB4-B917-01D00D0C8E0B</string> + <string>1CF0F70D-B223-4B80-8454-4AEC0B5A10D2</string> + <string>7830F906-A21D-441D-BA1D-E37635247542</string> + <string>085B8E6C-388F-456F-882C-B8D3392D61FA</string> + <string>A75D991D-240C-43AA-B9A6-553AC44F76FA</string> + <string>53B9B5E7-D897-49E4-AEEC-DE94F781AA2B</string> + <string>6B126A42-3320-4978-8ADF-F53C600B5795</string> + <string>00DA1390-C91E-4583-B83B-CC16F8892239</string> + <string>EC7BC99A-B82D-43EC-AEF2-8EB54041CDE6</string> + <string>3B195EF9-CCC3-4B2D-91D3-15D514E5F4BF</string> + <string>6521B870-750F-4109-8BBF-2910D584C525</string> + <string>16F25A48-3166-4E7C-8F80-DC9E61C65645</string> + <string>018DC512-CE52-4DCC-B556-DA3A9AD96FE6</string> + <string>94993BC1-CB55-4F02-9705-70ABCED8CFC9</string> + <string>5622EC10-8A81-4C9F-87C3-E3B6A9B4D96B</string> + <string>498615E3-E82E-4CD3-A526-EBAE9F68C7EF</string> + <string>217C9FA9-BB27-403B-8CBD-659B64FA6CF4</string> + <string>102E8B00-3629-43A3-A2D4-864C6CF0CD32</string> + <string>4B01C66D-8A74-4433-A07D-8FE705C7A352</string> + <string>9924DCE9-8C1C-4CAE-B232-E9FD07E1B53E</string> + <string>9A1B4C8F-EC35-4F05-8AB0-8122EB4B9A93</string> + <string>01E0876B-4D91-49AF-937A-7EC39DDDEE79</string> + <string>774B14A7-EDC4-4855-9915-6AB8B15D2F68</string> + <string>D8D50F69-36E3-45DA-807E-29D1E5914DD8</string> + <string>1CFD7E53-FFF7-46A8-9149-49E9F5088E55</string> + <string>3E572472-BBF1-4DDA-AFCF-D52B95B0ADFB</string> + <string>EBCC36A0-38E4-438D-BB39-6D3AC690C8AF</string> + <string>4158361F-D366-4BAA-8CC5-DC46AD449229</string> + <string>EE1507E5-F01B-4D73-8EE6-CCFECE98C3F4</string> + <string>C280847F-1A0C-47CC-9EE5-168B9973A8BB</string> + <string>F54727CC-8F88-4D17-AC6A-B5E4C8AC872F</string> + <string>FA9F757A-290F-4E33-92FC-9E6214113E58</string> + <string>C772C456-6B38-4987-87CF-D10486D185A9</string> + <string>1A402F7D-1B17-4090-BFD6-42BD426FF0A6</string> + <string>A80FF473-4E66-4DBF-89E2-3BC1AFC00A0D</string> + <string>6A325FC2-6C57-4B2C-9326-3244EAC96A47</string> + <string>87D35E2A-FCC1-4496-9198-8BC85C16E97F</string> + <string>63538655-54A5-465E-9E8D-9F57ABA5E40D</string> + <string>BA7CE17D-DDC3-4394-808D-6D58588C329C</string> + <string>EF439919-653A-4250-B8B6-9337DA8DD851</string> + <string>0A58EA58-3BBC-4A07-80FF-366933CF24A7</string> + <string>B00CB7C5-C864-493C-9C6E-DCF759CE3B6A</string> + </array> + <key>name</key> - <string>ColdFusion functions</string> + <string>ColdFusion Functions</string> </dict> + <key>C8F9D7A6-D447-4C16-B566-BE46335B1067</key> <dict> <key>items</key> <array> + <string>97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14</string> + <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> + <string>862EDD04-D606-4EDB-8D01-425D8024CF1B</string> <string>0AF4E3E4-8638-4EAD-B182-A4FE571E9974</string> <string>38EB1CC2-4A1A-4C37-9D69-19D81129C5DC</string> <string>E0D7DCCA-9801-4DD5-9C26-3B607BEF7135</string> <string>241129A8-4AF3-4005-B276-6F431B5CB3F2</string> <string>8AE48664-E323-4DF9-BED2-CE700CAC7C15</string> <string>08392E18-5D55-41CB-BE64-7B091492E7BF</string> <string>9AEFE392-91BE-4968-8FF8-8A2C9D51D4CC</string> <string>67423190-2729-4C30-B10D-51B7DC3FAB85</string> <string>1B072993-0FFD-44B7-8C6D-3F9D60AF9E7B</string> <string>B8817D6A-B326-48F9-9E35-B28778A79412</string> <string>157C15A0-D535-4EAB-8173-6D6EB0906173</string> <string>0E400696-4C11-4072-9DAD-7BFF6F7789BE</string> <string>5A2941B5-2D73-4348-AB92-932665EB6E1D</string> <string>902C51B4-E4E3-4B2C-BA03-769FC6AC0867</string> <string>5CF87863-EBA1-49BE-AB51-016A2D0FDA80</string> <string>A72AC858-A593-4758-894F-266F9925990D</string> <string>6E59F119-65E3-4D1F-B393-121208A9A83F</string> <string>E336E487-B1EA-449C-9B32-4C5994136CEA</string> <string>90B1EE50-DAC5-4748-8415-5C3ABB38CFD5</string> <string>784AAEB3-2367-4275-95E0-DFDBE61E9423</string> <string>D5310F63-357F-4E8A-9583-26F569D309EB</string> <string>1ADF5606-9DC3-413F-8BC2-5E54E7BAC4FF</string> <string>28364618-9329-4501-98EC-852D28D2F59A</string> <string>EA2AA961-32E7-4B4B-85C8-0F458AC6E671</string> <string>A14677C7-FB24-4A35-B9F5-F764C2EFE00E</string> <string>5736162D-BDF6-4C94-8F3C-8F4CEB38E349</string> <string>C6C27604-1D24-4EC3-B40D-BD1FF6196DF8</string> <string>96D4FDBD-4A7D-42E4-BF7A-AB366E22758B</string> <string>E1BBA1F0-05C7-4EA0-87BA-FB0FC5D1CAED</string> <string>C8C2C389-AEE0-4CE2-8944-A7EEEFB9B680</string> <string>36F4B163-2ACD-48F1-8E72-365E54EB7811</string> <string>5D0E9DF4-6631-419C-AEEE-7710EE30502F</string> <string>0A3097F1-36A8-4009-8501-CC5B9349072E</string> <string>C28091B5-3245-4E3C-BC49-38AAB093D00F</string> <string>1D9BEE6E-907F-430A-BD62-2DF38A454B3E</string> <string>B8DC9CF1-AFF5-44E4-B9A8-42093D829889</string> <string>BEDB5CCC-7FF1-4C78-8169-2B58BFB2C449</string> <string>E6EE6F14-372D-469B-B31F-827A54CFC5E3</string> <string>DB5DE93A-DA9A-40E9-B469-EF8337A11CBE</string> <string>63B626CD-2818-42F2-BD90-DE112A8DEF7A</string> <string>5C3D7157-DFC0-4762-B059-C10F1A098089</string> <string>BD84E1FB-DCA2-493E-887E-1A1330DD6EA9</string> <string>CED5A340-3643-4F34-A8ED-A9FB99008300</string> <string>AB4A8782-7466-4B5D-A180-96E0BD19C050</string> <string>D01E4126-187A-4275-8583-DFA44FE3BB3C</string> <string>F9725187-DAE2-43BB-9209-BAF4F709AD72</string> <string>C83F3775-A62D-425B-B05E-C6A58C929399</string> <string>6674FAC2-9201-4D0D-BAA5-E35D64BDADDC</string> <string>53E1E9D3-8F53-4CFE-8ADD-83AC13969D24</string> <string>415DDDAF-1163-49E7-8D5B-3B6CD1A27A06</string> <string>B2FCBECB-D1E0-4BF4-B046-5A9C4A6475F9</string> <string>601BA2FE-EA4D-4B9C-A8EF-646A9E9626DD</string> <string>B14D6A84-2B4D-4FF8-99CB-E2B41B0E00BF</string> <string>29745C05-70EC-418A-A7E1-E60EE6042A95</string> <string>2FB6FDE3-F8F0-47A1-AE6D-AA3895A489CD</string> <string>0B69D306-8DF0-4494-87AC-B8E92091E0E6</string> <string>9AA75F85-02C0-4006-9D95-F7EC2728A050</string> <string>192D1402-A2E5-43F1-B0C5-990853DB5D98</string> <string>8BBB6187-A1D9-43AF-AF72-CDF3BB8B0A76</string> <string>DE1C603E-D791-469F-99D3-69E17B9B41EB</string> <string>FA01E47F-EB01-4FE1-9EB6-96FDEB923E70</string> <string>AA6262C5-CA32-415E-B666-D2FBF93E0905</string> <string>80B9754E-47ED-46D6-8BA5-80744B0FBE4B</string> <string>9A1343CB-5E9E-45A2-8D21-B4959C412B6E</string> <string>622A22FB-207B-4322-BC6C-C2B3D605AF00</string> <string>4DD466D2-0B15-4E06-8446-5AFBFC8B4128</string> <string>183709C1-9414-4A25-89FB-A0D9A7E59D27</string> <string>35060F61-EF40-4046-BF12-1AB2748884A1</string> <string>44EA1298-2450-498B-82F6-1BF1BC1FFE59</string> <string>29486C8D-7A9A-4EE0-B6A3-34C77A7D253E</string> <string>7F70512F-517F-4361-89ED-13E8C3BD98F0</string> <string>2A8760F9-6ED1-4066-B996-5E490B5A17EF</string> <string>9187A792-54F4-4773-A2D7-EB5D207D1A54</string> <string>F0AFF0A1-90FA-424F-A6AF-6EA6EC1BB225</string> <string>026FDCF1-E739-42E4-925D-59D80EE7FF05</string> <string>50182FB9-0179-4CF6-9AD7-4E7BC725C594</string> <string>3B19D8BC-5389-4263-A539-160170F7DFB1</string> <string>B096E910-EE96-4E63-BB46-EB12616C80F6</string> <string>08743309-6431-44D2-8A38-926516B04BEF</string> <string>A4876D40-55A7-44A0-9CDD-BCF62A621FC3</string> <string>5C441A88-2F12-4C54-83F8-81A62F735F88</string> <string>FDDBDC40-D1D9-4981-92DE-30CA475BC8FA</string> <string>3C93CAC9-0DC3-4371-8E5F-2727B0A282BD</string> <string>6F5A4D8F-DE7C-4663-9D39-7BF23D84769E</string> <string>75FFC09D-CB71-49CF-AB01-3DA8C44F29F3</string> <string>97DD90F8-5334-46A0-B973-C59F357D6C31</string> <string>3ED1297F-4C77-4187-9356-4262D3F28625</string> <string>F36E8F58-CDBD-4E42-A64F-9D05BE2D49B9</string> <string>1B6D6622-49BD-4EAB-B521-B3D1ACF2E4B1</string> <string>E09B46CF-DDE0-4B40-B7AF-93C005F23BAB</string> <string>A607B362-68CB-4AE3-BE72-575EB7CBA55A</string> <string>A57CC7BE-F39A-4B64-908D-44EA058C294F</string> <string>0C5234DB-A0F6-4BE2-AF28-5276ED3F81BB</string> <string>BC74CDF9-65E1-4FD0-A939-110CF53F3F67</string> <string>D6CFEC97-357A-4EBD-9D95-F89FECD4ED66</string> <string>293B3EF2-892E-4FF9-BB3B-82AE01FFA38D</string> <string>24AEB6C9-9CDE-478C-9C08-5CB1825321AE</string> <string>4417C4C8-F581-41FC-96FF-76A28A1F0640</string> <string>BC022681-5DE4-4E5C-8638-93EF655F7B0D</string> <string>47BD7B3C-4316-4C5B-AD7D-596D90D64A7C</string> <string>ED205418-D60B-41CE-9942-6855C78C65F6</string> <string>AEA7BB76-4231-41DC-829C-D093F7BF28E5</string> <string>F29A9DA7-B58E-4839-8664-2C99C5679384</string> <string>7423A717-6340-4CEC-9151-2B882D052CB9</string> <string>6E621AA5-5304-4DCE-82B9-820FDB78C5FE</string> <string>21B96169-6556-4436-B3B2-4556A6372567</string> <string>7A62D445-BDCF-4C67-8B71-35255FACC231</string> <string>9B25BE9A-A2E8-4BA6-A1CD-A545C6A3AEDE</string> <string>AD74D8BA-A774-4748-BF7E-22A6E94194ED</string> <string>8743E910-AD98-42C7-AC9D-4EBD26B54456</string> <string>5EB9976E-F76E-40FE-828F-22B393BA59AE</string> <string>8A82A0E0-7396-436B-A3FD-46680599A33A</string> <string>B36FA4B0-F6AE-4489-97D1-54BFE773A560</string> <string>281422A7-AF82-45BF-8707-4242A22FA908</string> <string>CD089D33-F3B3-4BC8-9650-B7CF29B877BF</string> <string>18A3925F-BF0F-4FAF-B45C-C02B2D4C4CB1</string> <string>7188A872-4A9F-4A05-ADCA-46D83E911D2D</string> <string>6322FE39-5B27-49EF-A632-A6073EDCE0C4</string> <string>BEC86CCF-C220-4B07-9ACD-320238D1FE48</string> <string>1F61F24F-166C-4D2E-98B0-7BA454B21619</string> <string>5BAF7E27-FEAB-43E0-899F-ABE9DA500FD0</string> <string>EE49E017-4812-4CAA-8CCC-29DAB3BE7B64</string> <string>97F31F3F-B885-4DE8-B784-5582990C21CD</string> <string>5D2DC339-C6E8-4919-9500-DD24DC9D2F73</string> <string>9E6E0847-D0DB-435D-A129-CA90BE6B9210</string> <string>82B42D60-DC77-47AA-B433-14969E2A2CEB</string> <string>DE1DB107-EC48-4128-B400-203B72AFD40F</string> <string>2051A0AE-51E2-413F-9CCB-92826FCD5C99</string> </array> <key>name</key> - <string>ColdFusion tags</string> + <string>ColdFusion Tags</string> </dict> </dict> </dict> + <key>name</key> <string>ColdFusion</string> + <key>ordering</key> <array> - <string>97CAD6F7-0807-4EB4-876E-DA9E9C1CEC14</string> - <string>904C79F1-5730-4D8D-986A-0D71587B2C1F</string> - <string>862EDD04-D606-4EDB-8D01-425D8024CF1B</string> - <string>0AF4E3E4-8638-4EAD-B182-A4FE571E9974</string> - <string>38EB1CC2-4A1A-4C37-9D69-19D81129C5DC</string> - <string>E0D7DCCA-9801-4DD5-9C26-3B607BEF7135</string> - <string>241129A8-4AF3-4005-B276-6F431B5CB3F2</string> - <string>8AE48664-E323-4DF9-BED2-CE700CAC7C15</string> - <string>08392E18-5D55-41CB-BE64-7B091492E7BF</string> - <string>9AEFE392-91BE-4968-8FF8-8A2C9D51D4CC</string> - <string>67423190-2729-4C30-B10D-51B7DC3FAB85</string> - <string>1B072993-0FFD-44B7-8C6D-3F9D60AF9E7B</string> - <string>B8817D6A-B326-48F9-9E35-B28778A79412</string> - <string>157C15A0-D535-4EAB-8173-6D6EB0906173</string> - <string>0E400696-4C11-4072-9DAD-7BFF6F7789BE</string> - <string>5A2941B5-2D73-4348-AB92-932665EB6E1D</string> - <string>902C51B4-E4E3-4B2C-BA03-769FC6AC0867</string> - <string>5CF87863-EBA1-49BE-AB51-016A2D0FDA80</string> - <string>A72AC858-A593-4758-894F-266F9925990D</string> - <string>6E59F119-65E3-4D1F-B393-121208A9A83F</string> - <string>E336E487-B1EA-449C-9B32-4C5994136CEA</string> - <string>90B1EE50-DAC5-4748-8415-5C3ABB38CFD5</string> - <string>784AAEB3-2367-4275-95E0-DFDBE61E9423</string> - <string>D5310F63-357F-4E8A-9583-26F569D309EB</string> - <string>1ADF5606-9DC3-413F-8BC2-5E54E7BAC4FF</string> - <string>28364618-9329-4501-98EC-852D28D2F59A</string> - <string>EA2AA961-32E7-4B4B-85C8-0F458AC6E671</string> - <string>A14677C7-FB24-4A35-B9F5-F764C2EFE00E</string> - <string>5736162D-BDF6-4C94-8F3C-8F4CEB38E349</string> - <string>C6C27604-1D24-4EC3-B40D-BD1FF6196DF8</string> - <string>96D4FDBD-4A7D-42E4-BF7A-AB366E22758B</string> - <string>E1BBA1F0-05C7-4EA0-87BA-FB0FC5D1CAED</string> - <string>C8C2C389-AEE0-4CE2-8944-A7EEEFB9B680</string> - <string>36F4B163-2ACD-48F1-8E72-365E54EB7811</string> - <string>5D0E9DF4-6631-419C-AEEE-7710EE30502F</string> - <string>0A3097F1-36A8-4009-8501-CC5B9349072E</string> - <string>C28091B5-3245-4E3C-BC49-38AAB093D00F</string> - <string>1D9BEE6E-907F-430A-BD62-2DF38A454B3E</string> - <string>B8DC9CF1-AFF5-44E4-B9A8-42093D829889</string> - <string>BEDB5CCC-7FF1-4C78-8169-2B58BFB2C449</string> - <string>E6EE6F14-372D-469B-B31F-827A54CFC5E3</string> - <string>DB5DE93A-DA9A-40E9-B469-EF8337A11CBE</string> - <string>63B626CD-2818-42F2-BD90-DE112A8DEF7A</string> - <string>5C3D7157-DFC0-4762-B059-C10F1A098089</string> - <string>BD84E1FB-DCA2-493E-887E-1A1330DD6EA9</string> - <string>CED5A340-3643-4F34-A8ED-A9FB99008300</string> - <string>AB4A8782-7466-4B5D-A180-96E0BD19C050</string> - <string>D01E4126-187A-4275-8583-DFA44FE3BB3C</string> - <string>F9725187-DAE2-43BB-9209-BAF4F709AD72</string> - <string>C83F3775-A62D-425B-B05E-C6A58C929399</string> - <string>6674FAC2-9201-4D0D-BAA5-E35D64BDADDC</string> - <string>53E1E9D3-8F53-4CFE-8ADD-83AC13969D24</string> - <string>415DDDAF-1163-49E7-8D5B-3B6CD1A27A06</string> - <string>B2FCBECB-D1E0-4BF4-B046-5A9C4A6475F9</string> - <string>601BA2FE-EA4D-4B9C-A8EF-646A9E9626DD</string> - <string>B14D6A84-2B4D-4FF8-99CB-E2B41B0E00BF</string> - <string>29745C05-70EC-418A-A7E1-E60EE6042A95</string> - <string>2FB6FDE3-F8F0-47A1-AE6D-AA3895A489CD</string> - <string>0B69D306-8DF0-4494-87AC-B8E92091E0E6</string> - <string>9AA75F85-02C0-4006-9D95-F7EC2728A050</string> - <string>192D1402-A2E5-43F1-B0C5-990853DB5D98</string> - <string>8BBB6187-A1D9-43AF-AF72-CDF3BB8B0A76</string> - <string>DE1C603E-D791-469F-99D3-69E17B9B41EB</string> - <string>FA01E47F-EB01-4FE1-9EB6-96FDEB923E70</string> - <string>AA6262C5-CA32-415E-B666-D2FBF93E0905</string> - <string>80B9754E-47ED-46D6-8BA5-80744B0FBE4B</string> - <string>9A1343CB-5E9E-45A2-8D21-B4959C412B6E</string> - <string>622A22FB-207B-4322-BC6C-C2B3D605AF00</string> - <string>59075941-A690-46FC-BFA6-58B81E1B18B0</string> - <string>4DD466D2-0B15-4E06-8446-5AFBFC8B4128</string> - <string>183709C1-9414-4A25-89FB-A0D9A7E59D27</string> - <string>35060F61-EF40-4046-BF12-1AB2748884A1</string> - <string>44EA1298-2450-498B-82F6-1BF1BC1FFE59</string> - <string>29486C8D-7A9A-4EE0-B6A3-34C77A7D253E</string> - <string>7F70512F-517F-4361-89ED-13E8C3BD98F0</string> - <string>2A8760F9-6ED1-4066-B996-5E490B5A17EF</string> - <string>9187A792-54F4-4773-A2D7-EB5D207D1A54</string> - <string>F0AFF0A1-90FA-424F-A6AF-6EA6EC1BB225</string> - <string>026FDCF1-E739-42E4-925D-59D80EE7FF05</string> - <string>50182FB9-0179-4CF6-9AD7-4E7BC725C594</string> - <string>3B19D8BC-5389-4263-A539-160170F7DFB1</string> - <string>B096E910-EE96-4E63-BB46-EB12616C80F6</string> - <string>08743309-6431-44D2-8A38-926516B04BEF</string> - <string>A4876D40-55A7-44A0-9CDD-BCF62A621FC3</string> - <string>5C441A88-2F12-4C54-83F8-81A62F735F88</string> - <string>FDDBDC40-D1D9-4981-92DE-30CA475BC8FA</string> - <string>3C93CAC9-0DC3-4371-8E5F-2727B0A282BD</string> - <string>6F5A4D8F-DE7C-4663-9D39-7BF23D84769E</string> - <string>75FFC09D-CB71-49CF-AB01-3DA8C44F29F3</string> - <string>97DD90F8-5334-46A0-B973-C59F357D6C31</string> - <string>3ED1297F-4C77-4187-9356-4262D3F28625</string> - <string>F36E8F58-CDBD-4E42-A64F-9D05BE2D49B9</string> - <string>1B6D6622-49BD-4EAB-B521-B3D1ACF2E4B1</string> - <string>E09B46CF-DDE0-4B40-B7AF-93C005F23BAB</string> - <string>A607B362-68CB-4AE3-BE72-575EB7CBA55A</string> - <string>A57CC7BE-F39A-4B64-908D-44EA058C294F</string> - <string>0C5234DB-A0F6-4BE2-AF28-5276ED3F81BB</string> - <string>BC74CDF9-65E1-4FD0-A939-110CF53F3F67</string> - <string>D6CFEC97-357A-4EBD-9D95-F89FECD4ED66</string> - <string>293B3EF2-892E-4FF9-BB3B-82AE01FFA38D</string> - <string>24AEB6C9-9CDE-478C-9C08-5CB1825321AE</string> - <string>4417C4C8-F581-41FC-96FF-76A28A1F0640</string> - <string>BC022681-5DE4-4E5C-8638-93EF655F7B0D</string> - <string>47BD7B3C-4316-4C5B-AD7D-596D90D64A7C</string> - <string>ED205418-D60B-41CE-9942-6855C78C65F6</string> - <string>AEA7BB76-4231-41DC-829C-D093F7BF28E5</string> - <string>F29A9DA7-B58E-4839-8664-2C99C5679384</string> - <string>7423A717-6340-4CEC-9151-2B882D052CB9</string> - <string>6E621AA5-5304-4DCE-82B9-820FDB78C5FE</string> - <string>21B96169-6556-4436-B3B2-4556A6372567</string> - <string>7A62D445-BDCF-4C67-8B71-35255FACC231</string> - <string>9B25BE9A-A2E8-4BA6-A1CD-A545C6A3AEDE</string> - <string>AD74D8BA-A774-4748-BF7E-22A6E94194ED</string> - <string>8743E910-AD98-42C7-AC9D-4EBD26B54456</string> - <string>5EB9976E-F76E-40FE-828F-22B393BA59AE</string> - <string>8A82A0E0-7396-436B-A3FD-46680599A33A</string> - <string>B36FA4B0-F6AE-4489-97D1-54BFE773A560</string> - <string>281422A7-AF82-45BF-8707-4242A22FA908</string> - <string>CD089D33-F3B3-4BC8-9650-B7CF29B877BF</string> - <string>18A3925F-BF0F-4FAF-B45C-C02B2D4C4CB1</string> - <string>7188A872-4A9F-4A05-ADCA-46D83E911D2D</string> - <string>6322FE39-5B27-49EF-A632-A6073EDCE0C4</string> - <string>BEC86CCF-C220-4B07-9ACD-320238D1FE48</string> - <string>1F61F24F-166C-4D2E-98B0-7BA454B21619</string> - <string>5BAF7E27-FEAB-43E0-899F-ABE9DA500FD0</string> - <string>EE49E017-4812-4CAA-8CCC-29DAB3BE7B64</string> - <string>97F31F3F-B885-4DE8-B784-5582990C21CD</string> - <string>5D2DC339-C6E8-4919-9500-DD24DC9D2F73</string> - <string>9E6E0847-D0DB-435D-A129-CA90BE6B9210</string> - <string>82B42D60-DC77-47AA-B433-14969E2A2CEB</string> - <string>DE1DB107-EC48-4128-B400-203B72AFD40F</string> - <string>2051A0AE-51E2-413F-9CCB-92826FCD5C99</string> - <string>0CA09D51-8DE8-48A0-A178-02D7D8285802</string> - <string>1519328F-1308-4DC8-9E71-2B7473F9080F</string> - <string>2DD711BA-8C2D-4AF4-85C2-C42733743D0A</string> - <string>5C998560-6284-4F59-A6F9-420962E130E2</string> - <string>5DBF4A9D-7C3E-4FAD-B6DE-16AB145F081B</string> - <string>C3F1BC8E-892F-4FB5-8A63-F8225B42CCFC</string> - <string>3B7767FB-E117-4543-B27C-C178D5F451DF</string> - <string>618D41F8-8A13-42B6-9000-551AA2DF9FA3</string> - <string>ACB55DF1-EE3F-4B20-A3CA-3DC63018212B</string> - <string>466D3581-0875-4E99-952A-0650CB84D33D</string> - <string>17CFEC94-0BF5-40CD-97DD-79A2CAECB041</string> - <string>5C46558A-599C-427F-8A7E-0343F1BED079</string> - <string>D2675FE6-79EF-40C6-A864-A5C6F092BA4C</string> - <string>D61CD41D-9838-4169-A754-424345AC4601</string> - <string>4C31384B-2B27-4C39-B2BB-CC2CA57B659A</string> - <string>02261555-8147-43DF-9D49-AEE4F58E1619</string> - <string>3757F0B8-F3B0-4272-9F6E-8968CE670387</string> - <string>3514ADDF-C60D-4A16-9346-11EB7A2AA61A</string> - <string>90E0EBD1-EC9F-425B-ACC3-06EFAB5F1F69</string> - <string>41ED9831-365B-4D4F-AF8D-2864343E271F</string> - <string>696A8BD3-EF4F-4A4C-A264-93BE6781D657</string> - <string>40051E46-ECE8-4A07-B600-934A3B482EFC</string> - <string>2016AF2A-1AC1-45A8-BCA0-A52F23142863</string> - <string>FD148128-FF2A-4CFE-99F6-FF43653FE8EA</string> - <string>6C79157D-36F9-4F91-B012-BDD27622FF9B</string> - <string>E45A3C54-88D7-4E4A-8092-56854FE825BE</string> - <string>49443738-7978-4865-A1AC-7358A0BEE2DE</string> - <string>C17555B3-A84A-404B-AECA-3F11CA9ABF0D</string> - <string>22ECD416-BC42-4C13-8BAF-F435A144A56E</string> - <string>E0363D86-A148-44D2-9AF9-45A2A57D1676</string> - <string>9992024A-E07D-4E29-9B35-F85038E890AF</string> - <string>23E6B8AA-CA8F-4CCC-BC29-76A027849595</string> - <string>28FE5A03-F962-4ECE-AF92-EE3436D20664</string> - <string>0D55F7C2-16A2-4B78-B390-EF780FF0F2EC</string> - <string>D9676E4C-3E0A-4886-8F2A-03E25DB4D44C</string> - <string>2C83D486-C0A5-4493-8562-BEA824BAD2D7</string> - <string>817F3C02-47AD-4553-9DE2-BDB0EC97BC9F</string> - <string>FEF3A4E6-7B4E-47B6-A529-ED41EDA41002</string> - <string>917BA410-EC71-492D-8472-A3C2CED279FA</string> - <string>6C78FA7D-0B84-4E9A-A063-77490073E99F</string> - <string>0F018E42-BB09-4631-B11E-EDDD267C8DFF</string> - <string>068FD2EE-B721-4DE3-A4E2-F98476C0530A</string> - <string>9A231D17-D36C-4081-B1EE-E3F5016040C1</string> - <string>E648C975-48FA-4818-89B6-34913675E41D</string> - <string>E7FD5C33-5516-4DB0-A553-B832515D17D4</string> - <string>F3102771-3AA4-492D-AD42-2FDB4F686662</string> - <string>C3AE011B-75E2-45AF-B427-864997717FE2</string> - <string>519D474D-FE82-4419-9D5F-AA88D817EDE6</string> - <string>6816281D-E43D-4DEC-AC2B-0E0756A00EEB</string> - <string>25ACCCC1-401C-4084-80DE-6CFFF6FDEA20</string> - <string>41E4F63F-C59D-4712-B29A-9CC83D717469</string> - <string>63CA1E9E-34AB-4EDD-B6CC-16C22EA5B777</string> - <string>2B8BC0E7-93C3-4DE2-957E-8212F6E373C3</string> - <string>19400E23-B260-4E85-AFFD-109708545A80</string> - <string>312DD333-8664-4C27-9C67-ED8B285579D4</string> - <string>9BDE4AC0-BEC2-4585-AEC7-AD60767AFBEE</string> - <string>9D47F8B3-B009-418B-8AB9-0E72D33F137D</string> - <string>79EDA618-F9E9-4A72-8A7F-DDC0D6826C19</string> - <string>0BA580D0-B978-48C0-8CEB-F78042E9F58F</string> - <string>AE303AF0-FAE2-4C2F-A5BF-0745D3161289</string> - <string>228F7B63-E8C8-48EF-9613-A32CAB3FF100</string> - <string>CB454D76-239A-40D2-B194-43CA6DDD9B8D</string> - <string>CBEAE712-0FC9-4210-B157-DC5C264BFCBF</string> - <string>8F41DFB0-285F-4FA7-A21D-210832BEBD60</string> - <string>81541C90-0980-47A1-9B9B-9F3E750016C7</string> - <string>E651A0E3-0EC3-45AC-B7D0-92E2DAD1F733</string> - <string>8D4E0C06-8D06-4871-9D92-5C72B18A5562</string> - <string>D455BE22-95B8-477F-BA2B-22C8C33D2C85</string> - <string>1262430C-CE62-4585-9EFC-7D5D001C5F24</string> - <string>5A00FE89-14AB-4DCA-B601-5FEA6C36F8F4</string> - <string>F82AABEA-89D3-4DE6-8B6C-3B7BDC194667</string> - <string>DEB3845A-FE19-4B41-84AD-EAA44A4BD1DB</string> - <string>3B74EAA8-B431-423C-971B-09349375FE3E</string> - <string>FA705D08-0DFD-4C3B-AB79-FF7719E9258D</string> - <string>C02F0BE6-CDE7-489F-8B1D-C63CD15AEEC6</string> - <string>2559432A-5071-4C85-B71B-A546326C4DE6</string> - <string>2358C3ED-39E9-4CB1-BBE0-C2C0419F4E9C</string> - <string>C91A69A3-2ECA-4F98-8777-E142F6777683</string> - <string>F78D0262-1B71-4AD6-8BB5-C2E9DC9BB083</string> - <string>8FC4AFD0-98E2-414D-8F80-ED36E5BD977A</string> - <string>80ECE03A-C2E3-4334-8F7B-2A2ED7BC80A7</string> - <string>0A20DB84-AAEF-4B95-A19F-18D6F3694798</string> - <string>31B2DCFD-1049-49CF-BCA8-FAE5D0D4917D</string> - <string>DDE93618-33D9-494A-93F0-1E0CAC672042</string> - <string>DD2F9E4A-E204-4CEF-ADCD-18B523A65966</string> - <string>44379253-BF02-4341-8BB2-B40CD39ED593</string> - <string>DF3F5402-8B88-40D3-81F4-B960A6174610</string> - <string>C22A5FC3-65EA-4234-85F2-2B43DFF811FF</string> - <string>041E3434-05CD-49B2-BFC3-4E3BE5643A65</string> - <string>829C9A8E-323D-44DA-BD6F-72AC150755A1</string> - <string>E55FC014-0F85-4A3E-884D-F7C4F3179659</string> - <string>C4D060C7-FF47-4799-AD06-108B3A757EB6</string> - <string>FB98EFB0-2C9C-4037-96CF-5C0644041281</string> - <string>8330E508-BE78-4713-BF73-2C8B08C02883</string> - <string>2452CEE2-65EC-4FF1-8E1E-C77876F1D14E</string> - <string>1B854256-5B23-4FCC-8367-2330D94D200E</string> - <string>BCF434DF-79AB-4F95-83E0-8D9B0163956B</string> - <string>F93D53FB-7669-4780-B53A-16276844A5BD</string> - <string>89150D95-04F4-4A3B-B885-20A9C95E3FBA</string> - <string>4F0429B6-0FB1-4CF6-BCB8-6350EBD89C35</string> - <string>998B082A-A679-4494-B66C-69AA8256E4D2</string> - <string>E03C0C8A-5CBA-4654-A4BD-EB6500901709</string> - <string>62B6DE6D-751C-4599-8094-6F3EA39F2517</string> - <string>ED3D3507-B8D9-4A83-88B7-CAD0F46A664A</string> - <string>958C7148-B01A-4FE8-AA42-88CADB026CBA</string> - <string>DEF118D7-4325-45E5-9AFC-77C80839A76F</string> - <string>AB98AFE4-E946-4CC6-B453-B6E478590152</string> - <string>3B4924D7-1FCB-4D61-85C8-63E69BFC808F</string> - <string>4640A976-0C9E-45AA-912F-AD2EEF351E60</string> - <string>5A3FFFCD-C7A2-457E-8D6E-151680293EBD</string> - <string>CA44FB3A-353F-418C-AC80-1DC89F4D65BF</string> - <string>0CC8642F-3BE7-45DA-86CB-179A4AE9C264</string> - <string>FD813CA3-8050-4E6A-815A-9F083D80A2F8</string> - <string>28CCC198-2A33-4677-8B8E-4774BF542C54</string> - <string>9038D5E1-01AC-41B8-BEB2-681702E589FF</string> - <string>8B3912D3-1C28-4DF2-8883-6C4B05377278</string> - <string>4C10EFDF-A3CE-48E3-8B9B-5174B0163EC2</string> - <string>24F07D3F-9B21-4035-A519-CF84DA5DB543</string> - <string>A0B83920-09E1-4361-8597-5B05BA1A23F9</string> - <string>5C8F03CB-AAD6-42F4-B20B-705D101354C7</string> - <string>C25BD8B9-99B8-429E-9499-BEA2C3C2F8C0</string> - <string>849C7A84-7E2B-4420-AE9D-FEFB11CA4A3F</string> - <string>67A5B7BD-0E56-477D-A38C-B101A2719988</string> - <string>56525EF4-4A5C-4415-B2D9-9D135CA32157</string> - <string>9C179D97-C855-420C-8689-642EB11AC767</string> - <string>F0FB9A33-FFB9-43D3-847D-AEF559D86B68</string> - <string>7B0D2A4C-CF10-4985-AEE3-212D3C479C38</string> - <string>ADA257DD-BB15-4CFD-BB53-55C7E1A30365</string> - <string>7F5D11B3-45DE-41E6-B5D1-71F370315500</string> - <string>92F58CD9-AE3E-4553-BA7B-B10FD1376B2F</string> - <string>259B5FFC-6CB8-4141-8270-CCEF88550A04</string> - <string>C953538A-5B40-4D20-B920-EE242B415A21</string> - <string>C6B47D42-9614-4C5A-A862-81A4E59EFC55</string> - <string>AAC6EB2B-2BE9-4CF5-995A-09C4632E5809</string> - <string>F8CE823F-8C57-4DAF-957A-C2370F49EB8D</string> - <string>DA3FB6A9-6C8A-47F1-932B-76E9AC9FF4A8</string> - <string>30468398-BDF8-4221-B8C1-108D660B5462</string> - <string>317DCAFC-B419-43D1-9516-CB020D48FE08</string> - <string>7FFE3035-50A2-43BC-9A6A-D3392DD711DA</string> - <string>67FC60DD-74BC-40D8-96F5-77E90D45E820</string> - <string>BE836A4A-003B-43B6-845D-E19A813D7E57</string> - <string>523CD084-3B13-46DB-AB6F-8961EC5914CB</string> - <string>5FA14C8D-B9CA-4635-B0ED-A9F6E8133716</string> - <string>DF07EEE5-5D1C-4226-921C-862390ED60D9</string> - <string>02288997-F2FE-4F78-86B5-7EB341820E31</string> - <string>09B68D0D-9DF3-4183-A57C-12352C1F992A</string> - <string>B040F5CB-43F8-442C-88D7-0C8B8FDB8989</string> - <string>BA93AEF3-2AF9-4987-820C-71788DE2DEF3</string> - <string>A28980B1-0C97-4C38-AC73-788170AE1D32</string> - <string>4A1ADF4A-5EDD-4D82-8141-B91E66BFD80D</string> - <string>6D88583E-821E-4921-AABD-997C5738F059</string> - <string>EC3B9C82-CD02-4EDE-B292-457CC8774E41</string> - <string>AE66DCD8-09E8-4EED-BAA6-031BACF237A0</string> - <string>A56B5F64-EF48-4000-B7D4-78B6C0E04CC1</string> - <string>11346CB0-A4DE-4DFF-BB31-E2D4DCDD14FC</string> - <string>206C70C1-010B-43F9-BC75-0CA766DB2DD3</string> - <string>B97E295E-62AD-4DD6-9E2D-625B016CC5AA</string> - <string>17180447-13E1-4330-A9DD-18D9DD6B8C2B</string> - <string>DAF8DD98-B342-4746-B017-EA3AA8861EE9</string> - <string>2FD9FC81-619B-4256-AFDB-4E1B4EB3B479</string> - <string>65714417-FFB2-441B-8A92-E660882D3A9B</string> - <string>CA71EDF5-8BDC-4CEF-A25B-91AD55BA9C07</string> - <string>A0DFAD24-FBA0-4867-841C-2DDA8B863454</string> - <string>E1F8DF31-6867-4D7B-96C1-842A860C3CF1</string> - <string>A8EEDB00-F4F2-4EC3-AB22-14A5E331D89C</string> - <string>C4BE4DC7-045B-470E-9BEE-6438C19D6D51</string> - <string>E411CA38-BF07-480C-AA82-864F2AF548B6</string> - <string>300C9DE5-E673-4A8F-B678-8A86E6AC24F6</string> - <string>31A1B000-84FE-4FC6-B941-B2080F6908E9</string> - <string>4554BD19-8A33-460E-BDC8-B2E4525D508F</string> - <string>48BF60D2-E9C1-4F1E-9FF8-BB08FC6F7A32</string> - <string>B09C244B-F8E0-4069-A4FF-5029DA586F72</string> - <string>6D3C12F2-DF3C-40F8-B47E-381FDD0A981A</string> - <string>60F3E813-2319-4310-9985-B7B50C0A9A33</string> - <string>32B99607-5DE8-4560-8079-2D84CD4E0001</string> - <string>F34A2296-6FF0-4090-ABAB-2C9D6F7EF482</string> - <string>14E4A176-FB73-41C7-BCF5-B11F90733CE9</string> - <string>D000FBCE-5C70-45C2-B9D2-86C42500568C</string> - <string>6DB8C1A2-09F5-4C4E-B4D8-A75F5E3D76FF</string> - <string>07A7E990-237A-43F9-A87E-8EA14DD81333</string> - <string>C245FB6E-95C2-4D6E-935F-A7F470328E49</string> - <string>0528B454-B8BC-466B-9AF9-BE68BC77E4E1</string> - <string>3D9D15C5-2E00-4332-9169-FC35542D1BEB</string> - <string>96265680-CFE2-404F-B614-B83B78AC1A0C</string> - <string>245A194E-803F-4951-BF63-19D639AA99FB</string> - <string>4B02989E-5D1A-497D-8FC1-561E4F2B67AB</string> - <string>9CA961D9-F34C-489F-865A-EB20A896C0F6</string> - <string>0FA5ADFC-C4D7-45D8-B745-2C0BC538179B</string> - <string>696428FC-070E-4D23-ACFD-0469CCC70079</string> - <string>2EDD4802-B07E-4CC2-9A88-B563FF05146E</string> - <string>286B13D0-E6C9-423C-B593-CD4B59A87E8F</string> - <string>041AC446-491D-4416-8E14-E60C8018A0D5</string> - <string>EB8C4DE1-8A2A-4C1B-AE5D-57D3FC8281CC</string> - <string>5BD2B7EB-5452-420D-BF49-B33C1D4E8706</string> - <string>268F708E-DBD4-4E38-9194-7063950783D7</string> - <string>DCAD363E-492B-49FD-B84F-43A3F77118CD</string> - <string>9072A654-06FA-42D6-950D-90E33975B2EB</string> - <string>3F07F52E-724D-4D8D-84E4-D4E87220B020</string> - <string>9DE5A98B-BEB2-4F3E-997C-4851CDAD76C5</string> - <string>FFADDBFF-B24E-4C06-8C4C-B28F6BD42349</string> - <string>538BB22C-E30C-45E4-92D1-F837360785AF</string> - <string>40BC17A0-BC89-4D08-A1C0-A54C85E90B46</string> - <string>509BDA8F-1AE1-4B62-9E5C-3742AE06167B</string> - <string>3F56DF3C-E73E-4133-B4D0-6EA5926E61B3</string> - <string>E50E3BBE-8581-4EC4-8875-717CA123463E</string> - <string>4E3ABBC1-20D2-4D0F-BC10-A128F85AD5BE</string> - <string>BF26D328-E8B2-4255-AB7E-E139FD8161CE</string> - <string>087457F5-B8B2-4673-8E60-92430D951D4C</string> - <string>A79C2E63-7CBD-453A-AD1A-B4B15A554C6B</string> - <string>8FC0283E-CE94-450F-9560-9990FB253D95</string> - <string>3FA1DAF0-1259-41F5-B642-872D9FD60297</string> - <string>21ADF248-F14F-469F-956B-14251B78B83A</string> - <string>92CA447A-F1ED-4C5A-B999-DFE13C587B8C</string> - <string>4F173886-8EF8-422A-A368-8E2F1B3699C0</string> - <string>FA4CAE63-B259-4A38-943B-88F1444835DB</string> - <string>452C6FF5-FF58-4799-841F-786BB2386B5C</string> - <string>12C986E9-3511-4179-AA1A-204BF3AC0EBB</string> - <string>9C53FE15-1C26-41B5-8ADE-EA902A7FCD89</string> - <string>606B7B7B-236D-42DE-AF65-5C9CBE79EDF5</string> - <string>C9DDCAF9-7A94-40B8-A355-17CBFD9FB0CB</string> - <string>80797385-06D3-45A6-A034-8C5BE53A5419</string> - <string>B8181ACC-5FBB-4813-BCBD-42326F575D16</string> - <string>C1E197A3-22AB-4EA7-8D06-E53478B70CD6</string> - <string>6D8B302B-3980-4B6D-AB18-0642220A1D09</string> - <string>4B4BAF15-6DDF-4AEC-A949-C09DF23D3A0E</string> - <string>70B7E6F1-FB81-4741-87D7-6E2CDBEBE6CA</string> - <string>2A358D34-E286-48DB-8FE4-34957124FE4B</string> - <string>F99266AC-C47B-4662-8140-91FC9CD83CD1</string> - <string>1F895B4D-8226-4945-9AFB-7680E54A8AF6</string> - <string>0CABE9A1-3E50-4516-9EE2-2189D1D87724</string> - <string>6DBA82BD-A1CE-40CA-B200-23E82562ACB5</string> - <string>956A0059-FFF9-4B14-9072-9B66B8D85BC7</string> - <string>65E81A15-9D95-4CE8-B2D1-9952FEF5226F</string> - <string>37710819-E241-495B-8EED-4FDCD9BE6A22</string> - <string>229077E7-4284-4085-A449-3C5AA8DCF41B</string> - <string>710BC149-0A06-48FE-87A7-4CABA810A519</string> - <string>A8B0343F-CD2C-41E7-BFE5-133C9AE9675F</string> - <string>A67CBED1-95F6-4920-A8D7-E84E650520ED</string> - <string>56173E05-CA6A-4773-AB05-050A3BBF0F49</string> - <string>40D70647-3C75-4588-9CFC-3448A881F79E</string> - <string>67D98396-31F6-4821-BF31-F75F08A92850</string> - <string>7E41534A-A1FF-4214-A106-2B721FB1A920</string> - <string>B01C3BE2-956D-4E5A-9DE0-2FA6B544DA25</string> - <string>96F76523-E10D-4366-BFF0-918D22BA37E9</string> - <string>DCBE259C-2268-4194-A4FE-03E53A232FBD</string> - <string>F61A0D68-C33F-48F6-B045-B1B3C4EF9525</string> - <string>B3617124-733D-47EC-9B2A-FAD4C0397831</string> - <string>BD44D578-30A0-4ECF-A8E2-4A23C36BD8DE</string> - <string>8AF8F6D9-32FD-4AAB-8453-7A2FDE3FD382</string> - <string>4AEAA48E-D914-4EB4-B917-01D00D0C8E0B</string> - <string>1CF0F70D-B223-4B80-8454-4AEC0B5A10D2</string> - <string>7830F906-A21D-441D-BA1D-E37635247542</string> - <string>085B8E6C-388F-456F-882C-B8D3392D61FA</string> - <string>A75D991D-240C-43AA-B9A6-553AC44F76FA</string> - <string>53B9B5E7-D897-49E4-AEEC-DE94F781AA2B</string> - <string>6B126A42-3320-4978-8ADF-F53C600B5795</string> - <string>00DA1390-C91E-4583-B83B-CC16F8892239</string> - <string>EC7BC99A-B82D-43EC-AEF2-8EB54041CDE6</string> - <string>3B195EF9-CCC3-4B2D-91D3-15D514E5F4BF</string> - <string>6521B870-750F-4109-8BBF-2910D584C525</string> - <string>16F25A48-3166-4E7C-8F80-DC9E61C65645</string> - <string>018DC512-CE52-4DCC-B556-DA3A9AD96FE6</string> - <string>94993BC1-CB55-4F02-9705-70ABCED8CFC9</string> - <string>5622EC10-8A81-4C9F-87C3-E3B6A9B4D96B</string> - <string>498615E3-E82E-4CD3-A526-EBAE9F68C7EF</string> - <string>217C9FA9-BB27-403B-8CBD-659B64FA6CF4</string> - <string>102E8B00-3629-43A3-A2D4-864C6CF0CD32</string> - <string>4B01C66D-8A74-4433-A07D-8FE705C7A352</string> - <string>9924DCE9-8C1C-4CAE-B232-E9FD07E1B53E</string> - <string>9A1B4C8F-EC35-4F05-8AB0-8122EB4B9A93</string> - <string>01E0876B-4D91-49AF-937A-7EC39DDDEE79</string> - <string>774B14A7-EDC4-4855-9915-6AB8B15D2F68</string> - <string>D8D50F69-36E3-45DA-807E-29D1E5914DD8</string> - <string>1CFD7E53-FFF7-46A8-9149-49E9F5088E55</string> - <string>3E572472-BBF1-4DDA-AFCF-D52B95B0ADFB</string> - <string>EBCC36A0-38E4-438D-BB39-6D3AC690C8AF</string> - <string>4158361F-D366-4BAA-8CC5-DC46AD449229</string> - <string>EE1507E5-F01B-4D73-8EE6-CCFECE98C3F4</string> - <string>C280847F-1A0C-47CC-9EE5-168B9973A8BB</string> - <string>F54727CC-8F88-4D17-AC6A-B5E4C8AC872F</string> - <string>FA9F757A-290F-4E33-92FC-9E6214113E58</string> - <string>C772C456-6B38-4987-87CF-D10486D185A9</string> - <string>1A402F7D-1B17-4090-BFD6-42BD426FF0A6</string> - <string>A80FF473-4E66-4DBF-89E2-3BC1AFC00A0D</string> - <string>6A325FC2-6C57-4B2C-9326-3244EAC96A47</string> - <string>87D35E2A-FCC1-4496-9198-8BC85C16E97F</string> - <string>63538655-54A5-465E-9E8D-9F57ABA5E40D</string> - <string>BA7CE17D-DDC3-4394-808D-6D58588C329C</string> - <string>EF439919-653A-4250-B8B6-9337DA8DD851</string> - <string>0A58EA58-3BBC-4A07-80FF-366933CF24A7</string> - <string>B00CB7C5-C864-493C-9C6E-DCF759CE3B6A</string> </array> + <key>uuid</key> <string>1A09BE0B-E81A-4CB7-AF69-AFC845162D1F</string> </dict> </plist>
onyxfish/nostaples
40c97f3518edfbe7c305c2588d56210c98dad11b
Added proper support for Gnome's Default Toolbar style.
diff --git a/constants.py b/constants.py index b3e596c..257d4b0 100644 --- a/constants.py +++ b/constants.py @@ -1,212 +1,220 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. ''' This module contains global configuration constants that are not likely to change often as well as enumeration-like state constants. ''' import os import gtk import Image from reportlab.lib.pagesizes import A0, A1, A2, A3, A4, A5, A6, \ B0, B1, B2, B3, B4, B5, B6, LETTER, LEGAL, ELEVENSEVENTEEN VERSION = (0, 4, 0) PAGESIZES_INCHES = {'A0' : (33.1, 46.8), 'A1' : (23.4, 33.1), 'A2' : (16.5, 23.4), 'A3' : (11.7, 16.5), 'A4' : (8.3, 11.7), 'A5' : (5.8, 8.3), 'A6' : (4.1, 5.8), 'A7' : (2.9, 4.1), 'A8' : (2.0, 2.9), 'A9' : (1.5, 2.0), 'A10' : (1.0, 1.5), 'B0' : (39.4, 55.7), 'B1' : (27.8, 39.4), 'B2' : (19.7, 27.8), 'B3' : (13.9, 19.7), 'B4' : (9.8, 13.9), 'B5' : (6.9, 9.8), 'B6' : (4.9, 6.9), 'B7' : (3.5, 4.9), 'B8' : (2.4, 3.5), 'B9' : (1.7, 2.4), 'B10' : (1.2, 1.7), 'Letter' : (8.5, 11.0), 'Legal' : (8.5, 14.0), 'Junior Legal' : (8.0, 5.0), 'Ledger' : (17.0, 11.0), 'Tabloid' : (11.0, 17.0), '3x5 Photo' : (3.0, 5.0), '4x6 Photo' : (4.0, 6.0), '5x7 Photo' : (5.0, 7.0), '8x10 Photo' : (8.0, 10.0), '11x14 Photo' : (11.0, 14.0)} PAGESIZES_MM = {'A0' : (841.0, 1189.0), 'A1' : (594.0, 841.0), 'A2' : (420.0, 594.0), 'A3' : (297.0, 420.0), 'A4' : (210.0, 297.0), 'A5' : (148.0, 210.0), 'A6' : (105.0, 148.0), 'A7' : (74.0, 105.0), 'A8' : (52.0, 74.0), 'A9' : (37.0, 52.0), 'A10' : (26.0, 37.0), 'B0' : (1000.0, 1414.0), 'B1' : (707.0, 1000.0), 'B2' : (500.0, 707.0), 'B3' : (353.0, 500.0), 'B4' : (250.0, 353.0), 'B5' : (176.0, 250.0), 'B6' : (125.0, 176.0), 'B7' : (88.0, 125.0), 'B8' : (62.0, 88.0), 'B9' : (44.0, 62.0), 'B10' : (31.0, 44.0), 'Letter' : (216.0, 279.0), 'Legal' : (216.0, 356.0), 'Junior Legal' : (203.2, 127.0), 'Ledger' : (432.0, 279.0), 'Tabloid' : (279.0, 43.0), '3x5 Photo' : (76.0, 127.0), '4x6 Photo' : (102.0, 152.0), '5x7 Photo' : (127.0, 178.0), '8x10 Photo' : (203.0, 254.0), '11x14 Photo' : (279.0, 356.0)} PAGESIZE_SORT_ORDER = ['A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'A10', 'B0', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9', 'B10', 'Letter', 'Legal', 'Junior Legal', 'Ledger', 'Tabloid', '3x5 Photo', '4x6 Photo', '5x7 Photo', '8x10 Photo', '11x14 Photo'] DEFAULT_SHOW_TOOLBAR = True DEFAULT_SHOW_STATUSBAR = True DEFAULT_SHOW_THUMBNAILS = True DEFAULT_SHOW_ADJUSTMENTS = False DEFAULT_ROTATE_ALL_PAGES = False DEFAULT_ACTIVE_SCANNER = '' DEFAULT_SCAN_MODE = 'Color' DEFAULT_SCAN_RESOLUTION = '75' DEFAULT_PAGE_SIZE = 'A4' DEFAULT_SAVE_PATH = '' DEFAULT_AUTHOR = os.getenv('LOGNAME') DEFAULT_SAVED_KEYWORDS = [] DEFAULT_PREVIEW_MODE = 'Bilinear (Default)' DEFAULT_THUMBNAIL_SIZE = 128 DEFAULT_SHOW_DOCUMENT_METADATA = True DEFAULT_BLACKLISTED_SCANNERS = [] DEFAULT_TOOLBAR_STYLE = 'System Default' THUMBNAILS_SCALING_MODE = Image.ANTIALIAS PREVIEW_ZOOM_MAX = 5.0 PREVIEW_ZOOM_MIN = 1.0 PREVIEW_ZOOM_STEP = 0.5 MAX_VALID_OPTION_VALUES = 11 SCAN_CANCELLED = -1 SCAN_FAILURE = 0 SCAN_SUCCESS = 1 RESPONSE_BLACKLIST_DEVICE = 1 GCONF_DIRECTORY = '/apps/nostaples' GCONF_TUPLE_SEPARATOR = '|' GCONF_LIST_SEPARATOR = '^' # TODO: rename to CONFIG_DIRECTORY APP_DIRECTORY = os.path.expanduser('~/.nostaples') LOGGING_CONFIG = os.path.join(os.path.dirname(__file__), 'logging.config') GUI_DIRECTORY = os.path.join(os.path.dirname(__file__), 'gui') PREVIEW_MODES = \ { 'Nearest (Fastest)': gtk.gdk.INTERP_NEAREST, 'Tiles': gtk.gdk.INTERP_TILES, 'Bilinear (Default)': gtk.gdk.INTERP_BILINEAR, 'Antialias (Smoothest)': gtk.gdk.INTERP_HYPER } PREVIEW_MODES_LIST = \ [ 'Nearest (Fastest)', 'Tiles', 'Bilinear (Default)', 'Antialias (Smoothest)' ] THUMBNAIL_SIZE_LIST = \ [ 32, 64, 128, 256 ] + +SYSTEM_TOOLBAR_STYLES = \ +{ + 'both': 'Icons and Text (Stacked)', + 'both-horiz': 'Icons and Text (Side by side)', + 'icons': 'Icons Only', + 'text': 'Text Only' +} TOOLBAR_STYLES = \ { 'System Default': None, 'Icons Only': gtk.TOOLBAR_ICONS, 'Text Only': gtk.TOOLBAR_TEXT, 'Icons and Text (Stacked)': gtk.TOOLBAR_BOTH, 'Icons and Text (Side by side)': gtk.TOOLBAR_BOTH_HORIZ } TOOLBAR_STYLES_LIST = \ [ 'System Default', 'Icons Only', 'Text Only', 'Icons and Text (Stacked)', 'Icons and Text (Side by side)' ] \ No newline at end of file diff --git a/controllers/main.py b/controllers/main.py index 0b996d1..709d37e 100644 --- a/controllers/main.py +++ b/controllers/main.py @@ -16,792 +16,792 @@ #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{MainController}, which manages interaction between the L{MainModel} and L{MainView}. """ import commands import logging import os import re import threading import gobject import gtk from gtkmvc.controller import Controller from nostaples.models.page import PageModel import nostaples.sane as saneme from nostaples.utils.scanning import * class MainController(Controller): """ Manages interaction between the L{MainModel} and L{MainView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the MainController, as well as necessary sub-controllers and services. """ self.application = application Controller.__init__(self, application.get_main_model()) application.get_document_model().register_observer(self) application.get_preferences_model().register_observer(self) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ self.adapt('show_toolbar', 'show_toolbar_menu_item') self.adapt('show_statusbar', 'show_statusbar_menu_item') self.adapt('show_thumbnails', 'show_thumbnails_menu_item') self.adapt('show_adjustments', 'show_adjustments_menu_item') self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS # Menu Items def on_scan_window_destroy(self, window): """Exits the application.""" self.quit() def on_scan_menu_item_activate(self, menu_item): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_menu_item_activate(self, menu_item): """Refresh the list of connected scanners from SANE.""" self._update_available_scanners() def on_save_as_menu_item_activate(self, menu_item): """Saves the current document to a file.""" self.application.show_save_dialog() def on_delete_menu_item_activate(self, menu_item): self.application.get_document_controller().delete_selected() def on_preferences_menu_item_activate(self, menu_item): """Creates and displays a preferences dialog.""" self.application.show_preferences_dialog() def on_quit_menu_item_activate(self, menu_item): """Exits the application.""" self.quit() def on_zoom_in_menu_item_activate(self, menu_item): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_menu_item_activate(self, menu_item): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_menu_item_activate(self, menu_item): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_menu_item_activate(self, menu_item): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_available_scanner_menu_item_toggled(self, menu_item): """ Set the active scanner. """ main_model = self.application.get_main_model() if menu_item.get_active(): for scanner in main_model.available_scanners: if scanner.display_name == menu_item.get_children()[0].get_text(): main_model.active_scanner = scanner return def on_valid_mode_menu_item_toggled(self, menu_item): """Sets the active scan mode.""" if menu_item.get_active(): self.application.get_main_model().active_mode = \ menu_item.get_children()[0].get_text() def on_valid_resolution_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_resolution = \ menu_item.get_children()[0].get_text() def on_valid_page_size_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_page_size = \ menu_item.get_children()[0].get_text() def on_go_first_menu_item_activate(self, menu_item): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_menu_item_activate(self, menu_item): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_menu_item_activate(self, menu_item): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_menu_item_activate(self, menu_item): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() def on_contents_menu_item_clicked(self, menu_item): """ TICKET #8 """ pass def on_about_menu_item_activate(self, menu_item): """Show the about dialog.""" self.application.show_about_dialog() # Toolbar Buttons def on_scan_button_clicked(self, button): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_button_clicked(self, button): self._update_available_scanners() def on_save_as_button_clicked(self, button): """Saves the current document to a file.""" self.application.show_save_dialog() def on_zoom_in_button_clicked(self, button): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_button_clicked(self, button): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_button_clicked(self, button): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_button_clicked(self, button): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_go_first_button_clicked(self, button): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_button_clicked(self, button): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_button_clicked(self, button): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_button_clicked(self, button): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() # Progress Window INTERFACE CALLBACKS def on_progress_window_delete_event(self, window, event): """ Emulate clicking of the cancel/close button and then hide the window. """ main_view = self.application.get_main_view() self.on_scan_cancel_button_clicked(None) main_view['progress_window'].hide() return True def on_scan_cancel_button_clicked(self, button): """ Cancel the current scan or, if the scan is finished, close the progress window. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress: assert self.cancel_event self.cancel_event.set() else: main_view['progress_window'].hide() def on_scan_again_button_clicked(self, button): """Initiate a new scan from the progress window.""" self._scan() def on_quick_save_button_clicked(self, button): """ Show the save dialog. If the user completes a save then disable the quick save button until another page is scanned. """ main_view = self.application.get_main_view() document_model = self.application.get_document_model() self.application.show_save_dialog() if document_model.count == 0: main_view['quick_save_button'].set_sensitive(False) # MainModel PROPERTY CALLBACKS def property_show_toolbar_value_change(self, model, old_value, new_value): """Update the visibility of the toolbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_toolbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['main_toolbar'].show() else: main_view['main_toolbar'].hide() def property_show_statusbar_value_change(self, model, old_value, new_value): """Update the visibility of the statusbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_statusbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['status_view_docking_viewport'].show() else: main_view['status_view_docking_viewport'].hide() def property_show_thumbnails_value_change(self, model, old_value, new_value): """Update the visibility of the thumbnails.""" main_view = self.application.get_main_view() menu_item = main_view['show_thumbnails_menu_item'] menu_item.set_active(new_value) self.application.get_document_controller().toggle_thumbnails_visible(new_value) def property_show_adjustments_value_change(self, model, old_value, new_value): """Update the visibility of the adjustments controls.""" document_controller = self.application.get_document_controller() main_view = self.application.get_main_view() menu_item = main_view['show_adjustments_menu_item'] menu_item.set_active(new_value) document_controller.toggle_adjustments_visible(new_value) def property_active_scanner_value_change(self, model, old_value, new_value): """ Update the menu and valid scanner options to match the new device. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() if new_value == None: return for menu_item in main_view['scanner_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value.display_name: menu_item.set_active(True) break def property_active_mode_value_change(self, model, old_value, new_value): """Select the active mode from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_mode_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_resolution_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_resolution_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_page_size_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_page_size_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_available_scanners_value_change(self, model, old_value, new_value): """ Update the menu of available scanners. """ main_view = self.application.get_main_view() self._clear_available_scanners_sub_menu() # Generate the new menu if len(new_value) == 0: menu_item = gtk.MenuItem('No Scanners Connected') menu_item.set_sensitive(False) main_view['scanner_sub_menu'].append(menu_item) else: first_item = None for i in range(len(new_value)): # The first menu item defines the group if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i].display_name) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i].display_name) main_view['scanner_sub_menu'].append(menu_item) main_view['scanner_sub_menu'].show_all() def property_valid_modes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan modes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_modes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Modes") menu_item.set_sensitive(False) main_view['scan_mode_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled) main_view['scan_mode_sub_menu'].append(menu_item) main_view['scan_mode_sub_menu'].show_all() def property_valid_resolutions_value_change(self, model, old_value, new_value): """ Updates the list of valid scan resolutions for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_resolutions_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Resolutions") menu_item.set_sensitive(False) main_view['scan_resolution_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled) main_view['scan_resolution_sub_menu'].append(menu_item) main_view['scan_resolution_sub_menu'].show_all() def property_valid_page_sizes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan page sizes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_page_sizes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Page Sizes") menu_item.set_sensitive(False) main_view['scan_page_size_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_page_size_menu_item_toggled) main_view['scan_page_size_sub_menu'].append(menu_item) main_view['scan_page_size_sub_menu'].show_all() def property_scan_in_progress_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() def property_updating_available_scanners_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() # DocumentModel PROPERTY CALLBACKS def property_count_value_change(self, model, old_value, new_value): """Toggle available controls.""" self._toggle_document_controls() # PreferencesModel PROPERTY CALLBACKS def property_toolbar_style_value_change(self, model, old_value, new_value): """Toggle available controls.""" main_view = self.application.get_main_view() if new_value == 'System Default': - # TICKET #35 pass else: - main_view['main_toolbar'].set_style(constants.TOOLBAR_STYLES[new_value]) + main_view['main_toolbar'].set_style( + constants.TOOLBAR_STYLES[new_value]) # THREAD CALLBACKS def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned): main_view = self.application.get_main_view() short_bytes_scanned = float(bytes_scanned) / 1000 short_total_bytes = float(scan_info.total_bytes) / 1000 main_view['scan_progressbar'].set_fraction( float(bytes_scanned) / scan_info.total_bytes) main_view['scan_progressbar'].set_text( 'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes)) main_view['progress_secondary_label'].set_markup( '<i>Scanning page.</i>') def on_scan_succeeded(self, scanning_thread, pil_image): """ Update the progress window and append the new page to the current document. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['scan_progressbar'].set_fraction(1) main_view['scan_progressbar'].set_text('Scan complete') main_view['progress_secondary_label'].set_markup( '<i>Adding page to document.</i>') gtk.gdk.flush() new_page = PageModel( self.application, pil_image, int(main_model.active_resolution), main_model.active_page_size) self.application.get_document_model().append(new_page) main_view['progress_secondary_label'].set_markup( '<i>Page added.</i>') main_view['scan_again_button'].set_sensitive(True) main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_failed(self, scanning_thread, reason): """ Update the progress window. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['progress_secondary_label'].set_markup( '<i>%s</i>' % reason) main_view['scan_again_button'].set_sensitive(True) if self.application.get_document_model().count > 0: main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_aborted(self, scanning_thread, exc_info): """ Change display to indicate that scanning failed and convey the to the user the reason why the thread aborted. If the failure was from a SANE exception then give the user the option to blacklist the device. If not, then reraise the error and let the sys.excepthook deal with it. """ self.on_scan_failed(scanning_thread, 'An error occurred.') if isinstance(exc_info[1], saneme.SaneError): self.run_device_exception_dialog(exc_info) else: raise exc_info[0], exc_info[1], exc_info[2] def on_update_available_scanners_thread_finished(self, update_thread, scanner_list): """Set the new list of available scanners.""" main_model = self.application.get_main_model() main_model.available_scanners = scanner_list main_model.updating_available_scanners = False def on_update_available_scanners_thread_aborted(self, update_thread, exc_info): """ Change the display to indicate that no scanners are available and reraise the exception so that it can be caught by the sys.excepthook. There is no reason to handle these cases with a special dialog, if the application failed to even enumerate the available devices then no other action will be possible. This should be fantastically rare. """ self.on_update_available_scanners_thread_finished(update_thread, []) raise exc_info[0], exc_info[1], exc_info[2] # PUBLIC METHODS def quit(self): """Exits the application.""" self.log.debug('Quit.') gtk.main_quit() def run_device_exception_dialog(self, exc_info): """ Display an error dialog that provides the user with the option of blacklisting the device which caused the error. TODO: Move into MainView. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() preferences_model = self.application.get_preferences_model() response = main_view.run_device_exception_dialog(exc_info) if response == constants.RESPONSE_BLACKLIST_DEVICE: temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(exc_info[1].device.display_name) temp_blacklist.sort() preferences_model.blacklisted_scanners = temp_blacklist # PRIVATE METHODS def _clear_available_scanners_sub_menu(self): """Clear the menu of available scanners.""" main_view = self.application.get_main_view() for child in main_view['scanner_sub_menu'].get_children(): main_view['scanner_sub_menu'].remove(child) def _clear_scan_modes_sub_menu(self): """Clear the menu of valid scan modes.""" main_view = self.application.get_main_view() for child in main_view['scan_mode_sub_menu'].get_children(): main_view['scan_mode_sub_menu'].remove(child) def _clear_scan_resolutions_sub_menu(self): """Clear the menu of valid scan resolutions.""" main_view = self.application.get_main_view() for child in main_view['scan_resolution_sub_menu'].get_children(): main_view['scan_resolution_sub_menu'].remove(child) def _clear_scan_page_sizes_sub_menu(self): """Clear the menu of valid scan page sizes.""" main_view = self.application.get_main_view() for child in main_view['scan_page_size_sub_menu'].get_children(): main_view['scan_page_size_sub_menu'].remove(child) def _toggle_scan_controls(self): """Toggle whether or not the scan controls or accessible.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_scan_controls_sensitive(False) main_view.set_refresh_scanner_controls_sensitive(False) else: if main_model.active_scanner != None: main_view.set_scan_controls_sensitive(True) main_view.set_refresh_scanner_controls_sensitive(True) def _toggle_document_controls(self): """ Toggle available document controls based on the current scanner status and the number of scanned pages. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() # Disable all controls when the scanner is in use if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: count = self.application.get_document_model().count # Disable all controls if no pages are scanned if count == 0: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: # Enable most controls if any pages scanned main_view.set_file_controls_sensitive(True) main_view.set_delete_controls_sensitive(True) main_view.set_zoom_controls_sensitive(True) main_view.set_adjustment_controls_sensitive(True) # Only enable navigation if more than one page scanned if count > 1: main_view.set_navigation_controls_sensitive(True) else: main_view.set_navigation_controls_sensitive(False) def _update_status(self): """ Update the text of the statusbar based on the current state of the application. """ main_model = self.application.get_main_model() status_controller = self.application.get_status_controller() status_controller.pop(self.status_context) if main_model.scan_in_progress: status_controller.push(self.status_context, 'Scanning...') elif main_model.updating_available_scanners: status_controller.push(self.status_context, 'Querying hardware...') else: if main_model.active_scanner: status_controller.push(self.status_context, 'Ready with %s.' % main_model.active_scanner.display_name) else: status_controller.push(self.status_context, 'No scanner available.') def _scan(self): """Begin a scan.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() main_model.scan_in_progress = True scanning_thread = ScanningThread(main_model.active_scanner) scanning_thread.connect("progress", self.on_scan_progress) scanning_thread.connect("succeeded", self.on_scan_succeeded) scanning_thread.connect("failed", self.on_scan_failed) scanning_thread.connect("aborted", self.on_scan_aborted) self.cancel_event = scanning_thread.cancel_event main_view['progress_primary_label'].set_markup( '<big><b>%s</b></big>' % main_model.active_scanner.display_name) main_view['scan_progressbar'].set_fraction(0) main_view['scan_progressbar'].set_text('Waiting for data') main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>') mode = main_model.active_mode if main_model.active_mode else 'Not set' main_view['progress_mode_label'].set_markup(mode) dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set' main_view['progress_resolution_label'].set_markup(dpi) page_size = '%s' % main_model.active_page_size if main_model.active_page_size else 'Not set' main_view['progress_page_size_label'].set_markup(page_size) main_view['scan_again_button'].set_sensitive(False) main_view['quick_save_button'].set_sensitive(False) main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL) main_view['progress_window'].show_all() scanning_thread.start() def _update_available_scanners(self): """ Start a new update thread to query for available scanners. """ sane = self.application.get_sane() main_model = self.application.get_main_model() main_model.updating_available_scanners = True update_thread = UpdateAvailableScannersThread(sane) update_thread.connect("finished", self.on_update_available_scanners_thread_finished) update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted) update_thread.start() \ No newline at end of file diff --git a/controllers/preferences.py b/controllers/preferences.py index d89d7b1..f355705 100644 --- a/controllers/preferences.py +++ b/controllers/preferences.py @@ -1,290 +1,335 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{PreferencesController}, which manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ import logging +import gconf import gtk from gtkmvc.controller import Controller from nostaples import constants from nostaples.utils.gui import read_combobox, write_combobox class PreferencesController(Controller): """ Manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the PreferencesController. """ self.application = application Controller.__init__(self, application.get_preferences_model()) application.get_main_model().register_observer(self) + # Setup GConf observer for system-wide toolbar settings + self.gconf_client = gconf.client_get_default() + self.gconf_client.add_dir( + '/desktop/gnome/interface', gconf.CLIENT_PRELOAD_NONE) + self.gconf_client.notify_add( + '/desktop/gnome/interface/toolbar_style', + self.on_default_toolbar_style_changed) + self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ pass # USER INTERFACE CALLBACKS def on_preview_mode_combobox_changed(self, combobox): """Update the preview mode in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.preview_mode = \ read_combobox(preferences_view['preview_mode_combobox']) def on_thumbnail_size_combobox_changed(self, combobox): """Update the thumbnail size in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.thumbnail_size = \ int(read_combobox(preferences_view['thumbnail_size_combobox'])) def on_toolbar_style_combobox_changed(self, combobox): """Update the toolbar style in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.toolbar_style = \ read_combobox(preferences_view['toolbar_style_combobox']) def on_remove_from_blacklist_button_clicked(self, button): """ Remove the currently selected blacklist device from the list. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['blacklist_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.remove(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_add_to_blacklist_button_clicked(self, button): """ Move the currently selected available scanner to the blacklist. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['available_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_remove_from_keywords_button_clicked(self, button): """ Remove the currently selected keyword from the list. """ preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['keywords_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_keywords = list(preferences_model.saved_keywords) temp_keywords.remove(selection_text) preferences_model.saved_keywords = temp_keywords def on_blacklist_tree_view_selection_changed(self, selection): """Update the available device controls.""" self._toggle_device_controls() def on_available_tree_view_selection_changed(self, selection): """Update the available device controls.""" self._toggle_device_controls() def on_preferences_dialog_response(self, dialog, response): """Close the preferences dialog.""" preferences_view = self.application.get_preferences_view() preferences_view['preferences_dialog'].hide() # PROPERTY CALLBACKS def property_preview_mode_value_change(self, model, old_value, new_value): """Select the active preview mode in the combobox.""" preferences_view = self.application.get_preferences_view() write_combobox(preferences_view['preview_mode_combobox'], new_value) def property_thumbnail_size_value_change(self, model, old_value, new_value): """Select the active thumbnail size in the combobox.""" preferences_view = self.application.get_preferences_view() write_combobox(preferences_view['thumbnail_size_combobox'], new_value) def property_toolbar_style_value_change(self, model, old_value, new_value): """Select the active toolbar style in the combobox.""" preferences_view = self.application.get_preferences_view() write_combobox(preferences_view['toolbar_style_combobox'], new_value) + + # If user sets to system default, need to force update from GConf + if new_value == 'System Default': + self.on_default_toolbar_style_changed(self.gconf_client) def property_blacklisted_scanners_value_change(self, model, old_value, new_value): """Update blacklisted scanners liststore.""" preferences_view = self.application.get_preferences_view() blacklist_liststore = preferences_view['blacklist_tree_view'].get_model() blacklist_liststore.clear() for blacklist_item in new_value: blacklist_liststore.append([blacklist_item]) self._toggle_device_controls() def property_saved_keywords_value_change(self, model, old_value, new_value): """Update keywords liststore.""" preferences_view = self.application.get_preferences_view() keywords_liststore = preferences_view['keywords_tree_view'].get_model() keywords_liststore.clear() for keyword in new_value: keywords_liststore.append([keyword]) # MainModel PROPERTY CALLBACKS def property_available_scanners_value_change(self, model, old_value, new_value): """Update available scanners liststore.""" preferences_view = self.application.get_preferences_view() available_liststore = preferences_view['available_tree_view'].get_model() available_liststore.clear() for available_item in new_value: available_liststore.append([available_item.display_name]) self._toggle_device_controls() def property_unavailable_scanners_value_change(self, model, old_value, new_value): """Update unavailable scanners liststore.""" preferences_view = self.application.get_preferences_view() unavailable_liststore = preferences_view['unavailable_tree_view'].get_model() unavailable_liststore.clear() for unavailable_item in new_value: unavailable_liststore.append(list(unavailable_item)) def property_updating_available_scanners_value_change(self, model, old_value, new_value): """ Disable device management controls while devices are being updated. """ self._toggle_device_controls() + + # GConf callbacks + + def on_default_toolbar_style_changed(self, client, *args, **kwargs): + """ + Update the toolbar style, if the user has not selected a style + specifically for NoStaples. + + Note: This method circumvents proper MVC separations in order to avoid + recursion and should probably be revisited at some point. + """ + preferences_model = self.application.get_preferences_model() + preferences_view = self.application.get_preferences_view() + + if preferences_model.toolbar_style != 'System Default': + return + + style = client.get_string('/desktop/gnome/interface/toolbar_style') + + try: + preferences_model.toolbar_style = \ + constants.SYSTEM_TOOLBAR_STYLES[style] + except KeyError: + preferences_model.toolbar_style = 'Icons Only' + + # Reset so that future system-wide changes will be handled. + # This must be back-ended to prevent an infinite recusion + if preferences_model.toolbar_style != 'System Default': + preferences_model._prop_toolbar_style = 'System Default' + write_combobox( + preferences_view['toolbar_style_combobox'], + 'System Default') # PUBLIC METHODS def run(self): """Run the preferences dialog.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() # Force property updates when dialog is run: this handles the case # where the PreferencesController has not been created until now # so it has not been receiving property notifications. self.property_blacklisted_scanners_value_change( preferences_model, None, preferences_model.blacklisted_scanners) self.property_saved_keywords_value_change( preferences_model, None, preferences_model.saved_keywords) self.property_available_scanners_value_change( main_model, None, main_model.available_scanners) self.property_unavailable_scanners_value_change( preferences_model, None, main_model.unavailable_scanners) preferences_view.run() # PRIVATE METHODS def _toggle_device_controls(self): """ Toggle the availability of the scanner management controls based on the state of the application. """ main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() if main_model.updating_available_scanners: preferences_view['remove_from_blacklist_button'].set_sensitive(False) preferences_view['add_to_blacklist_button'].set_sensitive(False) else: if preferences_view['blacklist_tree_view'].get_selection().count_selected_rows() > 0: preferences_view['remove_from_blacklist_button'].set_sensitive(True) else: preferences_view['remove_from_blacklist_button'].set_sensitive(False) if preferences_view['available_tree_view'].get_selection().count_selected_rows() > 0: preferences_view['add_to_blacklist_button'].set_sensitive(True) else: preferences_view['add_to_blacklist_button'].set_sensitive(False) \ No newline at end of file
onyxfish/nostaples
0ac61953b8c084b75fe9dd044e3ae077ed4bb70b
Assorted 'TODO' cleanup.
diff --git a/constants.py b/constants.py index bc7100b..b3e596c 100644 --- a/constants.py +++ b/constants.py @@ -1,206 +1,212 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. ''' This module contains global configuration constants that are not likely to change often as well as enumeration-like state constants. ''' import os import gtk import Image from reportlab.lib.pagesizes import A0, A1, A2, A3, A4, A5, A6, \ B0, B1, B2, B3, B4, B5, B6, LETTER, LEGAL, ELEVENSEVENTEEN + +VERSION = (0, 4, 0) PAGESIZES_INCHES = {'A0' : (33.1, 46.8), 'A1' : (23.4, 33.1), 'A2' : (16.5, 23.4), 'A3' : (11.7, 16.5), 'A4' : (8.3, 11.7), 'A5' : (5.8, 8.3), 'A6' : (4.1, 5.8), 'A7' : (2.9, 4.1), 'A8' : (2.0, 2.9), 'A9' : (1.5, 2.0), 'A10' : (1.0, 1.5), 'B0' : (39.4, 55.7), 'B1' : (27.8, 39.4), 'B2' : (19.7, 27.8), 'B3' : (13.9, 19.7), 'B4' : (9.8, 13.9), 'B5' : (6.9, 9.8), 'B6' : (4.9, 6.9), 'B7' : (3.5, 4.9), 'B8' : (2.4, 3.5), 'B9' : (1.7, 2.4), 'B10' : (1.2, 1.7), 'Letter' : (8.5, 11.0), 'Legal' : (8.5, 14.0), 'Junior Legal' : (8.0, 5.0), 'Ledger' : (17.0, 11.0), 'Tabloid' : (11.0, 17.0), '3x5 Photo' : (3.0, 5.0), '4x6 Photo' : (4.0, 6.0), '5x7 Photo' : (5.0, 7.0), '8x10 Photo' : (8.0, 10.0), '11x14 Photo' : (11.0, 14.0)} PAGESIZES_MM = {'A0' : (841.0, 1189.0), 'A1' : (594.0, 841.0), 'A2' : (420.0, 594.0), 'A3' : (297.0, 420.0), 'A4' : (210.0, 297.0), 'A5' : (148.0, 210.0), 'A6' : (105.0, 148.0), 'A7' : (74.0, 105.0), 'A8' : (52.0, 74.0), 'A9' : (37.0, 52.0), 'A10' : (26.0, 37.0), 'B0' : (1000.0, 1414.0), 'B1' : (707.0, 1000.0), 'B2' : (500.0, 707.0), 'B3' : (353.0, 500.0), 'B4' : (250.0, 353.0), 'B5' : (176.0, 250.0), 'B6' : (125.0, 176.0), 'B7' : (88.0, 125.0), 'B8' : (62.0, 88.0), 'B9' : (44.0, 62.0), 'B10' : (31.0, 44.0), 'Letter' : (216.0, 279.0), 'Legal' : (216.0, 356.0), 'Junior Legal' : (203.2, 127.0), 'Ledger' : (432.0, 279.0), 'Tabloid' : (279.0, 43.0), '3x5 Photo' : (76.0, 127.0), '4x6 Photo' : (102.0, 152.0), '5x7 Photo' : (127.0, 178.0), '8x10 Photo' : (203.0, 254.0), '11x14 Photo' : (279.0, 356.0)} PAGESIZE_SORT_ORDER = ['A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'A10', 'B0', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9', 'B10', 'Letter', 'Legal', 'Junior Legal', 'Ledger', 'Tabloid', '3x5 Photo', '4x6 Photo', '5x7 Photo', '8x10 Photo', '11x14 Photo'] DEFAULT_SHOW_TOOLBAR = True DEFAULT_SHOW_STATUSBAR = True DEFAULT_SHOW_THUMBNAILS = True DEFAULT_SHOW_ADJUSTMENTS = False DEFAULT_ROTATE_ALL_PAGES = False DEFAULT_ACTIVE_SCANNER = '' DEFAULT_SCAN_MODE = 'Color' DEFAULT_SCAN_RESOLUTION = '75' DEFAULT_PAGE_SIZE = 'A4' DEFAULT_SAVE_PATH = '' DEFAULT_AUTHOR = os.getenv('LOGNAME') DEFAULT_SAVED_KEYWORDS = [] DEFAULT_PREVIEW_MODE = 'Bilinear (Default)' DEFAULT_THUMBNAIL_SIZE = 128 DEFAULT_SHOW_DOCUMENT_METADATA = True DEFAULT_BLACKLISTED_SCANNERS = [] DEFAULT_TOOLBAR_STYLE = 'System Default' THUMBNAILS_SCALING_MODE = Image.ANTIALIAS +PREVIEW_ZOOM_MAX = 5.0 +PREVIEW_ZOOM_MIN = 1.0 +PREVIEW_ZOOM_STEP = 0.5 + MAX_VALID_OPTION_VALUES = 11 SCAN_CANCELLED = -1 SCAN_FAILURE = 0 SCAN_SUCCESS = 1 RESPONSE_BLACKLIST_DEVICE = 1 GCONF_DIRECTORY = '/apps/nostaples' GCONF_TUPLE_SEPARATOR = '|' GCONF_LIST_SEPARATOR = '^' # TODO: rename to CONFIG_DIRECTORY APP_DIRECTORY = os.path.expanduser('~/.nostaples') LOGGING_CONFIG = os.path.join(os.path.dirname(__file__), 'logging.config') GUI_DIRECTORY = os.path.join(os.path.dirname(__file__), 'gui') PREVIEW_MODES = \ { 'Nearest (Fastest)': gtk.gdk.INTERP_NEAREST, 'Tiles': gtk.gdk.INTERP_TILES, 'Bilinear (Default)': gtk.gdk.INTERP_BILINEAR, 'Antialias (Smoothest)': gtk.gdk.INTERP_HYPER } PREVIEW_MODES_LIST = \ [ 'Nearest (Fastest)', 'Tiles', 'Bilinear (Default)', 'Antialias (Smoothest)' ] THUMBNAIL_SIZE_LIST = \ [ 32, 64, 128, 256 ] TOOLBAR_STYLES = \ { 'System Default': None, 'Icons Only': gtk.TOOLBAR_ICONS, 'Text Only': gtk.TOOLBAR_TEXT, 'Icons and Text (Stacked)': gtk.TOOLBAR_BOTH, 'Icons and Text (Side by side)': gtk.TOOLBAR_BOTH_HORIZ } TOOLBAR_STYLES_LIST = \ [ 'System Default', 'Icons Only', 'Text Only', 'Icons and Text (Stacked)', 'Icons and Text (Side by side)' ] \ No newline at end of file diff --git a/controllers/document.py b/controllers/document.py index 9a92891..43f1987 100644 --- a/controllers/document.py +++ b/controllers/document.py @@ -1,473 +1,472 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{DocumentController}, which manages interaction between the L{DocumentModel} and L{DocumentView}. """ import logging import gtk from gtkmvc.controller import Controller import nostaples.utils.gui class DocumentController(Controller): """ Manages interaction between the L{DocumentModel} and L{DocumentView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the DocumentsController, as well as necessary sub-controllers. """ self.application = application Controller.__init__(self, application.get_document_model()) preferences_model = application.get_preferences_model() preferences_model.register_observer(self) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) application.get_document_model().connect( 'row-changed', self.on_document_model_row_changed) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) view['thumbnails_tree_view'].set_model( self.application.get_document_model()) view['thumbnails_tree_view'].get_selection().connect( 'changed', self.on_thumbnails_tree_view_selection_changed) view['thumbnails_tree_view'].connect( 'button-press-event', self.on_thumbnails_tree_view_button_press_event) view['delete_menu_item'].connect( "activate", self.on_delete_menu_item_activated) self.log.debug('%s registered.', view.__class__.__name__) # USER INTERFACE CALLBACKS def on_thumbnails_tree_view_selection_changed(self, selection): """ Set the current visible page to the be newly selected one. """ document_model = self.application.get_document_model() document_view = self.application.get_document_view() page_controller = self.application.get_page_controller() selection_iter = selection.get_selected()[1] if selection_iter: page_model = document_model.get_value(selection_iter, 0) page_controller.set_current_page_model(page_model) document_view['brightness_scale'].set_value(page_model.brightness) document_view['contrast_scale'].set_value(page_model.contrast) document_view['sharpness_scale'].set_value(page_model.sharpness) def on_thumbnails_tree_view_button_press_event(self, treeview, event): """ Popup the context menu when the user right-clicks. Method from U{http://faq.pygtk.org/index.py?req=show&file=faq13.017.htp}. """ document_view = self.application.get_document_view() if event.button == 3: info = treeview.get_path_at_pos(int(event.x), int(event.y)) if info is not None: document_view['thumbnails_context_menu'].popup( None, None, None, event.button, event.time) else: return True def on_document_model_row_changed(self, model, path, iter): """ Select a new rows when they are added. Per the following FAQ entry, must use row-changed event, not row-inserted. U{http://faq.pygtk.org/index.py?file=faq13.028.htp&req=show} Regarding the voodoo in this method: Whenever an adjustment causes page_model.thumbnail_pixbuf to be updated, the treeview emits a row-changed signal. If this method is allowed to handle those changes, then the change will be treated as a new row and it will be selected. This causes all sorts of unusual problems. To avoid this, all changes to a page_model that will cause thumbnail_pixbuf to be updated should be preceeded by setting the manually_updating_row flag so that this event can bypass them appropriately. """ document_model = self.application.get_document_model() document_view = self.application.get_document_view() if document_model.manually_updating_row: document_model.manually_updating_row = False else: document_view['thumbnails_tree_view'].get_selection().select_path(path) - # TODO: when a new row is added, if adjust_all is checked - # the current scale values should be applied to it. + # TICKET #49 # This code causes the application to hang: # if document_model.adjust_all_pages: # page_model = document_model.get_value(iter, 0) # document_model.manually_updating_row = True # page_model.set_adjustments( # document_view['brightness_scale'].get_value(), # document_view['contrast_scale'].get_value(), # document_view['sharpness_scale'].get_value()) def on_brightness_scale_value_changed(self, widget): """ Sets the brightness of the current page or, if "Apply to all pages?" is checked, all scanned pages. See L{on_document_model_row_changed} for an explanation of the voodoo in this method. """ document_model = self.application.get_document_model() document_view = self.application.get_document_view() page_model = self.application.get_current_page_model() status_controller = self.application.get_status_controller() if document_model.adjust_all_pages: i = 1 page_iter = document_model.get_iter_first() while page_iter: status_controller.push(self.status_context, 'Updating page %i...' % i) nostaples.utils.gui.flush_pending_events() page = document_model.get(page_iter, 0)[0] document_model.manually_updating_row = True page.brightness = \ document_view['brightness_scale'].get_value() page_iter = document_model.iter_next(page_iter) status_controller.pop(self.status_context) i = i + 1 else: status_controller.push(self.status_context, 'Updating current page...') nostaples.utils.gui.flush_pending_events() page_model.brightness = \ document_view['brightness_scale'].get_value() status_controller.pop(self.status_context) def on_contrast_scale_value_changed(self, widget): """ Sets the contrast of the current page or, if "Apply to all pages?" is checked, all scanned pages. See L{on_document_model_row_changed} for an explanation of the voodoo in this method. """ document_model = self.application.get_document_model() document_view = self.application.get_document_view() page_model = self.application.get_current_page_model() status_controller = self.application.get_status_controller() if document_model.adjust_all_pages: i = 1 page_iter = document_model.get_iter_first() while page_iter: status_controller.push(self.status_context, 'Updating page %i...' % i) nostaples.utils.gui.flush_pending_events() page = document_model.get(page_iter, 0)[0] document_model.manually_updating_row = True page.contrast = \ document_view['contrast_scale'].get_value() page_iter = document_model.iter_next(page_iter) status_controller.pop(self.status_context) i = i + 1 else: status_controller.push(self.status_context, 'Updating current page...') nostaples.utils.gui.flush_pending_events() page_model.contrast = \ document_view['contrast_scale'].get_value() status_controller.pop(self.status_context) def on_sharpness_scale_value_changed(self, widget): """ Sets the sharpness of the current page or, if "Apply to all pages?" is checked, all scanned pages. See L{on_document_model_row_changed} for an explanation of the voodoo in this method. """ document_model = self.application.get_document_model() document_view = self.application.get_document_view() page_model = self.application.get_current_page_model() status_controller = self.application.get_status_controller() if document_model.adjust_all_pages: i = 1 page_iter = document_model.get_iter_first() while page_iter: status_controller.push(self.status_context, 'Updating page %i...' % i) nostaples.utils.gui.flush_pending_events() page = document_model.get(page_iter, 0)[0] document_model.manually_updating_row = True page.sharpness = \ document_view['sharpness_scale'].get_value() page_iter = document_model.iter_next(page_iter) status_controller.pop(self.status_context) i = i + 1 else: status_controller.push(self.status_context, 'Updating current page...') nostaples.utils.gui.flush_pending_events() page_model.sharpness = \ document_view['sharpness_scale'].get_value() status_controller.pop(self.status_context) def on_adjust_all_pages_check_toggled(self, checkbox): """ When this box is checked, synchronize all page adjustments. See L{on_document_model_row_changed} for an explanation of the voodoo in this method. # TODO: should set hourglass cursor """ document_model = self.application.get_document_model() document_view = self.application.get_document_view() status_controller = self.application.get_status_controller() document_model.adjust_all_pages = checkbox.get_active() if document_model.adjust_all_pages: i = 1 page_iter = document_model.get_iter_first() while page_iter: status_controller.push(self.status_context, 'Updating page %i...' % i) nostaples.utils.gui.flush_pending_events() page = document_model.get(page_iter, 0)[0] document_model.manually_updating_row = True page.set_adjustments( document_view['brightness_scale'].get_value(), document_view['contrast_scale'].get_value(), document_view['sharpness_scale'].get_value()) page_iter = document_model.iter_next(page_iter) status_controller.pop(self.status_context) i = i + 1 def on_delete_menu_item_activated(self, menu_item): """Delete the currently selected page.""" self.delete_selected() # PROPERTY CALLBACKS def property_count_value_change(self, model, old_value, new_value): """ If all pages have been removed/deleted, switch to the null_page model for display. """ if new_value == 0: self.application.get_page_controller().set_current_page_model( self.application.get_null_page_model()) def property_thumbnail_size_value_change(self, model, old_value, new_value): """ Update the size of the thumbnail column and redraw all existing thumbnails. """ document_model = self.application.get_document_model() document_view = self.application.get_document_view() document_view['thumbnails_column'].set_fixed_width(new_value) page_iter = document_model.get_iter_first() while page_iter: page = document_model.get(page_iter, 0)[0] page._update_thumbnail_pixbuf() page_iter = document_model.iter_next(page_iter) # PUBLIC METHODS def toggle_thumbnails_visible(self, visible): """Toggle the visibility of the thumbnails view.""" document_view = self.application.get_document_view() if visible: document_view['thumbnails_scrolled_window'].show() else: document_view['thumbnails_scrolled_window'].hide() def toggle_adjustments_visible(self, visible): """Toggles the visibility of the adjustments view.""" document_view = self.application.get_document_view() if visible: document_view['adjustments_alignment'].show() else: document_view['adjustments_alignment'].hide() def delete_selected(self): """ Move the selection to the next page and delete the currently selected page. Selection is done here in place of catching the model's row-deleted signal, which seems like it I{should} be the proper way to do it. Unfortunantly, when trying to do it that way it was impossible to actually select another row as part of the event. This seems to work much more reliably. """ document_model = self.application.get_document_model() document_view = self.application.get_document_view() selection_iter = document_view['thumbnails_tree_view'].get_selection().get_selected()[1] if selection_iter: # Get the row element of the path row = document_model.get_path(selection_iter)[0] # Don't switch selections if this is the only page if document_model.count == 1: pass else: # Select previous row if deleting the last page if row == document_model.count - 1: document_view['thumbnails_tree_view'].get_selection().select_path(row - 1) # Otherwise select next row else: document_view['thumbnails_tree_view'].get_selection().select_path(row + 1) # Remove the row that was selected when the delete request was made document_model.remove(selection_iter) else: self.log.warn('Method delete_selected was called, but no selection has been made.') def rotate_counter_clockwise(self, rotate_all): """ Rotate the page counter-clockwise. """ status_controller = self.application.get_status_controller() if not rotate_all: page_model = self.application.get_current_page_model() status_controller.push(self.status_context, 'Rotating current page...') nostaples.utils.gui.flush_pending_events() page_model.rotate_counter_clockwise() status_controller.pop(self.status_context) else: document_model = self.application.get_document_model() page_iter = document_model.get_iter_first() i = 1 while page_iter: page_model = document_model.get_value(page_iter, 0) status_controller.push(self.status_context, 'Rotating page %i...' % i) nostaples.utils.gui.flush_pending_events() page_model.rotate_counter_clockwise() status_controller.pop(self.status_context) page_iter = document_model.iter_next(page_iter) i = i + 1 def rotate_clockwise(self, rotate_all): """ Rotate the page clockwise. """ status_controller = self.application.get_status_controller() if not rotate_all: page_model = self.application.get_current_page_model() status_controller.push(self.status_context, 'Rotating current page...') nostaples.utils.gui.flush_pending_events() page_model.rotate_clockwise() status_controller.pop(self.status_context) else: document_model = self.application.get_document_model() page_iter = document_model.get_iter_first() i = 1 while page_iter: page_model = document_model.get_value(page_iter, 0) status_controller.push(self.status_context, 'Rotating page %i...' % i) nostaples.utils.gui.flush_pending_events() page_model.rotate_clockwise() status_controller.pop(self.status_context) page_iter = document_model.iter_next(page_iter) i = i + 1 def goto_first_page(self): """Select the first scanned page.""" document_view = self.application.get_document_view() document_view['thumbnails_tree_view'].get_selection().select_path(0) def goto_previous_page(self): """Select the previous scanned page.""" document_model = self.application.get_document_model() document_view = self.application.get_document_view() iter = document_view['thumbnails_tree_view'].get_selection().get_selected()[1] row = document_model.get_path(iter)[0] if row == 0: return document_view['thumbnails_tree_view'].get_selection().select_path(row - 1) def goto_next_page(self): """Select the next scanned page.""" document_model = self.application.get_document_model() document_view = self.application.get_document_view() iter = document_view['thumbnails_tree_view'].get_selection().get_selected()[1] row = document_model.get_path(iter)[0] document_view['thumbnails_tree_view'].get_selection().select_path(row + 1) def goto_last_page(self): """ Select the last scanned page. Handles invalid paths gracefully without an exception case. """ document_model = self.application.get_document_model() document_view = self.application.get_document_view() document_view['thumbnails_tree_view'].get_selection().select_path(len(document_model) - 1) \ No newline at end of file diff --git a/controllers/main.py b/controllers/main.py index a590b26..0b996d1 100644 --- a/controllers/main.py +++ b/controllers/main.py @@ -1,808 +1,807 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{MainController}, which manages interaction between the L{MainModel} and L{MainView}. """ import commands import logging import os import re import threading import gobject import gtk from gtkmvc.controller import Controller from nostaples.models.page import PageModel import nostaples.sane as saneme from nostaples.utils.scanning import * class MainController(Controller): """ Manages interaction between the L{MainModel} and L{MainView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the MainController, as well as necessary sub-controllers and services. """ self.application = application Controller.__init__(self, application.get_main_model()) application.get_document_model().register_observer(self) application.get_preferences_model().register_observer(self) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ self.adapt('show_toolbar', 'show_toolbar_menu_item') self.adapt('show_statusbar', 'show_statusbar_menu_item') self.adapt('show_thumbnails', 'show_thumbnails_menu_item') self.adapt('show_adjustments', 'show_adjustments_menu_item') self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS # Menu Items def on_scan_window_destroy(self, window): """Exits the application.""" self.quit() def on_scan_menu_item_activate(self, menu_item): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_menu_item_activate(self, menu_item): """Refresh the list of connected scanners from SANE.""" self._update_available_scanners() def on_save_as_menu_item_activate(self, menu_item): """Saves the current document to a file.""" self.application.show_save_dialog() def on_delete_menu_item_activate(self, menu_item): self.application.get_document_controller().delete_selected() def on_preferences_menu_item_activate(self, menu_item): """Creates and displays a preferences dialog.""" self.application.show_preferences_dialog() def on_quit_menu_item_activate(self, menu_item): """Exits the application.""" self.quit() def on_zoom_in_menu_item_activate(self, menu_item): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_menu_item_activate(self, menu_item): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_menu_item_activate(self, menu_item): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_menu_item_activate(self, menu_item): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_available_scanner_menu_item_toggled(self, menu_item): """ Set the active scanner. - - TODO: Need a second scanner to properly test this... """ main_model = self.application.get_main_model() if menu_item.get_active(): for scanner in main_model.available_scanners: if scanner.display_name == menu_item.get_children()[0].get_text(): main_model.active_scanner = scanner return def on_valid_mode_menu_item_toggled(self, menu_item): """Sets the active scan mode.""" if menu_item.get_active(): self.application.get_main_model().active_mode = \ menu_item.get_children()[0].get_text() def on_valid_resolution_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_resolution = \ menu_item.get_children()[0].get_text() def on_valid_page_size_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_page_size = \ menu_item.get_children()[0].get_text() def on_go_first_menu_item_activate(self, menu_item): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_menu_item_activate(self, menu_item): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_menu_item_activate(self, menu_item): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_menu_item_activate(self, menu_item): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() def on_contents_menu_item_clicked(self, menu_item): - """TODO""" + """ + TICKET #8 + """ pass def on_about_menu_item_activate(self, menu_item): """Show the about dialog.""" self.application.show_about_dialog() # Toolbar Buttons def on_scan_button_clicked(self, button): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_button_clicked(self, button): self._update_available_scanners() def on_save_as_button_clicked(self, button): """Saves the current document to a file.""" self.application.show_save_dialog() def on_zoom_in_button_clicked(self, button): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_button_clicked(self, button): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_button_clicked(self, button): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_button_clicked(self, button): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_go_first_button_clicked(self, button): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_button_clicked(self, button): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_button_clicked(self, button): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_button_clicked(self, button): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() # Progress Window INTERFACE CALLBACKS def on_progress_window_delete_event(self, window, event): """ Emulate clicking of the cancel/close button and then hide the window. """ main_view = self.application.get_main_view() self.on_scan_cancel_button_clicked(None) main_view['progress_window'].hide() return True def on_scan_cancel_button_clicked(self, button): """ Cancel the current scan or, if the scan is finished, close the progress window. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress: assert self.cancel_event self.cancel_event.set() else: main_view['progress_window'].hide() def on_scan_again_button_clicked(self, button): """Initiate a new scan from the progress window.""" self._scan() def on_quick_save_button_clicked(self, button): """ Show the save dialog. If the user completes a save then disable the quick save button until another page is scanned. """ main_view = self.application.get_main_view() document_model = self.application.get_document_model() self.application.show_save_dialog() if document_model.count == 0: main_view['quick_save_button'].set_sensitive(False) # MainModel PROPERTY CALLBACKS def property_show_toolbar_value_change(self, model, old_value, new_value): """Update the visibility of the toolbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_toolbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['main_toolbar'].show() else: main_view['main_toolbar'].hide() def property_show_statusbar_value_change(self, model, old_value, new_value): """Update the visibility of the statusbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_statusbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['status_view_docking_viewport'].show() else: main_view['status_view_docking_viewport'].hide() def property_show_thumbnails_value_change(self, model, old_value, new_value): """Update the visibility of the thumbnails.""" main_view = self.application.get_main_view() menu_item = main_view['show_thumbnails_menu_item'] menu_item.set_active(new_value) self.application.get_document_controller().toggle_thumbnails_visible(new_value) def property_show_adjustments_value_change(self, model, old_value, new_value): """Update the visibility of the adjustments controls.""" document_controller = self.application.get_document_controller() main_view = self.application.get_main_view() menu_item = main_view['show_adjustments_menu_item'] menu_item.set_active(new_value) document_controller.toggle_adjustments_visible(new_value) def property_active_scanner_value_change(self, model, old_value, new_value): """ Update the menu and valid scanner options to match the new device. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() if new_value == None: return for menu_item in main_view['scanner_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value.display_name: menu_item.set_active(True) break def property_active_mode_value_change(self, model, old_value, new_value): """Select the active mode from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_mode_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_resolution_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_resolution_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_page_size_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_page_size_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_available_scanners_value_change(self, model, old_value, new_value): """ Update the menu of available scanners. """ main_view = self.application.get_main_view() self._clear_available_scanners_sub_menu() # Generate the new menu if len(new_value) == 0: menu_item = gtk.MenuItem('No Scanners Connected') menu_item.set_sensitive(False) main_view['scanner_sub_menu'].append(menu_item) else: first_item = None for i in range(len(new_value)): # The first menu item defines the group if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i].display_name) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i].display_name) main_view['scanner_sub_menu'].append(menu_item) main_view['scanner_sub_menu'].show_all() def property_valid_modes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan modes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_modes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Modes") menu_item.set_sensitive(False) main_view['scan_mode_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled) main_view['scan_mode_sub_menu'].append(menu_item) main_view['scan_mode_sub_menu'].show_all() def property_valid_resolutions_value_change(self, model, old_value, new_value): """ Updates the list of valid scan resolutions for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_resolutions_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Resolutions") menu_item.set_sensitive(False) main_view['scan_resolution_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled) main_view['scan_resolution_sub_menu'].append(menu_item) main_view['scan_resolution_sub_menu'].show_all() def property_valid_page_sizes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan page sizes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_page_sizes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Page Sizes") menu_item.set_sensitive(False) main_view['scan_page_size_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_page_size_menu_item_toggled) main_view['scan_page_size_sub_menu'].append(menu_item) main_view['scan_page_size_sub_menu'].show_all() def property_scan_in_progress_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() def property_updating_available_scanners_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() # DocumentModel PROPERTY CALLBACKS def property_count_value_change(self, model, old_value, new_value): """Toggle available controls.""" self._toggle_document_controls() # PreferencesModel PROPERTY CALLBACKS def property_toolbar_style_value_change(self, model, old_value, new_value): """Toggle available controls.""" main_view = self.application.get_main_view() if new_value == 'System Default': - # TODO - reset style to system default + # TICKET #35 pass else: main_view['main_toolbar'].set_style(constants.TOOLBAR_STYLES[new_value]) # THREAD CALLBACKS def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned): main_view = self.application.get_main_view() short_bytes_scanned = float(bytes_scanned) / 1000 short_total_bytes = float(scan_info.total_bytes) / 1000 main_view['scan_progressbar'].set_fraction( float(bytes_scanned) / scan_info.total_bytes) main_view['scan_progressbar'].set_text( 'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes)) - # TODO: multi page scans + main_view['progress_secondary_label'].set_markup( '<i>Scanning page.</i>') def on_scan_succeeded(self, scanning_thread, pil_image): """ - Append the new page to the current document. - TODO: update docstring + Update the progress window and append the new page to the current + document. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['scan_progressbar'].set_fraction(1) main_view['scan_progressbar'].set_text('Scan complete') main_view['progress_secondary_label'].set_markup( '<i>Adding page to document.</i>') gtk.gdk.flush() new_page = PageModel( self.application, pil_image, int(main_model.active_resolution), main_model.active_page_size) self.application.get_document_model().append(new_page) main_view['progress_secondary_label'].set_markup( '<i>Page added.</i>') main_view['scan_again_button'].set_sensitive(True) main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_failed(self, scanning_thread, reason): """ - Set that scan is complete. - TODO: update docstring + Update the progress window. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['progress_secondary_label'].set_markup( '<i>%s</i>' % reason) main_view['scan_again_button'].set_sensitive(True) if self.application.get_document_model().count > 0: main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_aborted(self, scanning_thread, exc_info): """ Change display to indicate that scanning failed and convey the to the user the reason why the thread aborted. If the failure was from a SANE exception then give the user the option to blacklist the device. If not, then reraise the error and let the sys.excepthook deal with it. """ self.on_scan_failed(scanning_thread, 'An error occurred.') if isinstance(exc_info[1], saneme.SaneError): self.run_device_exception_dialog(exc_info) else: raise exc_info[0], exc_info[1], exc_info[2] def on_update_available_scanners_thread_finished(self, update_thread, scanner_list): """Set the new list of available scanners.""" main_model = self.application.get_main_model() main_model.available_scanners = scanner_list main_model.updating_available_scanners = False def on_update_available_scanners_thread_aborted(self, update_thread, exc_info): """ Change the display to indicate that no scanners are available and reraise the exception so that it can be caught by the sys.excepthook. There is no reason to handle these cases with a special dialog, if the application failed to even enumerate the available devices then no other action will be possible. This should be fantastically rare. """ self.on_update_available_scanners_thread_finished(update_thread, []) raise exc_info[0], exc_info[1], exc_info[2] # PUBLIC METHODS def quit(self): """Exits the application.""" self.log.debug('Quit.') gtk.main_quit() def run_device_exception_dialog(self, exc_info): """ Display an error dialog that provides the user with the option of blacklisting the device which caused the error. TODO: Move into MainView. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() preferences_model = self.application.get_preferences_model() response = main_view.run_device_exception_dialog(exc_info) if response == constants.RESPONSE_BLACKLIST_DEVICE: temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(exc_info[1].device.display_name) temp_blacklist.sort() preferences_model.blacklisted_scanners = temp_blacklist # PRIVATE METHODS def _clear_available_scanners_sub_menu(self): """Clear the menu of available scanners.""" main_view = self.application.get_main_view() for child in main_view['scanner_sub_menu'].get_children(): main_view['scanner_sub_menu'].remove(child) def _clear_scan_modes_sub_menu(self): """Clear the menu of valid scan modes.""" main_view = self.application.get_main_view() for child in main_view['scan_mode_sub_menu'].get_children(): main_view['scan_mode_sub_menu'].remove(child) def _clear_scan_resolutions_sub_menu(self): """Clear the menu of valid scan resolutions.""" main_view = self.application.get_main_view() for child in main_view['scan_resolution_sub_menu'].get_children(): main_view['scan_resolution_sub_menu'].remove(child) def _clear_scan_page_sizes_sub_menu(self): """Clear the menu of valid scan page sizes.""" main_view = self.application.get_main_view() for child in main_view['scan_page_size_sub_menu'].get_children(): main_view['scan_page_size_sub_menu'].remove(child) def _toggle_scan_controls(self): """Toggle whether or not the scan controls or accessible.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_scan_controls_sensitive(False) main_view.set_refresh_scanner_controls_sensitive(False) else: if main_model.active_scanner != None: main_view.set_scan_controls_sensitive(True) main_view.set_refresh_scanner_controls_sensitive(True) def _toggle_document_controls(self): """ Toggle available document controls based on the current scanner status and the number of scanned pages. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() # Disable all controls when the scanner is in use if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: count = self.application.get_document_model().count # Disable all controls if no pages are scanned if count == 0: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: # Enable most controls if any pages scanned main_view.set_file_controls_sensitive(True) main_view.set_delete_controls_sensitive(True) main_view.set_zoom_controls_sensitive(True) main_view.set_adjustment_controls_sensitive(True) # Only enable navigation if more than one page scanned if count > 1: main_view.set_navigation_controls_sensitive(True) else: main_view.set_navigation_controls_sensitive(False) def _update_status(self): """ Update the text of the statusbar based on the current state of the application. """ main_model = self.application.get_main_model() status_controller = self.application.get_status_controller() status_controller.pop(self.status_context) if main_model.scan_in_progress: status_controller.push(self.status_context, 'Scanning...') elif main_model.updating_available_scanners: status_controller.push(self.status_context, 'Querying hardware...') else: if main_model.active_scanner: status_controller.push(self.status_context, 'Ready with %s.' % main_model.active_scanner.display_name) else: status_controller.push(self.status_context, 'No scanner available.') def _scan(self): """Begin a scan.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() main_model.scan_in_progress = True scanning_thread = ScanningThread(main_model.active_scanner) scanning_thread.connect("progress", self.on_scan_progress) scanning_thread.connect("succeeded", self.on_scan_succeeded) scanning_thread.connect("failed", self.on_scan_failed) scanning_thread.connect("aborted", self.on_scan_aborted) self.cancel_event = scanning_thread.cancel_event main_view['progress_primary_label'].set_markup( '<big><b>%s</b></big>' % main_model.active_scanner.display_name) main_view['scan_progressbar'].set_fraction(0) main_view['scan_progressbar'].set_text('Waiting for data') main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>') mode = main_model.active_mode if main_model.active_mode else 'Not set' main_view['progress_mode_label'].set_markup(mode) dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set' main_view['progress_resolution_label'].set_markup(dpi) page_size = '%s' % main_model.active_page_size if main_model.active_page_size else 'Not set' main_view['progress_page_size_label'].set_markup(page_size) main_view['scan_again_button'].set_sensitive(False) main_view['quick_save_button'].set_sensitive(False) main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL) main_view['progress_window'].show_all() scanning_thread.start() def _update_available_scanners(self): """ Start a new update thread to query for available scanners. """ sane = self.application.get_sane() main_model = self.application.get_main_model() main_model.updating_available_scanners = True update_thread = UpdateAvailableScannersThread(sane) update_thread.connect("finished", self.on_update_available_scanners_thread_finished) update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted) update_thread.start() \ No newline at end of file diff --git a/controllers/page.py b/controllers/page.py index 019b092..628ca25 100644 --- a/controllers/page.py +++ b/controllers/page.py @@ -1,499 +1,494 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{PageController}, which manages interaction between the L{PageModel} and L{PageView}. """ import logging import gtk from gtkmvc.controller import Controller from nostaples import constants class PageController(Controller): """ Manages interaction between the L{PageModel} and L{PageView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the PageController. """ self.application = application Controller.__init__(self, application.get_null_page_model()) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) application.get_preferences_model().register_observer(self) self.log = logging.getLogger(self.__class__.__name__) # The preview pixbuf is cached so it can be rerendered without # reapplying zoom transformations. self.preview_pixbuf = None # Non persistent settings that apply to all scanned pages self.preview_width = 0 self.preview_height = 0 self.preview_zoom = 1.0 self.preview_is_best_fit = False - # TODO: should be a gconf preference self.preview_zoom_rect_color = \ gtk.gdk.colormap_get_system().alloc_color( gtk.gdk.Color(65535, 0, 0), False, True) # Reusable temp vars to hold the start point of a mouse drag action. self.zoom_drag_start_x = 0 self.zoom_drag_start_y = 0 self.move_drag_start_x = 0 self.move_drag_start_y = 0 self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) # USER INTERFACE CALLBACKS def on_page_view_image_layout_button_press_event(self, widget, event): """ Begins a drag or zoom event. """ # Do not process mouse events if nothing is visible if not self.model.pixbuf: return if event.button == 1: self._begin_move(event.x, event.y) elif event.button == 3: self._begin_zoom(event.x, event.y) def on_page_view_image_layout_motion_notify_event(self, widget, event): """ Update the preview during a drag or zoom event. """ # Do not process mouse events if nothing is visible if not self.model.pixbuf: return # Handle both hint events and routine notifications # See: http://www.pygtk.org/pygtk2tutorial/sec-EventHandling.html if event.is_hint: mouse_state = event.window.get_pointer()[2] else: mouse_state = event.state # Move if (mouse_state & gtk.gdk.BUTTON1_MASK): self._update_move(event.x_root, event.y_root) # Zoom elif (mouse_state & gtk.gdk.BUTTON3_MASK): self._update_zoom(event.x, event.y) # NB: These need to be updated even if the button wasn't pressed self.move_drag_start_x = event.x_root self.move_drag_start_y = event.y_root def on_page_view_image_layout_button_release_event(self, widget, event): """ Ends a drag or zoom event. """ # Do not process mouse events if nothing is visible if not self.model.pixbuf: return # Move if event.button == 1: self._end_move() # Zoom elif event.button == 3: self._end_zoom(event.x, event.y) def on_page_view_image_layout_scroll_event(self, widget, event): """ - TODO: Mouse scroll event. Go to next/prev page? Or scroll image? + TICKET #48 """ pass def on_page_view_image_layout_size_request(self, widget, size): size.width = 1 size.height = 1 def on_page_view_image_layout_size_allocate(self, widget, allocation): """ Resizes the image preview size to match that which is allocated to the preview layout widget. - TODO: Resize of image does not occur until after the window has - finished resizing (which looks awful). + TICKET #3 """ if allocation.width == self.preview_width and \ allocation.height == self.preview_height: return self.preview_width = allocation.width self.preview_height = allocation.height self._update_preview() # PROPERTY CALLBACKS def property_pixbuf_value_change(self, model, old_value, new_value): """Update the preview display.""" self._update_preview() # PreferencesModel PROPERTY CALLBACKS def property_preview_mode_value_change(self, model, old_value, new_value): """Update the preview display.""" self._update_preview() # PUBLIC METHODS def get_current_page_model(self): """ Return the currently visible/selected page model. This may be the null page model. """ return self.model def set_current_page_model(self, page_model): """ Sets the PageModel that is currently being displayed in the preview area. """ self.model.unregister_observer(self) self.model = page_model self.model.register_observer(self) self._update_preview() def zoom_in(self): """ Zooms the preview image in. """ - # TODO: max zoom should be a gconf preference - if self.preview_zoom == 5: + if self.preview_zoom >= constants.PREVIEW_ZOOM_MAX: return - # TODO: zoom amount should be a gconf preference - self.preview_zoom += 0.5 + self.preview_zoom += constants.PREVIEW_ZOOM_STEP - if self.preview_zoom > 5: - self.preview_zoom = 5 + if self.preview_zoom > constants.PREVIEW_ZOOM_MAX: + self.preview_zoom = constants.PREVIEW_ZOOM_MAX self.preview_is_best_fit = False self._update_preview() def zoom_out(self): """ Zooms the preview image out. """ - # TODO: min zoom should be a gconf preference - if self.preview_zoom == 1.0: + if self.preview_zoom <= constants.PREVIEW_ZOOM_MIN: return - self.preview_zoom -= 0.5 + self.preview_zoom -= constants.PREVIEW_ZOOM_STEP - if self.preview_zoom < 0.5: - self.preview_zoom = 0.5 + if self.preview_zoom < constants.PREVIEW_ZOOM_MIN: + self.preview_zoom = constants.PREVIEW_ZOOM_MIN self.preview_is_best_fit = False self._update_preview() def zoom_one_to_one(self): """ Zooms the preview image to its true size. """ self.preview_zoom = 1.0 self.preview_is_best_fit = False self._update_preview() def zoom_best_fit(self): """ Zooms the preview image so the entire image will fit within the preview window. """ self.preview_is_best_fit = True self._update_preview() # PRIVATE (INTERNAL) METHODS def _begin_move(self, x, y): """ Determines if there is anything to be dragged and if so, sets the 'drag' cursor. """ page_view = self.application.get_page_view() if page_view['page_view_horizontal_scrollbar'].get_property('visible') and \ page_view['page_view_vertical_scrollbar'].get_property('visible'): return page_view['page_view_image'].get_parent_window().set_cursor( gtk.gdk.Cursor(gtk.gdk.FLEUR)) def _begin_zoom(self, x, y): """ Saves the starting position of the zoom and sets the 'zoom' cursor. """ page_view = self.application.get_page_view() page_view['page_view_image'].get_parent_window().set_cursor( gtk.gdk.Cursor(gtk.gdk.CROSS)) self.zoom_drag_start_x = x self.zoom_drag_start_y = y def _update_move(self, x, y): """ Moves/drags the preview in response to mouse movement. """ page_view = self.application.get_page_view() horizontal_adjustment = \ page_view['page_view_image_layout'].get_hadjustment() new_x = horizontal_adjustment.value + \ (self.move_drag_start_x - x) if new_x >= horizontal_adjustment.lower and \ new_x <= horizontal_adjustment.upper - horizontal_adjustment.page_size: horizontal_adjustment.set_value(new_x) vertical_adjustment = \ page_view['page_view_image_layout'].get_vadjustment() new_y = vertical_adjustment.value + \ (self.move_drag_start_y - y) if new_y >= vertical_adjustment.lower and \ new_y <= vertical_adjustment.upper - vertical_adjustment.page_size: vertical_adjustment.set_value(new_y) def _update_zoom(self, x, y): """ Renders a box around the zoom region the user has specified by dragging the mouse. """ page_view = self.application.get_page_view() start_x = self.zoom_drag_start_x start_y = self.zoom_drag_start_y end_x = x end_y = y if end_x < start_x: start_x, end_x = end_x, start_x if end_y < start_y: start_y, end_y = end_y, start_y width = end_x - start_x height = end_y - start_y page_view['page_view_image'].set_from_pixbuf(self.preview_pixbuf) page_view['page_view_image'].get_parent_window().invalidate_rect( (0, 0, self.preview_width, self.preview_height), False) page_view['page_view_image'].get_parent_window(). \ process_updates(False) graphics_context = \ page_view['page_view_image'].get_parent_window().new_gc( foreground=self.preview_zoom_rect_color, line_style=gtk.gdk.LINE_ON_OFF_DASH, line_width=2) page_view['page_view_image'].get_parent_window().draw_rectangle( graphics_context, False, int(start_x), int(start_y), int(width), int(height)) def _end_move(self): """ Resets to the default cursor. """ page_view = self.application.get_page_view() page_view['page_view_image'].get_parent_window().set_cursor(None) def _end_zoom(self, x, y): """ Calculates and applies zoom to the preview and updates the display. """ page_view = self.application.get_page_view() # Transform to absolute coords start_x = self.zoom_drag_start_x / self.preview_zoom start_y = self.zoom_drag_start_y / self.preview_zoom end_x = x / self.preview_zoom end_y = y / self.preview_zoom # Swizzle values if coords are reversed if end_x < start_x: start_x, end_x = end_x, start_x if end_y < start_y: start_y, end_y = end_y, start_y # Calc width and height width = end_x - start_x height = end_y - start_y # Calculate centering offset target_width = \ self.model.width * self.preview_zoom target_height = \ self.model.height * self.preview_zoom shift_x = int((self.preview_width - target_width) / 2) if shift_x < 0: shift_x = 0 shift_y = int((self.preview_height - target_height) / 2) if shift_y < 0: shift_y = 0 # Compensate for centering start_x -= shift_x / self.preview_zoom start_y -= shift_y / self.preview_zoom # Determine center-point of zoom region center_x = start_x + width / 2 center_y = start_y + height / 2 # Determine correct zoom to fit region if width > height: - # TODO: ZeroDivisionError has occurred here... + # TODO: ZeroDivisionError has occurred here... once self.preview_zoom = self.preview_width / width else: self.preview_zoom = self.preview_height / height - # Cap zoom at 500% - if self.preview_zoom > 5.0: - self.preview_zoom = 5.0 + # Cap zoom + if self.preview_zoom > constants.PREVIEW_ZOOM_MAX: + self.preview_zoom = constants.PREVIEW_ZOOM_MAX # Transform center-point to relative coords transform_x = int(center_x * self.preview_zoom) transform_y = int(center_y * self.preview_zoom) # Center in preview display transform_x -= int(self.preview_width / 2) transform_y -= int(self.preview_height / 2) self.preview_is_best_fit = False self._update_preview() page_view['page_view_image_layout'].get_hadjustment().set_value( transform_x) page_view['page_view_image_layout'].get_vadjustment().set_value( transform_y) page_view['page_view_image'].get_parent_window().set_cursor(None) def _update_preview(self): """ Render the current page to the preview display. """ page_view = self.application.get_page_view() preferences_model = self.application.get_preferences_model() status_controller = self.application.get_status_controller() # Short circuit if the PageModel does not have a pixbuf # (such as the null page). if not self.model.pixbuf: page_view['page_view_image'].clear() status_controller.pop(self.status_context) return # Fit if necessary if self.preview_is_best_fit: width_ratio = float(self.model.width) / self.preview_width height_ratio = float(self.model.height) / self.preview_height if width_ratio < height_ratio: self.preview_zoom = 1 / float(height_ratio) else: self.preview_zoom = 1 / float(width_ratio) # Zoom if necessary if self.preview_zoom != 1.0: target_width = \ int(self.model.width * self.preview_zoom) target_height = \ int(self.model.height * self.preview_zoom) gtk_scale_mode = \ constants.PREVIEW_MODES[preferences_model.preview_mode] self.preview_pixbuf = self.model.pixbuf.scale_simple( target_width, target_height, gtk_scale_mode) else: target_width = self.model.width target_height = self.model.height self.preview_pixbuf = self.model.pixbuf # Resize preview area page_view['page_view_image_layout'].set_size( target_width, target_height) # Center preview shift_x = int((self.preview_width - target_width) / 2) if shift_x < 0: shift_x = 0 shift_y = int((self.preview_height - target_height) / 2) if shift_y < 0: shift_y = 0 page_view['page_view_image_layout'].move( page_view['page_view_image'], shift_x, shift_y) # Show/hide scrollbars if target_width > self.preview_width: page_view['page_view_horizontal_scrollbar'].show() else: page_view['page_view_horizontal_scrollbar'].hide() if target_height > self.preview_height: page_view['page_view_vertical_scrollbar'].show() else: page_view['page_view_vertical_scrollbar'].hide() # Render updated preview page_view['page_view_image'].set_from_pixbuf(self.preview_pixbuf) # Update status status_controller.pop(self.status_context) status_controller.push(self.status_context, "%.0f%%" % (self.preview_zoom * 100)) \ No newline at end of file diff --git a/gui/about_dialog.glade b/gui/about_dialog.glade index d2dfc76..47e3775 100644 --- a/gui/about_dialog.glade +++ b/gui/about_dialog.glade @@ -1,59 +1,59 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> -<!--Generated with glade3 3.4.5 on Wed Mar 4 12:52:10 2009 --> +<!--Generated with glade3 3.4.5 on Sun Apr 5 15:13:43 2009 --> <glade-interface> <widget class="GtkAboutDialog" id="about_dialog"> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="border_width">5</property> <property name="title" translatable="yes">About NoStaples</property> <property name="resizable">False</property> <property name="modal">True</property> <property name="window_position">GTK_WIN_POS_CENTER_ON_PARENT</property> <property name="destroy_with_parent">True</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property> <property name="skip_taskbar_hint">True</property> <property name="skip_pager_hint">True</property> <property name="has_separator">False</property> <property name="program_name">NoStaples</property> - <property name="version">0.4.0</property> + <property name="version">X.Y.Z</property> <property name="copyright" translatable="yes">Copyright © 2009 Christopher Groskopf </property> <property name="comments" translatable="yes">A low-volume document imaging solution for Gnome.</property> <property name="website">http://www.etlafins.com/nostaples</property> <property name="website_label" translatable="yes">http://www.etlafins.com/nostaples</property> <property name="license" translatable="yes">NoStaples is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. NoStaples is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with NoStaples. If not, see &lt;http://www.gnu.org/licenses/&gt;.</property> <property name="authors">Christopher Groskopf &lt;[email protected]&gt;</property> <property name="documenters"></property> <signal name="close" handler="on_about_dialog_close"/> <signal name="delete_event" handler="on_about_dialog_delete_event"/> <signal name="response" handler="on_about_dialog_response"/> <child internal-child="vbox"> <widget class="GtkVBox" id="dialog-vbox1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="spacing">5</property> <child internal-child="action_area"> <widget class="GtkHButtonBox" id="dialog-action_area1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="layout_style">GTK_BUTTONBOX_END</property> </widget> <packing> <property name="expand">False</property> <property name="pack_type">GTK_PACK_END</property> </packing> </child> </widget> </child> </widget> </glade-interface> diff --git a/gui/document_view.glade b/gui/document_view.glade index 9fcecb0..4d82a50 100644 --- a/gui/document_view.glade +++ b/gui/document_view.glade @@ -1,204 +1,205 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> -<!--Generated with glade3 3.4.5 on Mon Feb 16 08:23:41 2009 --> +<!--Generated with glade3 3.4.5 on Sun Apr 5 14:43:21 2009 --> <glade-interface> <widget class="GtkWindow" id="dummy_document_view_window"> <child> <widget class="GtkHBox" id="document_view_horizontal_box"> <property name="visible">True</property> <child> <widget class="GtkScrolledWindow" id="thumbnails_scrolled_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_NEVER</property> <child> <placeholder/> </child> </widget> <packing> <property name="expand">False</property> + <property name="position">1</property> </packing> </child> <child> <widget class="GtkViewport" id="page_view_docking_viewport"> <property name="visible">True</property> <property name="resize_mode">GTK_RESIZE_QUEUE</property> <property name="shadow_type">GTK_SHADOW_NONE</property> <child> <placeholder/> </child> </widget> <packing> - <property name="position">1</property> + <property name="position">2</property> </packing> </child> <child> <widget class="GtkAlignment" id="adjustments_alignment"> <property name="no_show_all">True</property> <property name="top_padding">6</property> <property name="bottom_padding">6</property> <property name="left_padding">6</property> <property name="right_padding">6</property> <child> <widget class="GtkVBox" id="vbox4"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="spacing">6</property> <child> <widget class="GtkVBox" id="vbox5"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <child> <widget class="GtkLabel" id="brightness_label"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">Brightness:</property> </widget> <packing> <property name="fill">False</property> </packing> </child> <child> <widget class="GtkHScale" id="brightness_scale"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="update_policy">GTK_UPDATE_DELAYED</property> <property name="adjustment">1 0 2 0.5 1 0</property> <property name="restrict_to_fill_level">False</property> <property name="fill_level">0</property> <property name="value_pos">GTK_POS_LEFT</property> <signal name="value_changed" handler="on_brightness_scale_value_changed"/> </widget> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkVBox" id="vbox6"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <child> <widget class="GtkLabel" id="contrast_label"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">Contrast:</property> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <widget class="GtkHScale" id="contrast_scale"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="update_policy">GTK_UPDATE_DELAYED</property> <property name="adjustment">1 0 2 0.5 1 0</property> <property name="restrict_to_fill_level">False</property> <property name="fill_level">0</property> <property name="value_pos">GTK_POS_LEFT</property> <signal name="value_changed" handler="on_contrast_scale_value_changed"/> </widget> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child> <widget class="GtkVBox" id="vbox7"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <child> <widget class="GtkLabel" id="sharpness_label"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">Sharpness:</property> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <widget class="GtkHScale" id="sharpness_scale"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="update_policy">GTK_UPDATE_DELAYED</property> <property name="adjustment">1 0 2 0.5 1 0</property> <property name="restrict_to_fill_level">False</property> <property name="fill_level">0</property> <property name="value_pos">GTK_POS_LEFT</property> <signal name="value_changed" handler="on_sharpness_scale_value_changed"/> </widget> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="expand">False</property> <property name="position">2</property> </packing> </child> <child> <widget class="GtkHBox" id="hbox4"> <property name="visible">True</property> <property name="homogeneous">True</property> <child> <widget class="GtkCheckButton" id="adjust_all_pages_check"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="label" translatable="yes">Apply to all pages?</property> <property name="response_id">0</property> <property name="draw_indicator">True</property> <signal name="toggled" handler="on_adjust_all_pages_check_toggled"/> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">3</property> </packing> </child> </widget> </child> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="pack_type">GTK_PACK_END</property> <property name="position">2</property> </packing> </child> </widget> </child> </widget> </glade-interface> diff --git a/models/main.py b/models/main.py index 84e6a58..243dedb 100644 --- a/models/main.py +++ b/models/main.py @@ -1,834 +1,833 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme from nostaples.utils import properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'active_page_size' : None, 'available_scanners' : [], # [] of saneme.Device 'unavailable_scanners' : [], # [] of (saneme.Device.display_name, reason) tuples 'valid_modes' : [], 'valid_resolutions' : [], 'valid_page_sizes' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) self.active_page_size = state_manager.init_state( 'page_size', constants.DEFAULT_PAGE_SIZE, self.state_page_size_change) # PROPERTY SETTERS set_prop_show_toolbar = properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it's option constraints can be queried without error. if value is not None: # Verify that the proper type is being set assert isinstance(value, saneme.Device) # Open the new scanner try: self.log.debug( 'Setting active scanner to %s.' % value.display_name) value.open() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Get valid options from the new device and then reset the # previous options if they exist on the new device self._update_valid_modes() self.active_mode = self.active_mode self._update_valid_resolutions() self.active_resolution = self.active_resolution self._update_valid_page_sizes() self.active_page_size = self.active_page_size # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notifications self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_mode = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value self.log.debug( 'Setting active mode to %s.' % value) self.active_scanner.options['mode'].value = value except saneme.SaneInexactValueError: raise except saneme.SaneReloadOptionsError: # Reload any options that may have changed, this will # also force this value to be set again, so its safe to # return immediately self._reload_scanner_options() return # Never persist None to state if value is not None: self.application.get_state_manager()['scan_mode'] = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_resolution = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value self.log.debug( 'Setting active resolution to %s.' % value) self.active_scanner.options['resolution'].value = int(value) except saneme.SaneInexactValueError: raise except saneme.SaneReloadOptionsError: # Reload any options that may have changed, this will # also force this value to be set again, so its safe to # return immediately self._reload_scanner_options() return # Never persist None to state if value is not None: self.application.get_state_manager()['scan_resolution'] = value # Emit change notification self.notify_property_value_change( 'active_resolution', None, value) def set_prop_active_page_size(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_page_size = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Get the scan area options try: tl_x = self.active_scanner.options['tl-x'] tl_y = self.active_scanner.options['tl-y'] br_x = self.active_scanner.options['br-x'] br_y = self.active_scanner.options['br-y'] min_x = tl_x.constraint[0] min_y = tl_y.constraint[0] except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never set None to a device option # (it is safe to re-set these option values) if value is not None: if self.active_scanner.options['tl-x'].unit == saneme.OPTION_UNIT_PIXEL: # If there are no resolutions, then there should be no # page sizes to set. if len(self.valid_resolutions) == 0: raise AssertionError( 'Pixel-based page size being set when no valid resolutions are available.') resolution = max([int(i) for i in self.valid_resolutions]) page_width = int(resolution * constants.PAGESIZES_INCHES[value][0]) page_height = int(resolution * constants.PAGESIZES_INCHES[value][1]) else: page_width = constants.PAGESIZES_MM[value][0] page_height = constants.PAGESIZES_MM[value][1] # Set the new option value self.log.debug( 'Setting active page size to %s.' % value) needs_reload = False try: self.active_scanner.options['tl-x'].value = min_x except saneme.SaneInexactValueError: # See below pass except saneme.SaneReloadOptionsError: # See below needs_reload == True try: self.active_scanner.options['tl-y'].value = min_y except saneme.SaneInexactValueError: # See below pass except saneme.SaneReloadOptionsError: # See below needs_reload == True try: self.active_scanner.options['br-x'].value = \ min_x + page_width except saneme.SaneInexactValueError: # Coordinate may often be inexact due to backend # rounding/quantization. Nothing needs to be done # about this since the exact coordinates that have # been set are not cached in MainModel. pass except saneme.SaneReloadOptionsError: # Reload after other coordinates have been set. needs_reload == True try: self.active_scanner.options['br-y'].value = \ min_y + page_height except saneme.SaneInexactValueError: # See above pass except saneme.SaneReloadOptionsError: # See above needs_reload == True if needs_reload: self._reload_scanner_options() # Never persist None to state if value is not None: self.application.get_state_manager()['page_size'] = value # Emit change notification self.notify_property_value_change( 'active_page_size', None, value) def set_prop_available_scanners(self, value): """ Takes a new list of scanners, removes any which are blacklisted or unsupported, sets the new list, updates the active_scanner, and emits appropriate property callbacks. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() # Remove blacklisted scanners value = \ [scanner for scanner in value if not \ scanner.display_name in preferences_model.blacklisted_scanners] # Remove scanners that do not support necessary options or fail to # open entirely new_unavailable_scanners = [] - # TODO - move somewhere more appropriate? unsupported_scanner_error = \ 'Scanner %s is unsupported for the following reason: %s' for scanner in value: try: scanner.open() unsupported = False # Enforce mode option requirements if not scanner.has_option('mode'): reason = 'No \'mode\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue mode = scanner.options['mode'] if not self.is_settable_option(mode): reason = 'Unsettable \'mode\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue if not mode.constraint_type == saneme.OPTION_CONSTRAINT_STRING_LIST: reason = '\'Mode\' option does not include a STRING_LIST constraint.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # Enforce resolution option requirements if not scanner.has_option('resolution'): reason = 'No \'resolution\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue resolution = scanner.options['resolution'] if not self.is_settable_option(resolution): reason = 'Unsettable \'resolution\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue if resolution.constraint_type == saneme.OPTION_CONSTRAINT_NONE: reason = '\'Resolution\' option does not specify a constraint.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # See SANE API 4.5.2 if resolution.type != saneme.OPTION_TYPE_INT and \ resolution.type != saneme.OPTION_TYPE_FLOAT: reason = '\'Resolution\' option is not of type INT or FLOAT.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # See SANE API 4.5.2 if not resolution.unit == saneme.OPTION_UNIT_DPI: reason = '\'Resolution\' option is not measured in DPI units.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # Enforce scan area option requirements scan_area_option_names = ['tl-x', 'tl-y', 'br-x', 'br-y'] supported = True for option_name in scan_area_option_names: if not scanner.has_option(option_name): supported = False if not supported: reason = 'No \'scan area\' options.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue scan_area_options = \ [scanner.options[o] for o in scan_area_option_names] supported = True for option in scan_area_options: if option.type != saneme.OPTION_TYPE_INT: supported = False if not supported: reason = '\'Scan area\' options are not of type INT.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue supported = True for option in scan_area_options: if option.unit != saneme.OPTION_UNIT_PIXEL and \ option.unit != saneme.OPTION_UNIT_MM: supported = False if not supported: reason = '\'Scan area\' options are not measured in unit PIXEL or MM.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue supported = True for option in scan_area_options: if option.constraint_type != saneme.OPTION_CONSTRAINT_RANGE: supported = False if not supported: reason = '\'Scan area\' options do not specify a RANGE constraint.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue scanner.close() except saneme.SaneError: reason = 'Exception raised while attempting to query device options.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue self._prop_unavailable_scanners = new_unavailable_scanners self._prop_available_scanners = value self.notify_property_value_change( 'unavailable_scanners', None, new_unavailable_scanners) self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None elif self._prop_active_scanner not in value: self.active_scanner = value[0] def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) if len(value) == 0: self.active_mode = None elif self.active_mode not in value: self.active_mode = value[0] def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) if len(value) == 0: self.active_resolution = None elif self.active_resolution not in value: self.active_resolution = value[0] def set_prop_valid_page_sizes(self, value): """ Set the list of valid scan page sizes, update the active page size and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_page_sizes = value self.notify_property_value_change( 'valid_page_sizes', None, value) if len(value) == 0: self.active_page_size = None elif self.active_page_size not in value: self.active_page_size = value[0] # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution def state_page_size_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_page_size'] in self.valid_page_sizes: self.active_page_size = state_manager['scan_page_size'] else: state_manager['scan_page_size'] = self.active_page_size # INTERNAL METHODS def is_settable_option(self, option): """ Verify an option supports minimum capabilities needed to be used by NoStaples. """ return option.is_active() and \ option.is_soft_gettable() and \ option.is_soft_settable() def _update_valid_modes(self): """ Update valid modes from the active scanner. """ self.valid_modes = self.active_scanner.options['mode'].constraint def _update_valid_resolutions(self): """ Update valid resolutions from the active scanner. """ if self.active_scanner.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_RANGE: min, max, step = self.active_scanner.options['resolution'].constraint # Fix for ticket #34. if step is None or step == 0: step = 1 resolutions = [] # If there are not an excessive number, include every possible # resolution if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: i = min while i <= max: resolutions.append(str(i)) i = i + step # Otherwise, take a crack at building a sensible set of options # that meet that constraint criteria else: # TODO: This is a naive implementation that is likely to # generate an unusuably large number of valid resolutions. i = min tested_resolutions = [] while i <= max: try: self.active_scanner.options['resolution'].value = i except saneme.SANE_INFO_INEXACT: pass except saneme.SANE_INFO_RELOAD_PARAMS: pass tested_resolutions.append( self.active_scanner.options['resolution'].value) i = i + step # Prune duplicates # http://code.activestate.com/recipes/52560/ uniques = {} for j in tested_resolutions: uniques[j] = True resolutions = [str(k) for k in uniques.keys()] self._prop_valid_resolutions = resolutions elif self.active_scanner.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_VALUE_LIST: # Convert values to strings for display self.valid_resolutions = \ [str(i) for i in self.active_scanner.options['resolution'].constraint] elif self.active_scanner.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST: self.valid_resolutions = \ self.active_scanner.options['resolution'].constraint else: raise AssertionError('Unsupported constraint type.') def _update_valid_page_sizes(self): """ Update valid page sizes from the active scanner.tl_x + page_width """ main_controller = self.application.get_main_controller() try: tl_x = self.active_scanner.options['tl-x'] tl_y = self.active_scanner.options['tl-y'] br_x = self.active_scanner.options['br-x'] br_y = self.active_scanner.options['br-y'] max_x = br_x.constraint[1] - tl_x.constraint[0] max_y = br_y.constraint[1] - tl_y.constraint[0] except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) new_sizes = [] for size in constants.PAGESIZES_INCHES.iterkeys(): if tl_x.unit == saneme.OPTION_UNIT_PIXEL: if len(self.valid_resolutions) == 0: break resolution = max([int(i) for i in self.valid_resolutions]) page_width = int(resolution * constants.PAGESIZES_INCHES[size][0]) page_height = int(resolution * constants.PAGESIZES_INCHES[size][1]) elif tl_x.unit == saneme.OPTION_UNIT_MM: page_width = int(constants.PAGESIZES_MM[size][0]) page_height = int(constants.PAGESIZES_MM[size][1]) else: raise AssertionError( 'Unknown measurement unit for scan area options.') if page_width <= max_x and page_height <= max_y: new_sizes.append(size) def page_size_sort(x, y): """ Sort paper sizes according to their order in a constant list. """ sort_x = constants.PAGESIZE_SORT_ORDER.index(x) sort_y = constants.PAGESIZE_SORT_ORDER.index(y) if sort_x > sort_y: return 1 elif sort_x == sort_y: return 0 else: return -1 new_sizes.sort(page_size_sort) self.valid_page_sizes = new_sizes def _reload_scanner_options(self): """ Get current scanner options from the active_scanner. Use to reload options in response to a SaneReloadOptionsError. IMPORTANT: An empirical review of SANE backends has shown that neither the constraints nor the values of the scan area options are changed when the Reload Options flag is set. Also, the backend may change scan area option values that are set due to quantization/rounding, so it would be impossible to read the new value and determine the set page size from that. For these two reasons, updating the active and valid page sizes is excluded from this method. """ main_controller = self.application.get_main_controller() self.log.debug('Reloading scanner options.') try: # Read updated values from the device new_mode = self.active_scanner.options['mode'].value new_resolution = str(self.active_scanner.options['resolution'].value) # Reload valid options self._update_valid_modes() self._update_valid_resolutions() # Reset new values (in case they were overwritten) self.active_mode = new_mode self.active_resolution = new_resolution except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) self.log.debug('Scanner options reloaded.') \ No newline at end of file diff --git a/sane/saneme.py b/sane/saneme.py index 4b53c96..0571ccd 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -1,1018 +1,1013 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module contains the Pythonic implementation of the SANE API. The flat C functions have been wrapped in a set of objects and all ctypes of the underlying implmentation have been hidden from the user's view. This enumerations and definiations which are absolutely necessary to the end user have been redeclared. """ -# TODO: document what exceptions can be thrown by each method, -# including those that could bubble up - from array import * import atexit import ctypes from types import * from PIL import Image from errors import * from saneh import * # Redeclare saneh enumerations which are visible to the application (OPTION_TYPE_BOOL, OPTION_TYPE_INT, # Automatically converted from SANE_TYPE_FIXED OPTION_TYPE_FLOAT, OPTION_TYPE_STRING, OPTION_TYPE_BUTTON, OPTION_TYPE_GROUP) = xrange(6) (OPTION_UNIT_NONE, OPTION_UNIT_PIXEL, OPTION_UNIT_BIT, OPTION_UNIT_MM, OPTION_UNIT_DPI, OPTION_UNIT_PERCENT, OPTION_UNIT_MICROSECOND) = xrange(7) (OPTION_CONSTRAINT_NONE, OPTION_CONSTRAINT_RANGE, OPTION_CONSTRAINT_VALUE_LIST, OPTION_CONSTRAINT_STRING_LIST) = xrange(4) class SaneMe(object): """ The top-level object for interacting with the SANE API. Handles polling for devices. This object should only be instantiated once. """ _log = None _version = None # (major, minor, build) _devices = [] def __init__(self, log=None): """ Create the SANE object, perform setup, and register the cleanup function. @param log: an optional Python logging object to log to. """ self._log = log self._setup() atexit.register(self._shutdown) # Read only properties def __get_version(self): """Get the current installed version of SANE.""" return self._version version = property(__get_version) def _setup(self): """ Iniitalize SANE and retrieve the current installed version. """ version_code = SANE_Int() auth_callback = SANE_Auth_Callback(self._sane_auth_callback) status = sane_init(byref(version_code), auth_callback) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_init returned an invalid status: %i.' % status) self._version = (SANE_VERSION_MAJOR(version_code), SANE_VERSION_MINOR(version_code), SANE_VERSION_BUILD(version_code)) if self._log: self._log.info('SANE version %s initalized.', self._version) def _sane_auth_callback(self, resource, username, password): """ - TODO + TICKET #44 """ raise NotImplementedError( 'sane_auth_callback requested, but not yet implemented.') def _shutdown(self): """ Deinitialize SANE. This code would go in __del__, but it is not guaranteed that method will be called and sane_exit must be called to release resources. To ensure this method is called it is registered with atexit. """ for device in self._devices: if device.is_open(): device.close() sane_exit() self._version = None if self._log: self._log.info('SANE deinitialized.') # Public Methods def get_device_list(self): """ Poll for connected devices. This method may take several seconds to return. Note that SANE is exited and re-inited before querying for devices to workaround a limitation in SANE's USB driver which causes the device list to only be updated on init. This means that all settings applied to all devices will be B{lost} and must be restored by the calling application. This was found documented here: U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html} """ if not self._version: raise AssertionError('version was None') # See docstring for details on this voodoo self._shutdown() self._setup() cdevices = POINTER(POINTER(SANE_Device))() status = sane_get_devices(byref(cdevices), SANE_Bool(0)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_get_devices ran out of memory.') else: raise SaneUnknownError( 'sane_get_devices returned an invalid status: %i.' % status) device_count = 0 self._devices = [] while cdevices[device_count]: self._devices.append( Device(cdevices[device_count].contents, self._log)) device_count += 1 if self._log: self._log.info('SANE queried, %i device(s) found.', device_count) return self._devices def get_device_by_name(self, name): """ Retrieve a L{Device} by name. Must be preceded by a call to L{get_device_list}. """ for device in self._devices: if device.name == name: return device raise SaneNoSuchDeviceError( 'The requested device does not exist.') class Device(object): """ This is the primary object for interacting with SANE. It represents a single device and handles enumeration of options, getting and setting of options, and starting and stopping of scanning jobs. """ _log = None _handle = None _name = '' _vendor = '' _model = '' _type = '' _display_name = '' _options = {} def __init__(self, ctypes_device, log=None): """ Sets the Devices properties from a ctypes SANE_Device and queries for its available options. """ self._log = log # String attributes should never be None self._name = ctypes_device.name if ctypes_device.name else '' self._vendor = ctypes_device.vendor if ctypes_device.vendor else '' self._model = ctypes_device.model if ctypes_device.model else '' self._type = ctypes_device.type if ctypes_device.type else '' self._display_name = ' '.join([self._vendor, self._model]) # Read only properties def __get_name(self): """ Get the complete SANE identifier for this device, e.g. 'lexmark:libusb:002:006'. """ return self._name name = property(__get_name) def __get_vendor(self): """Get the manufacturer of this device, e.g. 'Lexmark'.""" return self._vendor vendor = property(__get_vendor) def __get_model(self): """Get the specific model of this device, e.g. 'X1100/rev. B2'.""" return self._model model = property(__get_model) def __get_type(self): """Get the type of this device, e.g. 'flatbed scanner'.""" return self._type type = property(__get_type) def __get_display_name(self): """ Get an appropriate name to use for displaying this device to a user, e.g. 'Lexmark X1100/rev. B2'.""" return self._display_name display_name = property(__get_display_name) def __get_options(self): """Get the dictionary of options that this device has.""" return self._options options = property(__get_options) # Public methods def open(self): """ Open a new handle to this device. Must be called before any operations (including getting or setting options) are performed on this device. """ if self._handle: raise AssertionError('device handle already exists.') self._handle = SANE_Handle() status = sane_open(self.name, byref(self._handle)) # If and exception will be thrown, nullify device handle # so is_open() will return false for the device. if status != SANE_STATUS_GOOD.value: self._handle = None if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_open reported that the device was busy.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) self._load_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) def has_option(self, option_name): """Return true if option_name is available for this scanner.""" return (option_name in self.options.keys()) def scan(self, progress_callback=None): """ Scan a document using this device. - TODO: handle ADF scans - @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater_update_options access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: # Lineart if sane_parameters.depth == 1: pil_image = Image.frombuffer( '1', (scan_info.width, scan_info.height), data_array, 'raw', '1;I', 0, 1) # Grayscale elif sane_parameters.depth == 8: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) else: raise AssertionError( 'Unexpected bit depth for monochrome scan format: %i' % sane_parameters.depth) elif sane_parameters.format == SANE_FRAME_RGB.value: # Color pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: - # TODO + # TICKET #45 raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Internal methods def _load_options(self): """ Update the list of available options for this device. This is called when the Device is first instantiated and in response to any SANE_INFO_RELOAD_OPTIONS flags when setting option values. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') option_value = pointer(c_int()) status = sane_control_option( self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: raise SaneUnsupportedOperationError( 'sane_control_option reported that a value was outside the option\'s constraint.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) option_count = option_value.contents.value if self._log: self._log.debug('Device queried, %i option(s) found.', option_count) self._options.clear() i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) self._options[coption.contents.name] = Option( self, i, coption.contents, self._log) i = i + 1 class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capability = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number # String attributes should never be None self._name = ctypes_option.name if ctypes_option.name else '' self._title = ctypes_option.title if ctypes_option.title else '' self._description = ctypes_option.desc if ctypes_option.desc else '' self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: if self._type == SANE_TYPE_FIXED.value: self._constraint = ( SANE_UNFIX(ctypes_option.constraint.range.contents.min), SANE_UNFIX(ctypes_option.constraint.range.contents.max), SANE_UNFIX(ctypes_option.constraint.range.contents.quant)) else: self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 if self._type == SANE_TYPE_FIXED.value: self._constraint = [SANE_UNFIX(i) for i in self._constraint] elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 if self._type == SANE_TYPE_FIXED.value: self._constraint = [str(SANE_UNFIX(int(i))) for i in self._constraint] else: self._constraint = None # Read only properties def __get_name(self): """ Get the short-form name of this option, e.g. 'mode'. May be an empty string, but never None. """ return self._name name = property(__get_name) def __get_title(self): """ Get the full name of this option, e.g. 'Scan mode'. May be an empty string, but never None. """ return self._title title = property(__get_title) def __get_description(self): """ Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' May be an empty string, but never None. """ return self._description description = property(__get_description) def __get_type(self): """ Get the type of this option, e.g. OPTION_TYPE_STRING. """ return self._type type = property(__get_type) def __get_unit(self): """ Get the unit of this option, e.g.OPTION_UNIT_DPI. """ return self._unit unit = property(__get_unit) def __get_constraint_type(self): """ Get the type of constraint on this option, e.g. OPTION_CONSTRAINT_RANGE. """ return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_VALUE_LIST then this is a list of ints/floats which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """value Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option( handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i.' % status, device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value elif self._type == SANE_TYPE_FIXED.value: option_value = SANE_UNFIX(option_value.value) else: option_value = option_value.contents.value # if self._log: # self._log.debug( # 'Option %s queried, its current value is %s.', # self._name, # option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: raise TypeError( 'option set with %s, expected BooleanType' % type(value)) c_value = pointer(SANE_Bool(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(SANE_Int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType and type(value) is not FloatType: raise TypeError( 'option set with %s, expected IntType or FloatType' % type(value)) c_value = pointer(SANE_Fixed(SANE_FIX(value))) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: raise TypeError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: raise ValueError( 'value for option is longer than max string size') c_value = SANE_String(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: min, max, step = self._constraint if value < min: raise ValueError('value for option is less than min.') if value > max: raise ValueError('value for option is greater than max.') if step is not None and step > 0: # In theory this should be enforced, but in practice it is # useful to sometimes let the backend adjust the values # (such as with page size, where their may not be a perfect # fit). If the value does not match the step, it will cause # a SaneInexactValueError to be thrown, which the frontened # can handle in different ways depending on the option being # set. pass elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i .' % status, device=self._device) # if self._log: # self._log.debug('Option %s set to value %s.', self._name, value) # See SANE API 4.3.7 if info_flags.value & SANE_INFO_RELOAD_OPTIONS: self._device._load_options() raise SaneReloadOptionsError() # Catching this can not be avoided by constraint checking, as some # devices restrict option values without setting a constraint range # step. if info_flags.value & SANE_INFO_INEXACT: raise SaneInexactValueError() # TODO? if info_flags.value & SANE_INFO_RELOAD_PARAMS: pass value = property(__get_value, __set_value) # PUBLIC METHODS def is_soft_settable(self): """ Returns True if the option can be set by software. """ return self._capability & SANE_CAP_SOFT_SELECT def is_hard_settable(self): """ Returns True if the option can be set by hardware. """ return self._capability & SANE_CAP_HARD_SELECT def is_soft_gettable(self): """ Returns True if the option can be read by software. """ return self._capability & SANE_CAP_SOFT_DETECT def is_emulated(self): """ Returns True if the option is emulated by the backend driver. """ return self._capability & SANE_CAP_EMULATED # def is_automatic(self): # return self._capability & SANE_CAP_AUTOMATIC def is_active(self): """ Returns False if this device is unavailable because of the value of some other option. """ return not self._capability & SANE_CAP_INACTIVE # def is_advanced(self): # return self._capability & SANE_CAP_ADVANCED class ScanInfo(object): """ Contains the parameters and progress of a scan in progress. """ _width = 0 _height = 0 _depth = 0 _total_bytes = 0 def __init__(self, sane_parameters): """ Initialize the ScanInfo object from the sane_parameters. """ self._width = sane_parameters.pixels_per_line self._height = sane_parameters.lines self._depth = sane_parameters.depth self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines # Read only properties def __get_width(self): """Get the width of the current scan, in pixels.""" return self._width width = property(__get_width) def __get_height(self): """Get the height of the current scan, in pixels.""" return self._height height = property(__get_height) def __get_depth(self): """Get the depth of the current scan, in bits.""" return self._depth depth = property(__get_depth) def __get_total_bytes(self): """Get the total number of bytes comprising this scan.""" return self._total_bytes total_bytes = property(__get_total_bytes) \ No newline at end of file diff --git a/views/about.py b/views/about.py index ebac133..70a1d13 100644 --- a/views/about.py +++ b/views/about.py @@ -1,66 +1,68 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the AboutView which exposes the application's about dialog. """ import logging import os import gtk from gtkmvc.view import View from nostaples import constants class AboutView(View): """ Exposes the application's main window. """ def __init__(self, application): """Constructs the AboutView.""" self.application = application about_controller = self.application.get_about_controller() about_dialog_glade = os.path.join( constants.GUI_DIRECTORY, 'about_dialog.glade') # This must be set before the window is created or # the url will not be clickable. gtk.about_dialog_set_url_hook( about_controller.on_about_dialog_url_clicked) View.__init__( self, about_controller, about_dialog_glade, 'about_dialog', None, False) self.log = logging.getLogger(self.__class__.__name__) # Can't do this in constructor as main_view has multiple # top-level widgets self['about_dialog'].set_transient_for( self.application.get_main_view()['scan_window']) + + self['about_dialog'].set_version('%i.%i.%i' % constants.VERSION) self.application.get_about_controller().register_view(self) self.log.debug('Created.') def run(self): """Run this modal dialog.""" self['about_dialog'].run() \ No newline at end of file
onyxfish/nostaples
9c33ef785e61406c417074001b7263e15893da10
Added pygtkmvc import check.
diff --git a/nostaples b/nostaples index 01e503e..d4c9fee 100755 --- a/nostaples +++ b/nostaples @@ -1,174 +1,187 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. ''' This module parses command line options, checks that imports are available, and bootstraps the NoStaples application. ''' import optparse import sys import pygtk pygtk.require('2.0') import gtk # COMMAND LINE PARSING # Functions to pretty-print debugging info def print_device_debug(i, device): """Pretty-print device information.""" print 'Device %i' % i print '' print 'Name:\t%s' % device.name print 'Vendor:\t%s' % device.vendor print 'Model:\t%s' % device.model print 'Type:\t%s' % device.type print '' try: device.open() j = 1 for option in device.options.values(): print_option_debug(j, option) print '' j = j + 1 device.close() except Exception: print '\t**Failed to open device.**' def print_option_debug(j, option): """Pretty-print device option information.""" print '\tOption %i' % j print '' print '\tName:\t%s' % option._name print '\tTitle:\t%s' % option._title print '\tDesc:\t%s' % option._description print '\tType:\t%s' % option._type print '\tUnit:\t%s' % option._unit print '\tSize:\t%s' % option._size print '\tCap:\t%s' % option._capability print '\tConstraint Type:\t%s' % option._constraint_type print '\tConstraint:\t', option._constraint if not option.is_active(): print '\tValue:\tNot active.' elif not option.is_soft_gettable(): print '\tValue:\tNot soft-gettable.' else: try: print '\tValue:\t%s' % str(option.value) except Exception: print '\t**Failed to get current value for option.**' # Parse command line options parser = optparse.OptionParser() parser.add_option("--debugdevices", action="store_true", dest="debug_devices", help="print debugging information for all connected devices") (options, args) = parser.parse_args() if options.debug_devices: import nostaples.sane as saneme sane_manager = saneme.SaneMe() devices = sane_manager.get_device_list() if len(devices) == 0: print 'No devices found.' i = 1 for device in devices: print_device_debug(i, device) print '' i = i + 1 sys.exit() # CHECK IMPORT VERSIONS def display_import_error(message): """ Displays a GTK message dialog containing the import error and then exits the application. """ dialog = gtk.MessageDialog( parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_NONE) dialog.set_title('') primary = "<big><b>A required package is not installed.</b></big>" secondary = '%s' % message dialog.set_markup(primary) dialog.format_secondary_markup(secondary) dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) response = dialog.run() dialog.destroy() sys.exit() # Python if sys.version_info < (2, 5) or sys.version_info >= (3, 0): display_import_error( 'NoStaples requires Python version 2.5 or later (but not version 3.0 or later).') # GTK if gtk.gtk_version < (2, 6, 0): display_import_error( 'NoStaples requires GTK+ version 2.6 or later.') if gtk.pygtk_version < (2, 8, 0): display_import_error( 'NoStaples requires PyGTK version 2.8 or later.') # PIL try: import Image except ImportError: display_import_error( 'NoStaples requires the Python Imaging Library (PIL) 1.1.6 or later.') pil_version = tuple([int(i) for i in Image.VERSION.split('.')]) if pil_version < (1, 1, 6): display_import_error( 'NoStaples requires the Python Imaging Library (PIL) version 1.1.6 or later.') # ReportLab try: import reportlab except ImportError: display_import_error( 'NoStaples requires ReportLab version 2.1 or later.') reportlab_version = tuple([int(i) for i in reportlab.Version.split('.')]) if reportlab_version < (2, 1): display_import_error( 'NoStaples requires ReportLab version 2.1 or later.') + +# Python-gtkmvc +try: + import gtkmvc +except ImportError: + display_import_error( + 'NoStaples requires python-gtkmvc version 1.2.2 (exactly).') + +pygtkmvc_version = gtkmvc.get_version() + +if pygtkmvc_version != (1, 2, 2): + display_import_error( + 'NoStaples requires python-gtkmvc version 1.2.2 (exactly).') # BOOTSTRAP from nostaples.application import Application nostaples = Application() nostaples.run()
onyxfish/nostaples
dac4e6f2505bec1fc6566b9d032a240a5341e2c3
Page sizes are now properly saved to PDF.
diff --git a/controllers/main.py b/controllers/main.py index 59ff452..a590b26 100644 --- a/controllers/main.py +++ b/controllers/main.py @@ -53,750 +53,756 @@ class MainController(Controller): application.get_preferences_model().register_observer(self) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ self.adapt('show_toolbar', 'show_toolbar_menu_item') self.adapt('show_statusbar', 'show_statusbar_menu_item') self.adapt('show_thumbnails', 'show_thumbnails_menu_item') self.adapt('show_adjustments', 'show_adjustments_menu_item') self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS # Menu Items def on_scan_window_destroy(self, window): """Exits the application.""" self.quit() def on_scan_menu_item_activate(self, menu_item): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_menu_item_activate(self, menu_item): """Refresh the list of connected scanners from SANE.""" self._update_available_scanners() def on_save_as_menu_item_activate(self, menu_item): """Saves the current document to a file.""" self.application.show_save_dialog() def on_delete_menu_item_activate(self, menu_item): self.application.get_document_controller().delete_selected() def on_preferences_menu_item_activate(self, menu_item): """Creates and displays a preferences dialog.""" self.application.show_preferences_dialog() def on_quit_menu_item_activate(self, menu_item): """Exits the application.""" self.quit() def on_zoom_in_menu_item_activate(self, menu_item): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_menu_item_activate(self, menu_item): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_menu_item_activate(self, menu_item): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_menu_item_activate(self, menu_item): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_available_scanner_menu_item_toggled(self, menu_item): """ Set the active scanner. TODO: Need a second scanner to properly test this... """ main_model = self.application.get_main_model() if menu_item.get_active(): for scanner in main_model.available_scanners: if scanner.display_name == menu_item.get_children()[0].get_text(): main_model.active_scanner = scanner return def on_valid_mode_menu_item_toggled(self, menu_item): """Sets the active scan mode.""" if menu_item.get_active(): self.application.get_main_model().active_mode = \ menu_item.get_children()[0].get_text() def on_valid_resolution_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_resolution = \ menu_item.get_children()[0].get_text() def on_valid_page_size_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_page_size = \ menu_item.get_children()[0].get_text() def on_go_first_menu_item_activate(self, menu_item): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_menu_item_activate(self, menu_item): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_menu_item_activate(self, menu_item): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_menu_item_activate(self, menu_item): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() def on_contents_menu_item_clicked(self, menu_item): """TODO""" pass def on_about_menu_item_activate(self, menu_item): """Show the about dialog.""" self.application.show_about_dialog() # Toolbar Buttons def on_scan_button_clicked(self, button): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_button_clicked(self, button): self._update_available_scanners() def on_save_as_button_clicked(self, button): """Saves the current document to a file.""" self.application.show_save_dialog() def on_zoom_in_button_clicked(self, button): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_button_clicked(self, button): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_button_clicked(self, button): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_button_clicked(self, button): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_go_first_button_clicked(self, button): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_button_clicked(self, button): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_button_clicked(self, button): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_button_clicked(self, button): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() # Progress Window INTERFACE CALLBACKS def on_progress_window_delete_event(self, window, event): """ Emulate clicking of the cancel/close button and then hide the window. """ main_view = self.application.get_main_view() self.on_scan_cancel_button_clicked(None) main_view['progress_window'].hide() return True def on_scan_cancel_button_clicked(self, button): """ Cancel the current scan or, if the scan is finished, close the progress window. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress: assert self.cancel_event self.cancel_event.set() else: main_view['progress_window'].hide() def on_scan_again_button_clicked(self, button): """Initiate a new scan from the progress window.""" self._scan() def on_quick_save_button_clicked(self, button): """ Show the save dialog. If the user completes a save then disable the quick save button until another page is scanned. """ main_view = self.application.get_main_view() document_model = self.application.get_document_model() self.application.show_save_dialog() if document_model.count == 0: main_view['quick_save_button'].set_sensitive(False) # MainModel PROPERTY CALLBACKS def property_show_toolbar_value_change(self, model, old_value, new_value): """Update the visibility of the toolbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_toolbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['main_toolbar'].show() else: main_view['main_toolbar'].hide() def property_show_statusbar_value_change(self, model, old_value, new_value): """Update the visibility of the statusbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_statusbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['status_view_docking_viewport'].show() else: main_view['status_view_docking_viewport'].hide() def property_show_thumbnails_value_change(self, model, old_value, new_value): """Update the visibility of the thumbnails.""" main_view = self.application.get_main_view() menu_item = main_view['show_thumbnails_menu_item'] menu_item.set_active(new_value) self.application.get_document_controller().toggle_thumbnails_visible(new_value) def property_show_adjustments_value_change(self, model, old_value, new_value): """Update the visibility of the adjustments controls.""" document_controller = self.application.get_document_controller() main_view = self.application.get_main_view() menu_item = main_view['show_adjustments_menu_item'] menu_item.set_active(new_value) document_controller.toggle_adjustments_visible(new_value) def property_active_scanner_value_change(self, model, old_value, new_value): """ Update the menu and valid scanner options to match the new device. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() if new_value == None: return for menu_item in main_view['scanner_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value.display_name: menu_item.set_active(True) break def property_active_mode_value_change(self, model, old_value, new_value): """Select the active mode from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_mode_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_resolution_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_resolution_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_page_size_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_page_size_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_available_scanners_value_change(self, model, old_value, new_value): """ Update the menu of available scanners. """ main_view = self.application.get_main_view() self._clear_available_scanners_sub_menu() # Generate the new menu if len(new_value) == 0: menu_item = gtk.MenuItem('No Scanners Connected') menu_item.set_sensitive(False) main_view['scanner_sub_menu'].append(menu_item) else: first_item = None for i in range(len(new_value)): # The first menu item defines the group if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i].display_name) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i].display_name) main_view['scanner_sub_menu'].append(menu_item) main_view['scanner_sub_menu'].show_all() def property_valid_modes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan modes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_modes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Modes") menu_item.set_sensitive(False) main_view['scan_mode_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled) main_view['scan_mode_sub_menu'].append(menu_item) main_view['scan_mode_sub_menu'].show_all() def property_valid_resolutions_value_change(self, model, old_value, new_value): """ Updates the list of valid scan resolutions for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_resolutions_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Resolutions") menu_item.set_sensitive(False) main_view['scan_resolution_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled) main_view['scan_resolution_sub_menu'].append(menu_item) main_view['scan_resolution_sub_menu'].show_all() def property_valid_page_sizes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan page sizes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_page_sizes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Page Sizes") menu_item.set_sensitive(False) main_view['scan_page_size_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_page_size_menu_item_toggled) main_view['scan_page_size_sub_menu'].append(menu_item) main_view['scan_page_size_sub_menu'].show_all() def property_scan_in_progress_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() def property_updating_available_scanners_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() # DocumentModel PROPERTY CALLBACKS def property_count_value_change(self, model, old_value, new_value): """Toggle available controls.""" self._toggle_document_controls() # PreferencesModel PROPERTY CALLBACKS def property_toolbar_style_value_change(self, model, old_value, new_value): """Toggle available controls.""" main_view = self.application.get_main_view() if new_value == 'System Default': # TODO - reset style to system default pass else: main_view['main_toolbar'].set_style(constants.TOOLBAR_STYLES[new_value]) # THREAD CALLBACKS def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned): main_view = self.application.get_main_view() short_bytes_scanned = float(bytes_scanned) / 1000 short_total_bytes = float(scan_info.total_bytes) / 1000 main_view['scan_progressbar'].set_fraction( float(bytes_scanned) / scan_info.total_bytes) main_view['scan_progressbar'].set_text( 'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes)) # TODO: multi page scans main_view['progress_secondary_label'].set_markup( '<i>Scanning page.</i>') def on_scan_succeeded(self, scanning_thread, pil_image): """ Append the new page to the current document. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['scan_progressbar'].set_fraction(1) main_view['scan_progressbar'].set_text('Scan complete') main_view['progress_secondary_label'].set_markup( '<i>Adding page to document.</i>') gtk.gdk.flush() - new_page = PageModel(self.application, pil_image, int(main_model.active_resolution)) + new_page = PageModel( + self.application, + pil_image, + int(main_model.active_resolution), + main_model.active_page_size) self.application.get_document_model().append(new_page) main_view['progress_secondary_label'].set_markup( '<i>Page added.</i>') main_view['scan_again_button'].set_sensitive(True) main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_failed(self, scanning_thread, reason): """ Set that scan is complete. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['progress_secondary_label'].set_markup( '<i>%s</i>' % reason) main_view['scan_again_button'].set_sensitive(True) if self.application.get_document_model().count > 0: main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_aborted(self, scanning_thread, exc_info): """ Change display to indicate that scanning failed and convey the to the user the reason why the thread aborted. If the failure was from a SANE exception then give the user the option to blacklist the device. If not, then reraise the error and let the sys.excepthook deal with it. """ self.on_scan_failed(scanning_thread, 'An error occurred.') if isinstance(exc_info[1], saneme.SaneError): self.run_device_exception_dialog(exc_info) else: raise exc_info[0], exc_info[1], exc_info[2] def on_update_available_scanners_thread_finished(self, update_thread, scanner_list): """Set the new list of available scanners.""" main_model = self.application.get_main_model() main_model.available_scanners = scanner_list main_model.updating_available_scanners = False def on_update_available_scanners_thread_aborted(self, update_thread, exc_info): """ Change the display to indicate that no scanners are available and reraise the exception so that it can be caught by the sys.excepthook. There is no reason to handle these cases with a special dialog, if the application failed to even enumerate the available devices then no other action will be possible. This should be fantastically rare. """ self.on_update_available_scanners_thread_finished(update_thread, []) raise exc_info[0], exc_info[1], exc_info[2] # PUBLIC METHODS def quit(self): """Exits the application.""" self.log.debug('Quit.') gtk.main_quit() def run_device_exception_dialog(self, exc_info): """ Display an error dialog that provides the user with the option of blacklisting the device which caused the error. TODO: Move into MainView. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() preferences_model = self.application.get_preferences_model() response = main_view.run_device_exception_dialog(exc_info) if response == constants.RESPONSE_BLACKLIST_DEVICE: temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(exc_info[1].device.display_name) temp_blacklist.sort() preferences_model.blacklisted_scanners = temp_blacklist # PRIVATE METHODS def _clear_available_scanners_sub_menu(self): """Clear the menu of available scanners.""" main_view = self.application.get_main_view() for child in main_view['scanner_sub_menu'].get_children(): main_view['scanner_sub_menu'].remove(child) def _clear_scan_modes_sub_menu(self): """Clear the menu of valid scan modes.""" main_view = self.application.get_main_view() for child in main_view['scan_mode_sub_menu'].get_children(): main_view['scan_mode_sub_menu'].remove(child) def _clear_scan_resolutions_sub_menu(self): """Clear the menu of valid scan resolutions.""" main_view = self.application.get_main_view() for child in main_view['scan_resolution_sub_menu'].get_children(): main_view['scan_resolution_sub_menu'].remove(child) def _clear_scan_page_sizes_sub_menu(self): """Clear the menu of valid scan page sizes.""" main_view = self.application.get_main_view() for child in main_view['scan_page_size_sub_menu'].get_children(): main_view['scan_page_size_sub_menu'].remove(child) def _toggle_scan_controls(self): """Toggle whether or not the scan controls or accessible.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_scan_controls_sensitive(False) main_view.set_refresh_scanner_controls_sensitive(False) else: if main_model.active_scanner != None: main_view.set_scan_controls_sensitive(True) main_view.set_refresh_scanner_controls_sensitive(True) def _toggle_document_controls(self): """ Toggle available document controls based on the current scanner status and the number of scanned pages. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() # Disable all controls when the scanner is in use if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: count = self.application.get_document_model().count # Disable all controls if no pages are scanned if count == 0: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: # Enable most controls if any pages scanned main_view.set_file_controls_sensitive(True) main_view.set_delete_controls_sensitive(True) main_view.set_zoom_controls_sensitive(True) main_view.set_adjustment_controls_sensitive(True) # Only enable navigation if more than one page scanned if count > 1: main_view.set_navigation_controls_sensitive(True) else: main_view.set_navigation_controls_sensitive(False) def _update_status(self): """ Update the text of the statusbar based on the current state of the application. """ main_model = self.application.get_main_model() status_controller = self.application.get_status_controller() status_controller.pop(self.status_context) if main_model.scan_in_progress: status_controller.push(self.status_context, 'Scanning...') elif main_model.updating_available_scanners: status_controller.push(self.status_context, 'Querying hardware...') else: if main_model.active_scanner: status_controller.push(self.status_context, 'Ready with %s.' % main_model.active_scanner.display_name) else: status_controller.push(self.status_context, 'No scanner available.') def _scan(self): """Begin a scan.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() main_model.scan_in_progress = True scanning_thread = ScanningThread(main_model.active_scanner) scanning_thread.connect("progress", self.on_scan_progress) scanning_thread.connect("succeeded", self.on_scan_succeeded) scanning_thread.connect("failed", self.on_scan_failed) scanning_thread.connect("aborted", self.on_scan_aborted) self.cancel_event = scanning_thread.cancel_event main_view['progress_primary_label'].set_markup( '<big><b>%s</b></big>' % main_model.active_scanner.display_name) main_view['scan_progressbar'].set_fraction(0) main_view['scan_progressbar'].set_text('Waiting for data') main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>') mode = main_model.active_mode if main_model.active_mode else 'Not set' main_view['progress_mode_label'].set_markup(mode) dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set' main_view['progress_resolution_label'].set_markup(dpi) + page_size = '%s' % main_model.active_page_size if main_model.active_page_size else 'Not set' + main_view['progress_page_size_label'].set_markup(page_size) main_view['scan_again_button'].set_sensitive(False) main_view['quick_save_button'].set_sensitive(False) main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL) main_view['progress_window'].show_all() scanning_thread.start() def _update_available_scanners(self): """ Start a new update thread to query for available scanners. """ sane = self.application.get_sane() main_model = self.application.get_main_model() main_model.updating_available_scanners = True update_thread = UpdateAvailableScannersThread(sane) update_thread.connect("finished", self.on_update_available_scanners_thread_finished) update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted) update_thread.start() \ No newline at end of file diff --git a/controllers/save.py b/controllers/save.py index c0d19d9..9ffd181 100644 --- a/controllers/save.py +++ b/controllers/save.py @@ -1,309 +1,262 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{SaveController}, which manages interaction between the L{SaveModel} and L{SaveView}. """ import logging import os import sys import tempfile import gtk from gtkmvc.controller import Controller import Image, ImageEnhance from reportlab.pdfgen.canvas import Canvas as PdfCanvas from reportlab.lib.pagesizes import landscape, portrait from reportlab.lib.pagesizes import inch as points_per_inch from nostaples import constants import nostaples.utils.gui class SaveController(Controller): """ Manages interaction between the L{SaveModel} and L{SaveView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the SaveController. """ self.application = application Controller.__init__(self, application.get_save_model()) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) preferences_model = self.application.get_preferences_model() save_model = self.application.get_save_model() # Force refresh of keyword list keywords_liststore = view['keywords_entry'].get_liststore() keywords_liststore.clear() for keyword in preferences_model.saved_keywords: keywords_liststore.append([keyword]) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ self.adapt('title', 'title_entry') self.adapt('author', 'author_entry') self.adapt('keywords', 'keywords_entry') self.adapt('show_document_metadata', 'document_metadata_expander') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS def on_title_from_filename_button_clicked(self, button): """ Copy the selected filename to the pdf title property. """ save_view = self.application.get_save_view() title = save_view['save_dialog'].get_filename() if not title: save_view['title_entry'].set_text('') return title = title.split('/')[-1] if title[-4:] == '.pdf': title = title[:-4] save_view['title_entry'].set_text(title) def on_clear_title_button_clicked(self, button): """Clear the title.""" self.application.get_save_model().title = '' def on_clear_author_button_clicked(self, button): """Clear the author.""" self.application.get_save_model().author = '' def on_clear_keywords_button_clicked(self, button): """Clear the keywords.""" self.application.get_save_model().keywords = '' def on_save_dialog_response(self, dialog, response): """ Determine the selected file type and invoke the method that saves that file type. """ save_model = self.application.get_save_model() save_view = self.application.get_save_view() main_view = self.application.get_main_view() save_view['save_dialog'].hide() if response != gtk.RESPONSE_ACCEPT: return main_view['scan_window'].window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH)) nostaples.utils.gui.flush_pending_events() save_model.filename = save_view['save_dialog'].get_filename() filename_filter = save_view['save_dialog'].get_filter() if filename_filter.get_name() == 'PDF Files': if save_model.filename[-4:] != '.pdf': save_model.filename = ''.join([save_model.filename, '.pdf']) self._save_pdf() else: self.log.error('Unknown file type: %s.' % save_model.filename) self._update_saved_keywords() main_view['scan_window'].window.set_cursor(None) save_model.save_path = save_view['save_dialog'].get_current_folder() # PROPERTY CALLBACKS def property_saved_keywords_value_change(self, model, old_value, new_value): """ Update the keywords auto-completion control with the new keywords. """ save_view = self.application.get_save_view() keywords_liststore = save_view['keywords_entry'].get_liststore() keywords_liststore.clear() for keyword in new_value: keywords_liststore.append([keyword]) # PRIVATE METHODS def _save_pdf(self): """ Output the current document to a PDF file using ReportLab. """ save_model = self.application.get_save_model() save_view = self.application.get_save_view() document_model = self.application.get_document_model() # TODO: seperate saving code into its own thread? # Setup output pdf pdf = PdfCanvas(save_model.filename) pdf.setTitle(save_model.title) pdf.setAuthor(save_model.author) pdf.setKeywords(save_model.keywords) # Generate pages page_iter = document_model.get_iter_first() while page_iter: current_page = document_model.get_value(page_iter, 0) # Write transformed image temp_file_path = ''.join([tempfile.mktemp(), '.bmp']) current_page.pil_image.save(temp_file_path) assert os.path.exists(temp_file_path), \ 'Temporary bitmap file was not created by PIL.' - width_in_inches = \ - int(current_page.width / current_page.resolution) - height_in_inches = \ - int(current_page.height / current_page.resolution) + size = constants.PAGESIZES_INCHES[current_page.page_size] + pdf_width = size[0] * points_per_inch + pdf_height = size[1] * points_per_inch - # NB: Because not all SANE backends support specifying the size - # of the scan area, the best we can do is scan at the default - # setting and then convert that to an appropriate PDF. For the - # vast majority of scanners we hope that this would be either - # letter or A4. - pdf_width, pdf_height = self._determine_best_fitting_pagesize( - width_in_inches, height_in_inches) + # Swizzle width and height if the page has been rotated on its side + if abs(current_page.rotation) % 180 == 90: + pdf_width, pdf_height = pdf_height, pdf_width pdf.setPageSize((pdf_width, pdf_height)) pdf.drawImage( temp_file_path, 0, 0, width=pdf_width, height=pdf_height, preserveAspectRatio=True) pdf.showPage() os.remove(temp_file_path) page_iter = document_model.iter_next(page_iter) # Save complete PDF pdf.save() assert os.path.exists(save_model.filename), \ 'Final PDF file was not created by ReportLab.' document_model.clear() - - def _determine_best_fitting_pagesize(self, width_in_inches, height_in_inches): - """ - Searches through the possible page sizes and finds the smallest one that - will contain the image without cropping. - """ - image_width_in_points = width_in_inches * points_per_inch - image_height_in_points = height_in_inches * points_per_inch - - nearest_size = None - nearest_distance = sys.maxint - - for size in constants.PAGESIZES.values(): - # Orient the size to match the page - if image_width_in_points > image_height_in_points: - size = landscape(size) - else: - size = portrait(size) - - # Only compare the size if its large enough to contain the entire - # image - if size[0] < image_width_in_points or \ - size[1] < image_height_in_points: - continue - - # Compute distance for comparison - distance = \ - size[0] - image_width_in_points + \ - size[1] - image_height_in_points - - # Save if closer than prior nearest distance - if distance < nearest_distance: - nearest_distance = distance - nearest_size = size - - # Stop searching if a perfect match is found - if nearest_distance == 0: - break - - assert nearest_size != None, 'No nearest size found.' - - return nearest_size def _update_saved_keywords(self): """ Update the saved keywords with any new keywords that have been used. """ preferences_model = self.application.get_preferences_model() save_model = self.application.get_save_model() new_keywords = [] for keyword in save_model.keywords.split(): if keyword not in preferences_model.saved_keywords: new_keywords.append(keyword) if new_keywords: temp_list = [] temp_list.extend(preferences_model.saved_keywords) temp_list.extend(new_keywords) temp_list.sort() preferences_model.saved_keywords = temp_list # PUBLIC METHODS def run(self): """Run the save dialog.""" save_model = self.application.get_save_model() save_view = self.application.get_save_view() status_controller = self.application.get_status_controller() save_view['save_dialog'].set_current_folder(save_model.save_path) save_view['save_dialog'].set_current_name('') status_controller.push(self.status_context, 'Saving...') save_view.run() status_controller.pop(self.status_context) \ No newline at end of file diff --git a/gui/scan_window.glade b/gui/scan_window.glade index eb58c4b..ae6ba03 100644 --- a/gui/scan_window.glade +++ b/gui/scan_window.glade @@ -1,774 +1,774 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> -<!--Generated with glade3 3.4.5 on Tue Mar 31 10:35:43 2009 --> +<!--Generated with glade3 3.4.5 on Tue Mar 31 21:02:30 2009 --> <glade-interface> <widget class="GtkWindow" id="progress_window"> <property name="width_request">400</property> <property name="height_request">200</property> <property name="title" translatable="yes">Scan in progress...</property> <property name="resizable">False</property> <property name="modal">True</property> <property name="window_position">GTK_WIN_POS_CENTER</property> <property name="destroy_with_parent">True</property> <property name="icon_name">scanner</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property> <property name="skip_taskbar_hint">True</property> <property name="skip_pager_hint">True</property> <property name="transient_for">scan_window</property> <signal name="delete_event" handler="on_progress_window_delete_event"/> <child> <widget class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkLabel" id="progress_primary_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">&lt;big&gt;&lt;b&gt;Scan in progress...&lt;/b&gt;&lt;/big&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <widget class="GtkVBox" id="vbox4"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkVBox" id="vbox3"> <property name="visible">True</property> <child> <widget class="GtkHBox" id="hbox2"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="static_mode_label"> <property name="width_request">90</property> <property name="visible">True</property> <property name="xalign">1</property> <property name="label" translatable="yes">&lt;b&gt;Mode:&lt;/b&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkLabel" id="progress_mode_label"> <property name="visible">True</property> <property name="label" translatable="yes">Color</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </widget> </child> <child> <widget class="GtkHBox" id="hbox5"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="static_page_size_label"> <property name="width_request">90</property> <property name="visible">True</property> <property name="xalign">1</property> <property name="label" translatable="yes">&lt;b&gt;Page Size:&lt;/b&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkLabel" id="progress_page_size_label"> <property name="visible">True</property> - <property name="label" translatable="yes">Letter (TODO)</property> + <property name="label" translatable="yes">Letter</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkHBox" id="hbox3"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="static_resolution_label"> <property name="width_request">90</property> <property name="visible">True</property> <property name="xalign">1</property> <property name="label" translatable="yes">&lt;b&gt;Resolution:&lt;/b&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkLabel" id="progress_resolution_label"> <property name="visible">True</property> <property name="label" translatable="yes">150 DPI</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="position">2</property> </packing> </child> </widget> </child> <child> <widget class="GtkVBox" id="vbox4"> <property name="visible">True</property> <child> <widget class="GtkProgressBar" id="scan_progressbar"> <property name="visible">True</property> <property name="show_text">True</property> <property name="text" translatable="yes">X of Y bytes receieved.</property> </widget> <packing> <property name="fill">False</property> </packing> </child> <child> <widget class="GtkLabel" id="progress_secondary_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">&lt;i&gt;Scanning page 1 of Z.&lt;/i&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </widget> </child> <child> <widget class="GtkHBox" id="hbox1"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkButton" id="scan_cancel_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="label" translatable="yes">gtk-cancel</property> <property name="use_stock">True</property> <property name="response_id">0</property> <signal name="clicked" handler="on_scan_cancel_button_clicked"/> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="pack_type">GTK_PACK_END</property> <property name="position">2</property> </packing> </child> <child> - <widget class="GtkButton" id="quick_save_button"> + <widget class="GtkButton" id="scan_again_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="response_id">0</property> - <signal name="clicked" handler="on_quick_save_button_clicked"/> + <signal name="clicked" handler="on_scan_again_button_clicked"/> <child> - <widget class="GtkHBox" id="hbox6"> + <widget class="GtkHBox" id="hbox4"> <property name="visible">True</property> <child> - <widget class="GtkImage" id="image2"> + <widget class="GtkImage" id="image1"> <property name="visible">True</property> - <property name="stock">gtk-save-as</property> + <property name="icon_name">scanner</property> </widget> </child> <child> - <widget class="GtkLabel" id="label2"> + <widget class="GtkLabel" id="label1"> <property name="visible">True</property> - <property name="label" translatable="yes">Quick Save</property> + <property name="label" translatable="yes">Scan Again</property> + <property name="use_markup">True</property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> </child> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="pack_type">GTK_PACK_END</property> <property name="position">1</property> </packing> </child> <child> - <widget class="GtkButton" id="scan_again_button"> + <widget class="GtkButton" id="quick_save_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="response_id">0</property> - <signal name="clicked" handler="on_scan_again_button_clicked"/> + <signal name="clicked" handler="on_quick_save_button_clicked"/> <child> - <widget class="GtkHBox" id="hbox4"> + <widget class="GtkHBox" id="hbox6"> <property name="visible">True</property> <child> - <widget class="GtkImage" id="image1"> + <widget class="GtkImage" id="image2"> <property name="visible">True</property> - <property name="icon_name">scanner</property> + <property name="stock">gtk-save-as</property> </widget> </child> <child> - <widget class="GtkLabel" id="label1"> + <widget class="GtkLabel" id="label2"> <property name="visible">True</property> - <property name="label" translatable="yes">Scan Again</property> - <property name="use_markup">True</property> + <property name="label" translatable="yes">Quick Save</property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> </child> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="pack_type">GTK_PACK_END</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </widget> </child> </widget> </child> </widget> <widget class="GtkWindow" id="scan_window"> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="title" translatable="yes">NoStaples</property> <property name="window_position">GTK_WIN_POS_CENTER</property> <property name="default_width">600</property> <property name="default_height">400</property> <signal name="destroy" handler="on_scan_window_destroy"/> <signal name="size_allocate" handler="on_scan_window_size_allocate"/> <child> <widget class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <child> <widget class="GtkMenuBar" id="menubar1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <child> <widget class="GtkMenuItem" id="menuitem1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">_File</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <child> <widget class="GtkImageMenuItem" id="scan_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">S_can</property> <property name="use_underline">True</property> <signal name="activate" handler="on_scan_menu_item_activate"/> <child internal-child="image"> <widget class="GtkImage" id="menu-item-image2"> <property name="visible">True</property> <property name="icon_name">scanner</property> </widget> </child> </widget> </child> <child> <widget class="GtkImageMenuItem" id="refresh_available_scanners_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">Refresh Available Scanners</property> <property name="use_underline">True</property> <signal name="activate" handler="on_refresh_available_scanners_menu_item_activate"/> <child internal-child="image"> <widget class="GtkImage" id="menu-item-image4"> <property name="stock">gtk-refresh</property> </widget> </child> </widget> </child> <child> <widget class="GtkSeparatorMenuItem" id="separatormenuitem7"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> </widget> </child> <child> <widget class="GtkImageMenuItem" id="save_as_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">Save _As...</property> <property name="use_underline">True</property> <signal name="activate" handler="on_save_as_menu_item_activate"/> <accelerator key="S" modifiers="GDK_CONTROL_MASK" signal="activate"/> <child internal-child="image"> <widget class="GtkImage" id="menu-item-image1"> <property name="stock">gtk-save-as</property> </widget> </child> </widget> </child> <child> <widget class="GtkSeparatorMenuItem" id="separatormenuitem1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> </widget> </child> <child> <widget class="GtkImageMenuItem" id="quit_menu_item"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">gtk-quit</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_quit_menu_item_activate"/> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="menuitem2"> <property name="visible">True</property> <property name="label" translatable="yes">_Edit</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu4"> <property name="visible">True</property> <child> <widget class="GtkImageMenuItem" id="delete_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-delete</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_delete_menu_item_activate"/> <accelerator key="Delete" modifiers="" signal="activate"/> </widget> </child> <child> <widget class="GtkSeparatorMenuItem" id="separatormenuitem4"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> </widget> </child> <child> <widget class="GtkImageMenuItem" id="preferences_menu_item"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">gtk-preferences</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_preferences_menu_item_activate"/> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="view_menu"> <property name="visible">True</property> <property name="label" translatable="yes">_View</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu2"> <property name="visible">True</property> <child> <widget class="GtkCheckMenuItem" id="show_toolbar_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Toolbar</property> <property name="use_underline">True</property> <property name="active">True</property> <signal name="toggled" handler="on_show_toolbar_menu_item_toggled"/> </widget> </child> <child> <widget class="GtkCheckMenuItem" id="show_statusbar_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Statusbar</property> <property name="use_underline">True</property> <property name="active">True</property> <signal name="toggled" handler="on_show_statusbar_menu_item_toggled"/> </widget> </child> <child> <widget class="GtkCheckMenuItem" id="show_thumbnails_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">Thumb_nails</property> <property name="use_underline">True</property> <property name="active">True</property> <signal name="toggled" handler="on_show_thumbnails_menu_item_toggled"/> </widget> </child> <child> <widget class="GtkCheckMenuItem" id="show_adjustments_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Adjustments</property> <property name="use_underline">True</property> <signal name="toggled" handler="on_show_adjustments_menu_item_toggled"/> </widget> </child> <child> <widget class="GtkSeparatorMenuItem" id="separatormenuitem5"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> </widget> </child> <child> <widget class="GtkImageMenuItem" id="zoom_in_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-zoom-in</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_zoom_in_menu_item_activate"/> <accelerator key="plus" modifiers="GDK_CONTROL_MASK" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="zoom_out_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-zoom-out</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_zoom_out_menu_item_activate"/> <accelerator key="minus" modifiers="GDK_CONTROL_MASK" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="zoom_one_to_one_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-zoom-100</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_zoom_one_to_one_menu_item_activate"/> <accelerator key="1" modifiers="GDK_CONTROL_MASK" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="zoom_best_fit_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-zoom-fit</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_zoom_best_fit_menu_item_activate"/> <accelerator key="F" modifiers="GDK_CONTROL_MASK" signal="activate"/> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="menuitem9"> <property name="visible">True</property> <property name="label" translatable="yes">_Tools</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu6"> <property name="visible">True</property> <child> <widget class="GtkMenuItem" id="rotate_clockwise_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Rotate Clockwise</property> <property name="use_underline">True</property> <signal name="activate" handler="on_rotate_clockwise_menu_item_activate"/> </widget> </child> <child> <widget class="GtkMenuItem" id="rotate_counter_clockwise_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">Rotate _Counterclockwise</property> <property name="use_underline">True</property> <signal name="activate" handler="on_rotate_counter_clockwise_menu_item_activate"/> </widget> </child> <child> <widget class="GtkCheckMenuItem" id="rotate_all_pages_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">Apply rotation to all _pages?</property> <property name="use_underline">True</property> <signal name="toggled" handler="on_rotate_all_pages_menu_item_toggled"/> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="options_menu"> <property name="visible">True</property> <property name="label" translatable="yes">_Options</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu7"> <property name="visible">True</property> <child> <widget class="GtkMenuItem" id="scanner_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Scanner</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="scanner_sub_menu"> <property name="visible">True</property> <child> <widget class="GtkMenuItem" id="menuitem5"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="label" translatable="yes">None</property> <property name="use_underline">True</property> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="scan_mode_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Mode</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="scan_mode_sub_menu"> <property name="visible">True</property> <child> <widget class="GtkMenuItem" id="menuitem8"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="label" translatable="yes">None</property> <property name="use_underline">True</property> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="scan_resolution_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Resolution</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="scan_resolution_sub_menu"> <property name="visible">True</property> <child> <widget class="GtkMenuItem" id="menuitem10"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="label" translatable="yes">None</property> <property name="use_underline">True</property> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="scan_page_size_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Page Size</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="scan_page_size_sub_menu"> <property name="visible">True</property> <child> <widget class="GtkMenuItem" id="menuitem7"> <property name="visible">True</property> <property name="label" translatable="yes">None</property> <property name="use_underline">True</property> </widget> </child> </widget> </child> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="menuitem3"> <property name="visible">True</property> <property name="label" translatable="yes">_Go</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu5"> <property name="visible">True</property> <child> <widget class="GtkImageMenuItem" id="go_first_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-goto-first</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_go_first_menu_item_activate"/> <accelerator key="Home" modifiers="" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="go_previous_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-go-back</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_go_previous_menu_item_activate"/> <accelerator key="Left" modifiers="GDK_MOD1_MASK" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="go_next_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-go-forward</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_go_next_menu_item_activate"/> <accelerator key="Right" modifiers="GDK_MOD1_MASK" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="go_last_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-goto-last</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_go_last_menu_item_activate"/> <accelerator key="End" modifiers="" signal="activate"/> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="menuitem4"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">_Help</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu3"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <child> <widget class="GtkImageMenuItem" id="contents_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Contents</property> <property name="use_underline">True</property> <accelerator key="F1" modifiers="" signal="activate"/> <child internal-child="image"> <widget class="GtkImage" id="menu-item-image3"> <property name="visible">True</property> <property name="stock">gtk-help</property> </widget> </child> </widget> </child> <child> <widget class="GtkImageMenuItem" id="about_menu_item"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">gtk-about</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_about_menu_item_activate"/> </widget> </child> </widget> </child> </widget> </child> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkToolbar" id="main_toolbar"> <property name="visible">True</property> <property name="icon_size">GTK_ICON_SIZE_SMALL_TOOLBAR</property> <child> <widget class="GtkToolButton" id="scan_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Scan</property> <property name="label" translatable="yes">Scan</property> <property name="icon_name">scanner</property> <signal name="clicked" handler="on_scan_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="refresh_available_scanners_button"> <property name="visible">True</property> <property name="label" translatable="yes">Refresh Available Scanners</property> <property name="stock_id">gtk-refresh</property> <signal name="clicked" handler="on_refresh_available_scanners_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="save_as_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Save As...</property> <property name="label" translatable="yes">Save As</property> <property name="icon_name">document-save-as</property> <signal name="clicked" handler="on_save_as_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> diff --git a/models/page.py b/models/page.py index 30cd3b2..f18711a 100644 --- a/models/page.py +++ b/models/page.py @@ -1,226 +1,230 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the PageModel, which represents a single scanned page. """ import logging import gtk from gtkmvc.model import Model import Image, ImageEnhance from nostaples import constants from nostaples.utils.graphics import * class PageModel(Model): """ Represents a single scanned page. """ __properties__ = \ { '_raw_pil_image' : None, 'rotation' : 0, 'brightness' : 1.0, 'contrast' : 1.0, 'sharpness' : 1.0, - 'resolution' : 75, + 'resolution' : constants.DEFAULT_SCAN_RESOLUTION, + 'page_size' : constants.DEFAULT_PAGE_SIZE, 'pil_image' : None, 'pixbuf' : None, 'thumbnail_pixbuf': None, } # SETUP METHODS - def __init__(self, application, pil_image=None, resolution=75): + def __init__(self, application, pil_image=None, resolution=constants.DEFAULT_SCAN_RESOLUTION, page_size=constants.DEFAULT_PAGE_SIZE): """ Constructs the PageModel. @type pil_image: a PIL image @param pil_image: The image data for this page. + @type page_size: str + @param page_size: The name of the page size this image should be saved + in. @type resolution: int - @param resolution: The dpi that the page was - scanned at. + @param resolution: The dpi that the page was scanned at. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.resolution = resolution + self.page_size = page_size if pil_image: self._raw_pil_image = pil_image self._update_pixbuf() self._update_thumbnail_pixbuf() self.register_observer(self) # TODO: Wtf am I doing here, solves a bug, but why? self.accepts_spurious_change = lambda : True self.log.debug('Created.') # COMPUTED PROPERTIES @property def width(self): """ Gets the width of the page after transformations have been applied. """ return self.pixbuf.get_width() @property def height(self): """ Gets the height of the page after transformations have been applied. """ return self.pixbuf.get_height() # PROPERTY CALLBACKS def property_rotation_value_change(self, model, old_value, new_value): """Updates the full and thumbnail pixbufs.""" self._update_pixbuf() self._update_thumbnail_pixbuf() def property_brightness_value_change(self, model, old_value, new_value): """Updates the full and thumbnail pixbufs.""" self._update_pixbuf() self._update_thumbnail_pixbuf() def property_contrast_value_change(self, model, old_value, new_value): """Updates the full and thumbnail pixbufs.""" self._update_pixbuf() self._update_thumbnail_pixbuf() def property_sharpness_value_change(self, model, old_value, new_value): """Updates the full and thumbnail pixbufs.""" self._update_pixbuf() self._update_thumbnail_pixbuf() # PUBLIC METHODS def rotate_counter_clockwise(self): """ Rotate this page ninety degrees counter-clockwise. """ self.rotation += 90 def rotate_clockwise(self): """ Rotate this page ninety degrees clockwise. """ self.rotation -= 90 def set_adjustments(self, brightness, contrast, sharpness): """ Sets all three adjustment values in one method without triggering each property callback. This prevents the pixbuf and thumbnail from being update multiple times. """ if (self.__properties__['brightness'] == brightness and self.__properties__['contrast'] == contrast and self.__properties__['sharpness'] == sharpness): return self.__properties__['brightness'] = brightness self.__properties__['contrast'] = contrast self.__properties__['sharpness'] = sharpness self._update_pixbuf() self._update_thumbnail_pixbuf() # PRIVATE METHODS def _update_pixbuf(self): """ Creates a full-size pixbuf of the scanned image with all transformations applied. """ image = self._raw_pil_image if self.brightness != 1.0: image = ImageEnhance.Brightness(image).enhance( self.brightness) if self.contrast != 1.0: image = ImageEnhance.Contrast(image).enhance( self.contrast) if self.sharpness != 1.0: image = ImageEnhance.Sharpness(image).enhance( self.sharpness) if abs(self.rotation % 360) == 90: image = image.transpose(Image.ROTATE_90) elif abs(self.rotation % 360) == 180: image = image.transpose(Image.ROTATE_180) elif abs(self.rotation % 360) == 270: image = image.transpose(Image.ROTATE_270) self.pil_image = image self.pixbuf = convert_pil_image_to_pixbuf(image) def _update_thumbnail_pixbuf(self): """ Creates a thumbnail image with all transformations applied. """ preferences_model = self.application.get_preferences_model() image = self._raw_pil_image if self.brightness != 1.0: image = ImageEnhance.Brightness(image).enhance( self.brightness) if self.contrast != 1.0: image = ImageEnhance.Contrast(image).enhance( self.contrast) if self.sharpness != 1.0: image = ImageEnhance.Sharpness(image).enhance( self.sharpness) if abs(self.rotation % 360) == 90: image = image.transpose(Image.ROTATE_90) elif abs(self.rotation % 360) == 180: image = image.transpose(Image.ROTATE_180) elif abs(self.rotation % 360) == 270: image = image.transpose(Image.ROTATE_270) width, height = image.size thumbnail_size = preferences_model.thumbnail_size width_ratio = float(width) / thumbnail_size height_ratio = float(height) / thumbnail_size if width_ratio < height_ratio: zoom = 1 / float(height_ratio) else: zoom = 1 / float(width_ratio) target_width = int(width * zoom) target_height = int(height * zoom) image = image.resize( (target_width, target_height), constants.THUMBNAILS_SCALING_MODE) self.thumbnail_pixbuf = convert_pil_image_to_pixbuf(image) \ No newline at end of file
onyxfish/nostaples
65c22a4a815f4528179d9f5eaabc6cd0fd7a23d3
Reviewed page size support for quality.
diff --git a/models/main.py b/models/main.py index f226a56..84e6a58 100644 --- a/models/main.py +++ b/models/main.py @@ -1,819 +1,834 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme from nostaples.utils import properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'active_page_size' : None, 'available_scanners' : [], # [] of saneme.Device 'unavailable_scanners' : [], # [] of (saneme.Device.display_name, reason) tuples 'valid_modes' : [], 'valid_resolutions' : [], 'valid_page_sizes' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) self.active_page_size = state_manager.init_state( 'page_size', constants.DEFAULT_PAGE_SIZE, self.state_page_size_change) # PROPERTY SETTERS set_prop_show_toolbar = properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it's option constraints can be queried without error. if value is not None: # Verify that the proper type is being set assert isinstance(value, saneme.Device) # Open the new scanner try: self.log.debug( 'Setting active scanner to %s.' % value.display_name) value.open() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Get valid options from the new device and then reset the # previous options if they exist on the new device self._update_valid_modes() self.active_mode = self.active_mode self._update_valid_resolutions() self.active_resolution = self.active_resolution self._update_valid_page_sizes() self.active_page_size = self.active_page_size # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notifications self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_mode = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value self.log.debug( 'Setting active mode to %s.' % value) self.active_scanner.options['mode'].value = value except saneme.SaneInexactValueError: raise except saneme.SaneReloadOptionsError: # Reload any options that may have changed, this will # also force this value to be set again, so its safe to # return immediately self._reload_scanner_options() return # Never persist None to state if value is not None: self.application.get_state_manager()['scan_mode'] = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() - + # Set new property value self._prop_active_resolution = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value self.log.debug( 'Setting active resolution to %s.' % value) self.active_scanner.options['resolution'].value = int(value) except saneme.SaneInexactValueError: raise except saneme.SaneReloadOptionsError: # Reload any options that may have changed, this will # also force this value to be set again, so its safe to # return immediately self._reload_scanner_options() return - - # Update available page sizes if resolution is relevant - if self.active_scanner.options['tl-x'].constraint_type == \ - saneme.OPTION_UNIT_PIXEL: - self._update_valid_page_sizes() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_resolution'] = value # Emit change notification self.notify_property_value_change( 'active_resolution', None, value) def set_prop_active_page_size(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_page_size = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() - # Store the current scanner value for comparison + # Get the scan area options try: - tl_x = self.active_scanner.options['tl-x'].value - tl_y = self.active_scanner.options['tl-y'].value - br_x = self.active_scanner.options['br-x'].value - br_y = self.active_scanner.options['br-y'].value + tl_x = self.active_scanner.options['tl-x'] + tl_y = self.active_scanner.options['tl-y'] + br_x = self.active_scanner.options['br-x'] + br_y = self.active_scanner.options['br-y'] + + min_x = tl_x.constraint[0] + min_y = tl_y.constraint[0] except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) - # Never re-set a value or set None to a device option + # Never set None to a device option + # (it is safe to re-set these option values) if value is not None: if self.active_scanner.options['tl-x'].unit == saneme.OPTION_UNIT_PIXEL: - # TODO - if self.valid_resolutions == None: - raise AssertionError() - + # If there are no resolutions, then there should be no + # page sizes to set. + if len(self.valid_resolutions) == 0: + raise AssertionError( + 'Pixel-based page size being set when no valid resolutions are available.') + resolution = max([int(i) for i in self.valid_resolutions]) page_width = int(resolution * constants.PAGESIZES_INCHES[value][0]) page_height = int(resolution * constants.PAGESIZES_INCHES[value][1]) else: page_width = constants.PAGESIZES_MM[value][0] page_height = constants.PAGESIZES_MM[value][1] - needs_reload = False + # Set the new option value + self.log.debug( + 'Setting active page size to %s.' % value) - if br_x - tl_x != page_width and br_y - tl_y != page_height: - try: - # Set the new option value - self.log.debug( - 'Setting active page size to %s.' % value) - - self.active_scanner.options['br-x'].value = tl_x + page_width - except saneme.SaneInexactValueError: - # Coordinate may often be inexact due to backend - # rounding/quantization. Nothing needs to be done - # about this since the exact coordinates that have - # been set are stored locally. - pass - except saneme.SaneReloadOptionsError: - # Reload after other coordinates have been set. - needs_reload == True + needs_reload = False + + try: + self.active_scanner.options['tl-x'].value = min_x + except saneme.SaneInexactValueError: + # See below + pass + except saneme.SaneReloadOptionsError: + # See below + needs_reload == True + + try: + self.active_scanner.options['tl-y'].value = min_y + except saneme.SaneInexactValueError: + # See below + pass + except saneme.SaneReloadOptionsError: + # See below + needs_reload == True - try: - # Set the new option value - self.log.debug( - 'Setting active page size to %s.' % value) - - self.active_scanner.options['br-y'].value = tl_y + page_height - except saneme.SaneInexactValueError: - # See above - pass - except saneme.SaneReloadOptionsError: - # See above - needs_reload == True - - if needs_reload: - # Reload any options that may have changed, this will - # also force this value to be set again, so its safe to - # return immediately - self._reload_scanner_options() - return + try: + self.active_scanner.options['br-x'].value = \ + min_x + page_width + except saneme.SaneInexactValueError: + # Coordinate may often be inexact due to backend + # rounding/quantization. Nothing needs to be done + # about this since the exact coordinates that have + # been set are not cached in MainModel. + pass + except saneme.SaneReloadOptionsError: + # Reload after other coordinates have been set. + needs_reload == True + + try: + self.active_scanner.options['br-y'].value = \ + min_y + page_height + except saneme.SaneInexactValueError: + # See above + pass + except saneme.SaneReloadOptionsError: + # See above + needs_reload == True + + if needs_reload: + self._reload_scanner_options() # Never persist None to state if value is not None: self.application.get_state_manager()['page_size'] = value # Emit change notification self.notify_property_value_change( 'active_page_size', None, value) def set_prop_available_scanners(self, value): """ Takes a new list of scanners, removes any which are blacklisted or unsupported, sets the new list, updates the active_scanner, and emits appropriate property callbacks. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() # Remove blacklisted scanners value = \ [scanner for scanner in value if not \ scanner.display_name in preferences_model.blacklisted_scanners] # Remove scanners that do not support necessary options or fail to # open entirely new_unavailable_scanners = [] # TODO - move somewhere more appropriate? unsupported_scanner_error = \ 'Scanner %s is unsupported for the following reason: %s' for scanner in value: try: scanner.open() unsupported = False # Enforce mode option requirements if not scanner.has_option('mode'): reason = 'No \'mode\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue mode = scanner.options['mode'] if not self.is_settable_option(mode): reason = 'Unsettable \'mode\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue if not mode.constraint_type == saneme.OPTION_CONSTRAINT_STRING_LIST: reason = '\'Mode\' option does not include a STRING_LIST constraint.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # Enforce resolution option requirements if not scanner.has_option('resolution'): reason = 'No \'resolution\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue resolution = scanner.options['resolution'] if not self.is_settable_option(resolution): reason = 'Unsettable \'resolution\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue if resolution.constraint_type == saneme.OPTION_CONSTRAINT_NONE: reason = '\'Resolution\' option does not specify a constraint.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # See SANE API 4.5.2 if resolution.type != saneme.OPTION_TYPE_INT and \ resolution.type != saneme.OPTION_TYPE_FLOAT: reason = '\'Resolution\' option is not of type INT or FLOAT.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # See SANE API 4.5.2 if not resolution.unit == saneme.OPTION_UNIT_DPI: reason = '\'Resolution\' option is not measured in DPI units.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # Enforce scan area option requirements scan_area_option_names = ['tl-x', 'tl-y', 'br-x', 'br-y'] supported = True for option_name in scan_area_option_names: if not scanner.has_option(option_name): supported = False if not supported: reason = 'No \'scan area\' options.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue scan_area_options = \ [scanner.options[o] for o in scan_area_option_names] supported = True for option in scan_area_options: if option.type != saneme.OPTION_TYPE_INT: supported = False if not supported: reason = '\'Scan area\' options are not of type INT.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue supported = True for option in scan_area_options: if option.unit != saneme.OPTION_UNIT_PIXEL and \ option.unit != saneme.OPTION_UNIT_MM: supported = False if not supported: reason = '\'Scan area\' options are not measured in unit PIXEL or MM.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue supported = True for option in scan_area_options: if option.constraint_type != saneme.OPTION_CONSTRAINT_RANGE: supported = False if not supported: reason = '\'Scan area\' options do not specify a RANGE constraint.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue scanner.close() except saneme.SaneError: reason = 'Exception raised while attempting to query device options.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue self._prop_unavailable_scanners = new_unavailable_scanners self._prop_available_scanners = value self.notify_property_value_change( 'unavailable_scanners', None, new_unavailable_scanners) self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None elif self._prop_active_scanner not in value: self.active_scanner = value[0] def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) if len(value) == 0: self.active_mode = None elif self.active_mode not in value: self.active_mode = value[0] def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) if len(value) == 0: self.active_resolution = None elif self.active_resolution not in value: self.active_resolution = value[0] def set_prop_valid_page_sizes(self, value): """ Set the list of valid scan page sizes, update the active page size and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_page_sizes = value - + self.notify_property_value_change( 'valid_page_sizes', None, value) if len(value) == 0: self.active_page_size = None elif self.active_page_size not in value: self.active_page_size = value[0] # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution def state_page_size_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_page_size'] in self.valid_page_sizes: self.active_page_size = state_manager['scan_page_size'] else: state_manager['scan_page_size'] = self.active_page_size # INTERNAL METHODS def is_settable_option(self, option): """ Verify an option supports minimum capabilities needed to be used by NoStaples. """ return option.is_active() and \ option.is_soft_gettable() and \ option.is_soft_settable() def _update_valid_modes(self): """ Update valid modes from the active scanner. """ self.valid_modes = self.active_scanner.options['mode'].constraint def _update_valid_resolutions(self): """ Update valid resolutions from the active scanner. """ if self.active_scanner.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_RANGE: min, max, step = self.active_scanner.options['resolution'].constraint # Fix for ticket #34. if step is None or step == 0: step = 1 resolutions = [] # If there are not an excessive number, include every possible # resolution if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: i = min while i <= max: resolutions.append(str(i)) i = i + step # Otherwise, take a crack at building a sensible set of options # that meet that constraint criteria else: # TODO: This is a naive implementation that is likely to # generate an unusuably large number of valid resolutions. i = min tested_resolutions = [] while i <= max: try: self.active_scanner.options['resolution'].value = i except saneme.SANE_INFO_INEXACT: pass except saneme.SANE_INFO_RELOAD_PARAMS: pass tested_resolutions.append( self.active_scanner.options['resolution'].value) i = i + step # Prune duplicates # http://code.activestate.com/recipes/52560/ uniques = {} for j in tested_resolutions: uniques[j] = True resolutions = [str(k) for k in uniques.keys()] self._prop_valid_resolutions = resolutions elif self.active_scanner.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_VALUE_LIST: # Convert values to strings for display self.valid_resolutions = \ [str(i) for i in self.active_scanner.options['resolution'].constraint] elif self.active_scanner.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST: self.valid_resolutions = \ self.active_scanner.options['resolution'].constraint else: raise AssertionError('Unsupported constraint type.') def _update_valid_page_sizes(self): """ - Update valid page sizes from the active scanner. + Update valid page sizes from the active scanner.tl_x + page_width """ - tl_x = self.active_scanner.options['tl-x'] - tl_y = self.active_scanner.options['tl-y'] - br_x = self.active_scanner.options['br-x'] - br_y = self.active_scanner.options['br-y'] + main_controller = self.application.get_main_controller() + + try: + tl_x = self.active_scanner.options['tl-x'] + tl_y = self.active_scanner.options['tl-y'] + br_x = self.active_scanner.options['br-x'] + br_y = self.active_scanner.options['br-y'] + + max_x = br_x.constraint[1] - tl_x.constraint[0] + max_y = br_y.constraint[1] - tl_y.constraint[0] + except saneme.SaneError: + exc_info = sys.exc_info() + main_controller.run_device_exception_dialog(exc_info) new_sizes = [] for size in constants.PAGESIZES_INCHES.iterkeys(): if tl_x.unit == saneme.OPTION_UNIT_PIXEL: - # TODO? - if self.valid_resolutions == None: + if len(self.valid_resolutions) == 0: break resolution = max([int(i) for i in self.valid_resolutions]) - page_width = int(resolution * constants.PAGESIZES_INCHES[size][0]) page_height = int(resolution * constants.PAGESIZES_INCHES[size][1]) - - max_x = br_x.constraint[1] - tl_x.constraint[0] - max_y = br_y.constraint[1] - tl_y.constraint[0] - - if page_width <= max_x and page_height <= max_y: - new_sizes.append(size) elif tl_x.unit == saneme.OPTION_UNIT_MM: page_width = int(constants.PAGESIZES_MM[size][0]) - page_height = int(constants.PAGESIZES_MM[size][1]) - - max_x = br_x.constraint[1] - tl_x.constraint[0] - max_y = br_y.constraint[1] - tl_y.constraint[0] - - if page_width <= max_x and page_height <= max_y: - new_sizes.append(size) + page_height = int(constants.PAGESIZES_MM[size][1]) else: - raise AssertionError() + raise AssertionError( + 'Unknown measurement unit for scan area options.') + + if page_width <= max_x and page_height <= max_y: + new_sizes.append(size) def page_size_sort(x, y): """ Sort paper sizes according to their order in a constant list. """ sort_x = constants.PAGESIZE_SORT_ORDER.index(x) sort_y = constants.PAGESIZE_SORT_ORDER.index(y) if sort_x > sort_y: return 1 elif sort_x == sort_y: return 0 else: return -1 new_sizes.sort(page_size_sort) self.valid_page_sizes = new_sizes def _reload_scanner_options(self): """ Get current scanner options from the active_scanner. - Useful for reloading any option that may have changed in response to - a SaneReloadOptionsError. + Use to reload options in response to a SaneReloadOptionsError. + + IMPORTANT: An empirical review of SANE backends has shown that neither + the constraints nor the values of the scan area options are changed + when the Reload Options flag is set. Also, the backend may change + scan area option values that are set due to quantization/rounding, so + it would be impossible to read the new value and determine the set page + size from that. For these two reasons, updating the active and valid + page sizes is excluded from this method. """ main_controller = self.application.get_main_controller() self.log.debug('Reloading scanner options.') try: # Read updated values from the device new_mode = self.active_scanner.options['mode'].value new_resolution = str(self.active_scanner.options['resolution'].value) - #new_page_size = ??? # Reload valid options self._update_valid_modes() self._update_valid_resolutions() - self._update_valid_page_sizes() # Reset new values (in case they were overwritten) self.active_mode = new_mode self.active_resolution = new_resolution - #self.active_page_size = new_page_size except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) self.log.debug('Scanner options reloaded.') \ No newline at end of file diff --git a/sane/saneme.py b/sane/saneme.py index cfd8ef3..4b53c96 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -1,1012 +1,1012 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module contains the Pythonic implementation of the SANE API. The flat C functions have been wrapped in a set of objects and all ctypes of the underlying implmentation have been hidden from the user's view. This enumerations and definiations which are absolutely necessary to the end user have been redeclared. """ # TODO: document what exceptions can be thrown by each method, # including those that could bubble up from array import * import atexit import ctypes from types import * from PIL import Image from errors import * from saneh import * # Redeclare saneh enumerations which are visible to the application (OPTION_TYPE_BOOL, OPTION_TYPE_INT, # Automatically converted from SANE_TYPE_FIXED OPTION_TYPE_FLOAT, OPTION_TYPE_STRING, OPTION_TYPE_BUTTON, OPTION_TYPE_GROUP) = xrange(6) (OPTION_UNIT_NONE, OPTION_UNIT_PIXEL, OPTION_UNIT_BIT, OPTION_UNIT_MM, OPTION_UNIT_DPI, OPTION_UNIT_PERCENT, OPTION_UNIT_MICROSECOND) = xrange(7) (OPTION_CONSTRAINT_NONE, OPTION_CONSTRAINT_RANGE, OPTION_CONSTRAINT_VALUE_LIST, OPTION_CONSTRAINT_STRING_LIST) = xrange(4) class SaneMe(object): """ The top-level object for interacting with the SANE API. Handles polling for devices. This object should only be instantiated once. """ _log = None _version = None # (major, minor, build) _devices = [] def __init__(self, log=None): """ Create the SANE object, perform setup, and register the cleanup function. @param log: an optional Python logging object to log to. """ self._log = log self._setup() atexit.register(self._shutdown) # Read only properties def __get_version(self): """Get the current installed version of SANE.""" return self._version version = property(__get_version) def _setup(self): """ Iniitalize SANE and retrieve the current installed version. """ version_code = SANE_Int() auth_callback = SANE_Auth_Callback(self._sane_auth_callback) status = sane_init(byref(version_code), auth_callback) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_init returned an invalid status: %i.' % status) self._version = (SANE_VERSION_MAJOR(version_code), SANE_VERSION_MINOR(version_code), SANE_VERSION_BUILD(version_code)) if self._log: self._log.info('SANE version %s initalized.', self._version) def _sane_auth_callback(self, resource, username, password): """ TODO """ raise NotImplementedError( 'sane_auth_callback requested, but not yet implemented.') def _shutdown(self): """ Deinitialize SANE. This code would go in __del__, but it is not guaranteed that method will be called and sane_exit must be called to release resources. To ensure this method is called it is registered with atexit. """ for device in self._devices: if device.is_open(): device.close() sane_exit() self._version = None if self._log: self._log.info('SANE deinitialized.') # Public Methods def get_device_list(self): """ Poll for connected devices. This method may take several seconds to return. Note that SANE is exited and re-inited before querying for devices to workaround a limitation in SANE's USB driver which causes the device list to only be updated on init. This means that all settings applied to all devices will be B{lost} and must be restored by the calling application. This was found documented here: U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html} """ if not self._version: raise AssertionError('version was None') # See docstring for details on this voodoo self._shutdown() self._setup() cdevices = POINTER(POINTER(SANE_Device))() status = sane_get_devices(byref(cdevices), SANE_Bool(0)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_get_devices ran out of memory.') else: raise SaneUnknownError( 'sane_get_devices returned an invalid status: %i.' % status) device_count = 0 self._devices = [] while cdevices[device_count]: self._devices.append( Device(cdevices[device_count].contents, self._log)) device_count += 1 if self._log: self._log.info('SANE queried, %i device(s) found.', device_count) return self._devices def get_device_by_name(self, name): """ Retrieve a L{Device} by name. Must be preceded by a call to L{get_device_list}. """ for device in self._devices: if device.name == name: return device raise SaneNoSuchDeviceError( 'The requested device does not exist.') class Device(object): """ This is the primary object for interacting with SANE. It represents a single device and handles enumeration of options, getting and setting of options, and starting and stopping of scanning jobs. """ _log = None _handle = None _name = '' _vendor = '' _model = '' _type = '' _display_name = '' _options = {} def __init__(self, ctypes_device, log=None): """ Sets the Devices properties from a ctypes SANE_Device and queries for its available options. """ self._log = log # String attributes should never be None self._name = ctypes_device.name if ctypes_device.name else '' self._vendor = ctypes_device.vendor if ctypes_device.vendor else '' self._model = ctypes_device.model if ctypes_device.model else '' self._type = ctypes_device.type if ctypes_device.type else '' self._display_name = ' '.join([self._vendor, self._model]) # Read only properties def __get_name(self): """ Get the complete SANE identifier for this device, e.g. 'lexmark:libusb:002:006'. """ return self._name name = property(__get_name) def __get_vendor(self): """Get the manufacturer of this device, e.g. 'Lexmark'.""" return self._vendor vendor = property(__get_vendor) def __get_model(self): """Get the specific model of this device, e.g. 'X1100/rev. B2'.""" return self._model model = property(__get_model) def __get_type(self): """Get the type of this device, e.g. 'flatbed scanner'.""" return self._type type = property(__get_type) def __get_display_name(self): """ Get an appropriate name to use for displaying this device to a user, e.g. 'Lexmark X1100/rev. B2'.""" return self._display_name display_name = property(__get_display_name) def __get_options(self): """Get the dictionary of options that this device has.""" return self._options options = property(__get_options) # Public methods def open(self): """ Open a new handle to this device. Must be called before any operations (including getting or setting options) are performed on this device. """ if self._handle: raise AssertionError('device handle already exists.') self._handle = SANE_Handle() status = sane_open(self.name, byref(self._handle)) # If and exception will be thrown, nullify device handle # so is_open() will return false for the device. if status != SANE_STATUS_GOOD.value: self._handle = None if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_open reported that the device was busy.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) self._load_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) def has_option(self, option_name): """Return true if option_name is available for this scanner.""" return (option_name in self.options.keys()) def scan(self, progress_callback=None): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater_update_options access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: # Lineart if sane_parameters.depth == 1: pil_image = Image.frombuffer( '1', (scan_info.width, scan_info.height), - data_array, 'raw', '1', 0, 1) + data_array, 'raw', '1;I', 0, 1) # Grayscale elif sane_parameters.depth == 8: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) else: raise AssertionError( 'Unexpected bit depth for monochrome scan format: %i' % sane_parameters.depth) elif sane_parameters.format == SANE_FRAME_RGB.value: # Color pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Internal methods def _load_options(self): """ Update the list of available options for this device. This is called when the Device is first instantiated and in response to any SANE_INFO_RELOAD_OPTIONS flags when setting option values. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') option_value = pointer(c_int()) status = sane_control_option( self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: raise SaneUnsupportedOperationError( 'sane_control_option reported that a value was outside the option\'s constraint.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) option_count = option_value.contents.value if self._log: self._log.debug('Device queried, %i option(s) found.', option_count) self._options.clear() i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) self._options[coption.contents.name] = Option( self, i, coption.contents, self._log) i = i + 1 class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capability = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number # String attributes should never be None self._name = ctypes_option.name if ctypes_option.name else '' self._title = ctypes_option.title if ctypes_option.title else '' self._description = ctypes_option.desc if ctypes_option.desc else '' self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: if self._type == SANE_TYPE_FIXED.value: self._constraint = ( SANE_UNFIX(ctypes_option.constraint.range.contents.min), SANE_UNFIX(ctypes_option.constraint.range.contents.max), SANE_UNFIX(ctypes_option.constraint.range.contents.quant)) else: self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 if self._type == SANE_TYPE_FIXED.value: self._constraint = [SANE_UNFIX(i) for i in self._constraint] elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 if self._type == SANE_TYPE_FIXED.value: self._constraint = [str(SANE_UNFIX(int(i))) for i in self._constraint] else: self._constraint = None # Read only properties def __get_name(self): """ Get the short-form name of this option, e.g. 'mode'. May be an empty string, but never None. """ return self._name name = property(__get_name) def __get_title(self): """ Get the full name of this option, e.g. 'Scan mode'. May be an empty string, but never None. """ return self._title title = property(__get_title) def __get_description(self): """ Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' May be an empty string, but never None. """ return self._description description = property(__get_description) def __get_type(self): """ Get the type of this option, e.g. OPTION_TYPE_STRING. """ return self._type type = property(__get_type) def __get_unit(self): """ Get the unit of this option, e.g.OPTION_UNIT_DPI. """ return self._unit unit = property(__get_unit) def __get_constraint_type(self): """ Get the type of constraint on this option, e.g. OPTION_CONSTRAINT_RANGE. """ return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_VALUE_LIST then this is a list of ints/floats which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """value Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option( handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i.' % status, device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value elif self._type == SANE_TYPE_FIXED.value: option_value = SANE_UNFIX(option_value.value) else: option_value = option_value.contents.value # if self._log: # self._log.debug( # 'Option %s queried, its current value is %s.', # self._name, # option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: raise TypeError( 'option set with %s, expected BooleanType' % type(value)) c_value = pointer(SANE_Bool(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(SANE_Int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType and type(value) is not FloatType: raise TypeError( 'option set with %s, expected IntType or FloatType' % type(value)) c_value = pointer(SANE_Fixed(SANE_FIX(value))) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: raise TypeError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: raise ValueError( 'value for option is longer than max string size') c_value = SANE_String(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: min, max, step = self._constraint if value < min: raise ValueError('value for option is less than min.') if value > max: raise ValueError('value for option is greater than max.') if step is not None and step > 0: # In theory this should be enforced, but in practice it is # useful to sometimes let the backend adjust the values # (such as with page size, where their may not be a perfect # fit). If the value does not match the step, it will cause # a SaneInexactValueError to be thrown, which the frontened # can handle in different ways depending on the option being # set. pass elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i .' % status, device=self._device) # if self._log: # self._log.debug('Option %s set to value %s.', self._name, value) # See SANE API 4.3.7 if info_flags.value & SANE_INFO_RELOAD_OPTIONS: self._device._load_options() raise SaneReloadOptionsError() # Catching this can not be avoided by constraint checking, as some # devices restrict option values without setting a constraint range # step. if info_flags.value & SANE_INFO_INEXACT: raise SaneInexactValueError() # TODO? if info_flags.value & SANE_INFO_RELOAD_PARAMS: pass value = property(__get_value, __set_value) # PUBLIC METHODS def is_soft_settable(self): """ Returns True if the option can be set by software. """ return self._capability & SANE_CAP_SOFT_SELECT def is_hard_settable(self): """ Returns True if the option can be set by hardware. """ return self._capability & SANE_CAP_HARD_SELECT def is_soft_gettable(self): """ Returns True if the option can be read by software. """ return self._capability & SANE_CAP_SOFT_DETECT def is_emulated(self): """ Returns True if the option is emulated by the backend driver. """ return self._capability & SANE_CAP_EMULATED # def is_automatic(self): # return self._capability & SANE_CAP_AUTOMATIC def is_active(self): """ Returns False if this device is unavailable because of the value of some other option. """ return not self._capability & SANE_CAP_INACTIVE # def is_advanced(self): # return self._capability & SANE_CAP_ADVANCED class ScanInfo(object): """ Contains the parameters and progress of a scan in progress. """ _width = 0 _height = 0 _depth = 0 _total_bytes = 0 def __init__(self, sane_parameters): """ Initialize the ScanInfo object from the sane_parameters. """ self._width = sane_parameters.pixels_per_line self._height = sane_parameters.lines self._depth = sane_parameters.depth self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines # Read only properties def __get_width(self): """Get the width of the current scan, in pixels.""" return self._width width = property(__get_width) def __get_height(self): """Get the height of the current scan, in pixels.""" return self._height height = property(__get_height) def __get_depth(self): """Get the depth of the current scan, in bits.""" return self._depth depth = property(__get_depth)
onyxfish/nostaples
9b4b53b295f5dace08a65d097bf1d5a0bc1c9491
Refined page size support.
diff --git a/constants.py b/constants.py index dac2a83..bc7100b 100644 --- a/constants.py +++ b/constants.py @@ -1,143 +1,206 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. ''' This module contains global configuration constants that are not likely to change often as well as enumeration-like state constants. ''' import os import gtk import Image from reportlab.lib.pagesizes import A0, A1, A2, A3, A4, A5, A6, \ B0, B1, B2, B3, B4, B5, B6, LETTER, LEGAL, ELEVENSEVENTEEN -PAGESIZES = {'A0' : A0, - 'A1' : A1, - 'A2' : A2, - 'A3' : A3, - 'A4' : A4, - 'A5' : A5, - 'A6' : A6, - 'B0' : B0, - 'B1' : B1, - 'B2' : B2, - 'B3' : B3, - 'B4' : B4, - 'B5' : B5, - 'B6' : B6, - 'Letter' : LETTER, - 'Legal' : LEGAL, - 'Ledger' : ELEVENSEVENTEEN} +PAGESIZES_INCHES = {'A0' : (33.1, 46.8), + 'A1' : (23.4, 33.1), + 'A2' : (16.5, 23.4), + 'A3' : (11.7, 16.5), + 'A4' : (8.3, 11.7), + 'A5' : (5.8, 8.3), + 'A6' : (4.1, 5.8), + 'A7' : (2.9, 4.1), + 'A8' : (2.0, 2.9), + 'A9' : (1.5, 2.0), + 'A10' : (1.0, 1.5), + 'B0' : (39.4, 55.7), + 'B1' : (27.8, 39.4), + 'B2' : (19.7, 27.8), + 'B3' : (13.9, 19.7), + 'B4' : (9.8, 13.9), + 'B5' : (6.9, 9.8), + 'B6' : (4.9, 6.9), + 'B7' : (3.5, 4.9), + 'B8' : (2.4, 3.5), + 'B9' : (1.7, 2.4), + 'B10' : (1.2, 1.7), + 'Letter' : (8.5, 11.0), + 'Legal' : (8.5, 14.0), + 'Junior Legal' : (8.0, 5.0), + 'Ledger' : (17.0, 11.0), + 'Tabloid' : (11.0, 17.0), + '3x5 Photo' : (3.0, 5.0), + '4x6 Photo' : (4.0, 6.0), + '5x7 Photo' : (5.0, 7.0), + '8x10 Photo' : (8.0, 10.0), + '11x14 Photo' : (11.0, 14.0)} + +PAGESIZES_MM = {'A0' : (841.0, 1189.0), + 'A1' : (594.0, 841.0), + 'A2' : (420.0, 594.0), + 'A3' : (297.0, 420.0), + 'A4' : (210.0, 297.0), + 'A5' : (148.0, 210.0), + 'A6' : (105.0, 148.0), + 'A7' : (74.0, 105.0), + 'A8' : (52.0, 74.0), + 'A9' : (37.0, 52.0), + 'A10' : (26.0, 37.0), + 'B0' : (1000.0, 1414.0), + 'B1' : (707.0, 1000.0), + 'B2' : (500.0, 707.0), + 'B3' : (353.0, 500.0), + 'B4' : (250.0, 353.0), + 'B5' : (176.0, 250.0), + 'B6' : (125.0, 176.0), + 'B7' : (88.0, 125.0), + 'B8' : (62.0, 88.0), + 'B9' : (44.0, 62.0), + 'B10' : (31.0, 44.0), + 'Letter' : (216.0, 279.0), + 'Legal' : (216.0, 356.0), + 'Junior Legal' : (203.2, 127.0), + 'Ledger' : (432.0, 279.0), + 'Tabloid' : (279.0, 43.0), + '3x5 Photo' : (76.0, 127.0), + '4x6 Photo' : (102.0, 152.0), + '5x7 Photo' : (127.0, 178.0), + '8x10 Photo' : (203.0, 254.0), + '11x14 Photo' : (279.0, 356.0)} PAGESIZE_SORT_ORDER = ['A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', + 'A7', + 'A8', + 'A9', + 'A10', 'B0', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', + 'B7', + 'B8', + 'B9', + 'B10', 'Letter', 'Legal', - 'Ledger'] + 'Junior Legal', + 'Ledger', + 'Tabloid', + '3x5 Photo', + '4x6 Photo', + '5x7 Photo', + '8x10 Photo', + '11x14 Photo'] DEFAULT_SHOW_TOOLBAR = True DEFAULT_SHOW_STATUSBAR = True DEFAULT_SHOW_THUMBNAILS = True DEFAULT_SHOW_ADJUSTMENTS = False DEFAULT_ROTATE_ALL_PAGES = False DEFAULT_ACTIVE_SCANNER = '' DEFAULT_SCAN_MODE = 'Color' DEFAULT_SCAN_RESOLUTION = '75' DEFAULT_PAGE_SIZE = 'A4' DEFAULT_SAVE_PATH = '' DEFAULT_AUTHOR = os.getenv('LOGNAME') DEFAULT_SAVED_KEYWORDS = [] DEFAULT_PREVIEW_MODE = 'Bilinear (Default)' DEFAULT_THUMBNAIL_SIZE = 128 DEFAULT_SHOW_DOCUMENT_METADATA = True DEFAULT_BLACKLISTED_SCANNERS = [] DEFAULT_TOOLBAR_STYLE = 'System Default' THUMBNAILS_SCALING_MODE = Image.ANTIALIAS MAX_VALID_OPTION_VALUES = 11 SCAN_CANCELLED = -1 SCAN_FAILURE = 0 SCAN_SUCCESS = 1 RESPONSE_BLACKLIST_DEVICE = 1 GCONF_DIRECTORY = '/apps/nostaples' GCONF_TUPLE_SEPARATOR = '|' GCONF_LIST_SEPARATOR = '^' # TODO: rename to CONFIG_DIRECTORY APP_DIRECTORY = os.path.expanduser('~/.nostaples') LOGGING_CONFIG = os.path.join(os.path.dirname(__file__), 'logging.config') GUI_DIRECTORY = os.path.join(os.path.dirname(__file__), 'gui') PREVIEW_MODES = \ { 'Nearest (Fastest)': gtk.gdk.INTERP_NEAREST, 'Tiles': gtk.gdk.INTERP_TILES, 'Bilinear (Default)': gtk.gdk.INTERP_BILINEAR, 'Antialias (Smoothest)': gtk.gdk.INTERP_HYPER } PREVIEW_MODES_LIST = \ [ 'Nearest (Fastest)', 'Tiles', 'Bilinear (Default)', 'Antialias (Smoothest)' ] THUMBNAIL_SIZE_LIST = \ [ 32, 64, 128, 256 ] TOOLBAR_STYLES = \ { 'System Default': None, 'Icons Only': gtk.TOOLBAR_ICONS, 'Text Only': gtk.TOOLBAR_TEXT, 'Icons and Text (Stacked)': gtk.TOOLBAR_BOTH, 'Icons and Text (Side by side)': gtk.TOOLBAR_BOTH_HORIZ } TOOLBAR_STYLES_LIST = \ [ 'System Default', 'Icons Only', 'Text Only', 'Icons and Text (Stacked)', 'Icons and Text (Side by side)' ] \ No newline at end of file diff --git a/models/main.py b/models/main.py index 22785e1..f226a56 100644 --- a/models/main.py +++ b/models/main.py @@ -1,830 +1,819 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model -from reportlab.lib.pagesizes import inch as points_per_inch -from reportlab.lib.pagesizes import cm as points_per_cm from nostaples import constants import nostaples.sane as saneme from nostaples.utils import properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'active_page_size' : None, 'available_scanners' : [], # [] of saneme.Device 'unavailable_scanners' : [], # [] of (saneme.Device.display_name, reason) tuples 'valid_modes' : [], 'valid_resolutions' : [], 'valid_page_sizes' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) self.active_page_size = state_manager.init_state( 'page_size', constants.DEFAULT_PAGE_SIZE, self.state_page_size_change) # PROPERTY SETTERS set_prop_show_toolbar = properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it's option constraints can be queried without error. if value is not None: # Verify that the proper type is being set assert isinstance(value, saneme.Device) # Open the new scanner try: self.log.debug( 'Setting active scanner to %s.' % value.display_name) value.open() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Get valid options from the new device and then reset the # previous options if they exist on the new device self._update_valid_modes() self.active_mode = self.active_mode self._update_valid_resolutions() self.active_resolution = self.active_resolution self._update_valid_page_sizes() self.active_page_size = self.active_page_size # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notifications self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_mode = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value self.log.debug( 'Setting active mode to %s.' % value) self.active_scanner.options['mode'].value = value except saneme.SaneInexactValueError: - # TODO - what if "exact" value isn't in the list? - pass + raise except saneme.SaneReloadOptionsError: # Reload any options that may have changed, this will # also force this value to be set again, so its safe to # return immediately self._reload_scanner_options() return # Never persist None to state if value is not None: self.application.get_state_manager()['scan_mode'] = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_resolution = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value self.log.debug( 'Setting active resolution to %s.' % value) self.active_scanner.options['resolution'].value = int(value) except saneme.SaneInexactValueError: - # TODO - what if "exact" value isn't in the list? - pass + raise except saneme.SaneReloadOptionsError: # Reload any options that may have changed, this will # also force this value to be set again, so its safe to # return immediately self._reload_scanner_options() return # Update available page sizes if resolution is relevant if self.active_scanner.options['tl-x'].constraint_type == \ saneme.OPTION_UNIT_PIXEL: self._update_valid_page_sizes() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_resolution'] = value # Emit change notification self.notify_property_value_change( 'active_resolution', None, value) def set_prop_active_page_size(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_page_size = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: tl_x = self.active_scanner.options['tl-x'].value tl_y = self.active_scanner.options['tl-y'].value br_x = self.active_scanner.options['br-x'].value br_y = self.active_scanner.options['br-y'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None: if self.active_scanner.options['tl-x'].unit == saneme.OPTION_UNIT_PIXEL: # TODO if self.valid_resolutions == None: raise AssertionError() resolution = max([int(i) for i in self.valid_resolutions]) - page_width = int(resolution * constants.PAGESIZES[value][0] / points_per_inch) - page_height = int(resolution * constants.PAGESIZES[value][1] / points_per_inch) + page_width = int(resolution * constants.PAGESIZES_INCHES[value][0]) + page_height = int(resolution * constants.PAGESIZES_INCHES[value][1]) else: - page_width = constants.PAGESIZES[value][0] - page_height = constants.PAGESIZES[value][1] + page_width = constants.PAGESIZES_MM[value][0] + page_height = constants.PAGESIZES_MM[value][1] needs_reload = False if br_x - tl_x != page_width and br_y - tl_y != page_height: try: # Set the new option value self.log.debug( 'Setting active page size to %s.' % value) self.active_scanner.options['br-x'].value = tl_x + page_width except saneme.SaneInexactValueError: - # TODO - what if "exact" value isn't in the list? + # Coordinate may often be inexact due to backend + # rounding/quantization. Nothing needs to be done + # about this since the exact coordinates that have + # been set are stored locally. pass except saneme.SaneReloadOptionsError: - # Reload any options that may have changed, this will - # also force this value to be set again, so its safe to - # return immediately + # Reload after other coordinates have been set. needs_reload == True try: # Set the new option value self.log.debug( 'Setting active page size to %s.' % value) self.active_scanner.options['br-y'].value = tl_y + page_height except saneme.SaneInexactValueError: - # TODO - what if "exact" value isn't in the list? + # See above pass except saneme.SaneReloadOptionsError: - # Reload any options that may have changed, this will - # also force this value to be set again, so its safe to - # return immediately + # See above needs_reload == True if needs_reload: + # Reload any options that may have changed, this will + # also force this value to be set again, so its safe to + # return immediately self._reload_scanner_options() return # Never persist None to state if value is not None: self.application.get_state_manager()['page_size'] = value # Emit change notification self.notify_property_value_change( 'active_page_size', None, value) def set_prop_available_scanners(self, value): """ Takes a new list of scanners, removes any which are blacklisted or unsupported, sets the new list, updates the active_scanner, and emits appropriate property callbacks. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() # Remove blacklisted scanners value = \ [scanner for scanner in value if not \ scanner.display_name in preferences_model.blacklisted_scanners] # Remove scanners that do not support necessary options or fail to # open entirely new_unavailable_scanners = [] # TODO - move somewhere more appropriate? unsupported_scanner_error = \ 'Scanner %s is unsupported for the following reason: %s' for scanner in value: try: scanner.open() unsupported = False # Enforce mode option requirements if not scanner.has_option('mode'): reason = 'No \'mode\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue mode = scanner.options['mode'] if not self.is_settable_option(mode): reason = 'Unsettable \'mode\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue if not mode.constraint_type == saneme.OPTION_CONSTRAINT_STRING_LIST: reason = '\'Mode\' option does not include a STRING_LIST constraint.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # Enforce resolution option requirements if not scanner.has_option('resolution'): reason = 'No \'resolution\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue resolution = scanner.options['resolution'] if not self.is_settable_option(resolution): reason = 'Unsettable \'resolution\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue if resolution.constraint_type == saneme.OPTION_CONSTRAINT_NONE: reason = '\'Resolution\' option does not specify a constraint.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # See SANE API 4.5.2 if resolution.type != saneme.OPTION_TYPE_INT and \ resolution.type != saneme.OPTION_TYPE_FLOAT: reason = '\'Resolution\' option is not of type INT or FLOAT.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # See SANE API 4.5.2 if not resolution.unit == saneme.OPTION_UNIT_DPI: reason = '\'Resolution\' option is not measured in DPI units.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # Enforce scan area option requirements scan_area_option_names = ['tl-x', 'tl-y', 'br-x', 'br-y'] supported = True for option_name in scan_area_option_names: if not scanner.has_option(option_name): supported = False if not supported: reason = 'No \'scan area\' options.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue scan_area_options = \ [scanner.options[o] for o in scan_area_option_names] supported = True for option in scan_area_options: if option.type != saneme.OPTION_TYPE_INT: supported = False if not supported: reason = '\'Scan area\' options are not of type INT.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue supported = True for option in scan_area_options: if option.unit != saneme.OPTION_UNIT_PIXEL and \ option.unit != saneme.OPTION_UNIT_MM: supported = False if not supported: reason = '\'Scan area\' options are not measured in unit PIXEL or MM.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue supported = True for option in scan_area_options: if option.constraint_type != saneme.OPTION_CONSTRAINT_RANGE: supported = False if not supported: reason = '\'Scan area\' options do not specify a RANGE constraint.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue scanner.close() except saneme.SaneError: reason = 'Exception raised while attempting to query device options.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue self._prop_unavailable_scanners = new_unavailable_scanners self._prop_available_scanners = value self.notify_property_value_change( 'unavailable_scanners', None, new_unavailable_scanners) self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None elif self._prop_active_scanner not in value: self.active_scanner = value[0] def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) if len(value) == 0: self.active_mode = None elif self.active_mode not in value: self.active_mode = value[0] def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) if len(value) == 0: self.active_resolution = None elif self.active_resolution not in value: self.active_resolution = value[0] def set_prop_valid_page_sizes(self, value): """ Set the list of valid scan page sizes, update the active page size and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_page_sizes = value self.notify_property_value_change( 'valid_page_sizes', None, value) if len(value) == 0: self.active_page_size = None elif self.active_page_size not in value: self.active_page_size = value[0] # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution def state_page_size_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_page_size'] in self.valid_page_sizes: self.active_page_size = state_manager['scan_page_size'] else: state_manager['scan_page_size'] = self.active_page_size # INTERNAL METHODS def is_settable_option(self, option): """ Verify an option supports minimum capabilities needed to be used by NoStaples. """ return option.is_active() and \ option.is_soft_gettable() and \ option.is_soft_settable() def _update_valid_modes(self): """ Update valid modes from the active scanner. """ self.valid_modes = self.active_scanner.options['mode'].constraint def _update_valid_resolutions(self): """ Update valid resolutions from the active scanner. """ if self.active_scanner.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_RANGE: min, max, step = self.active_scanner.options['resolution'].constraint # Fix for ticket #34. if step is None or step == 0: step = 1 resolutions = [] # If there are not an excessive number, include every possible # resolution if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: i = min while i <= max: resolutions.append(str(i)) i = i + step # Otherwise, take a crack at building a sensible set of options # that meet that constraint criteria else: - # THE OLD METHOD: DID NOT WORK -# i = 1 -# increment = (max - min) / (constants.MAX_VALID_OPTION_VALUES - 1) -# while (i <= constants.MAX_VALID_OPTION_VALUES - 2): -# unrounded = min + (i * increment) -# rounded = int(round(unrounded / step) * step) -# resolutions.append(str(rounded)) -# i = i + 1 -# resolutions.insert(0, str(min)) -# resolutions.append(str(max)) - + # TODO: This is a naive implementation that is likely to + # generate an unusuably large number of valid resolutions. i = min tested_resolutions = [] while i <= max: try: self.active_scanner.options['resolution'].value = i except saneme.SANE_INFO_INEXACT: pass except saneme.SANE_INFO_RELOAD_PARAMS: pass tested_resolutions.append( self.active_scanner.options['resolution'].value) i = i + step # Prune duplicates # http://code.activestate.com/recipes/52560/ uniques = {} for j in tested_resolutions: uniques[j] = True resolutions = [str(k) for k in uniques.keys()] self._prop_valid_resolutions = resolutions elif self.active_scanner.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_VALUE_LIST: # Convert values to strings for display self.valid_resolutions = \ [str(i) for i in self.active_scanner.options['resolution'].constraint] elif self.active_scanner.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST: self.valid_resolutions = \ self.active_scanner.options['resolution'].constraint else: raise AssertionError('Unsupported constraint type.') def _update_valid_page_sizes(self): """ Update valid page sizes from the active scanner. """ tl_x = self.active_scanner.options['tl-x'] tl_y = self.active_scanner.options['tl-y'] br_x = self.active_scanner.options['br-x'] br_y = self.active_scanner.options['br-y'] - sizes = [] + new_sizes = [] - for name, size in constants.PAGESIZES.iteritems(): + for size in constants.PAGESIZES_INCHES.iterkeys(): if tl_x.unit == saneme.OPTION_UNIT_PIXEL: # TODO? if self.valid_resolutions == None: break resolution = max([int(i) for i in self.valid_resolutions]) - page_width = int(resolution * size[0] / points_per_inch) - page_height = int(resolution * size[1] / points_per_inch) + page_width = int(resolution * constants.PAGESIZES_INCHES[size][0]) + page_height = int(resolution * constants.PAGESIZES_INCHES[size][1]) max_x = br_x.constraint[1] - tl_x.constraint[0] max_y = br_y.constraint[1] - tl_y.constraint[0] if page_width <= max_x and page_height <= max_y: - sizes.append(name) + new_sizes.append(size) elif tl_x.unit == saneme.OPTION_UNIT_MM: - page_width = int(size[0] / (points_per_cm / 10)) - page_height = int(size[1] / (points_per_cm / 10)) + page_width = int(constants.PAGESIZES_MM[size][0]) + page_height = int(constants.PAGESIZES_MM[size][1]) max_x = br_x.constraint[1] - tl_x.constraint[0] max_y = br_y.constraint[1] - tl_y.constraint[0] if page_width <= max_x and page_height <= max_y: - sizes.append(name) + new_sizes.append(size) else: raise AssertionError() def page_size_sort(x, y): """ Sort paper sizes according to their order in a constant list. """ sort_x = constants.PAGESIZE_SORT_ORDER.index(x) sort_y = constants.PAGESIZE_SORT_ORDER.index(y) if sort_x > sort_y: return 1 elif sort_x == sort_y: return 0 else: return -1 - sizes.sort(page_size_sort) - self.valid_page_sizes = sizes + new_sizes.sort(page_size_sort) + self.valid_page_sizes = new_sizes def _reload_scanner_options(self): """ Get current scanner options from the active_scanner. Useful for reloading any option that may have changed in response to a SaneReloadOptionsError. """ main_controller = self.application.get_main_controller() self.log.debug('Reloading scanner options.') try: # Read updated values from the device new_mode = self.active_scanner.options['mode'].value new_resolution = str(self.active_scanner.options['resolution'].value) #new_page_size = ??? # Reload valid options self._update_valid_modes() self._update_valid_resolutions() self._update_valid_page_sizes() # Reset new values (in case they were overwritten) self.active_mode = new_mode self.active_resolution = new_resolution #self.active_page_size = new_page_size except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) self.log.debug('Scanner options reloaded.') \ No newline at end of file diff --git a/sane/saneme.py b/sane/saneme.py index 079e3db..cfd8ef3 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -357,659 +357,662 @@ class Device(object): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater_update_options access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: # Lineart if sane_parameters.depth == 1: pil_image = Image.frombuffer( '1', (scan_info.width, scan_info.height), data_array, 'raw', '1', 0, 1) # Grayscale elif sane_parameters.depth == 8: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) else: raise AssertionError( 'Unexpected bit depth for monochrome scan format: %i' % sane_parameters.depth) elif sane_parameters.format == SANE_FRAME_RGB.value: # Color pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Internal methods def _load_options(self): """ Update the list of available options for this device. This is called when the Device is first instantiated and in response to any SANE_INFO_RELOAD_OPTIONS flags when setting option values. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') option_value = pointer(c_int()) status = sane_control_option( self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: raise SaneUnsupportedOperationError( 'sane_control_option reported that a value was outside the option\'s constraint.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) option_count = option_value.contents.value if self._log: self._log.debug('Device queried, %i option(s) found.', option_count) self._options.clear() i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) self._options[coption.contents.name] = Option( self, i, coption.contents, self._log) i = i + 1 class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capability = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number # String attributes should never be None self._name = ctypes_option.name if ctypes_option.name else '' self._title = ctypes_option.title if ctypes_option.title else '' self._description = ctypes_option.desc if ctypes_option.desc else '' self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: if self._type == SANE_TYPE_FIXED.value: self._constraint = ( SANE_UNFIX(ctypes_option.constraint.range.contents.min), SANE_UNFIX(ctypes_option.constraint.range.contents.max), SANE_UNFIX(ctypes_option.constraint.range.contents.quant)) else: self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 if self._type == SANE_TYPE_FIXED.value: self._constraint = [SANE_UNFIX(i) for i in self._constraint] elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 if self._type == SANE_TYPE_FIXED.value: self._constraint = [str(SANE_UNFIX(int(i))) for i in self._constraint] else: self._constraint = None # Read only properties def __get_name(self): """ Get the short-form name of this option, e.g. 'mode'. May be an empty string, but never None. """ return self._name name = property(__get_name) def __get_title(self): """ Get the full name of this option, e.g. 'Scan mode'. May be an empty string, but never None. """ return self._title title = property(__get_title) def __get_description(self): """ Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' May be an empty string, but never None. """ return self._description description = property(__get_description) def __get_type(self): """ Get the type of this option, e.g. OPTION_TYPE_STRING. """ return self._type type = property(__get_type) def __get_unit(self): """ Get the unit of this option, e.g.OPTION_UNIT_DPI. """ return self._unit unit = property(__get_unit) def __get_constraint_type(self): """ Get the type of constraint on this option, e.g. OPTION_CONSTRAINT_RANGE. """ return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_VALUE_LIST then this is a list of ints/floats which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """value Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option( handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i.' % status, device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value elif self._type == SANE_TYPE_FIXED.value: option_value = SANE_UNFIX(option_value.value) else: option_value = option_value.contents.value # if self._log: # self._log.debug( # 'Option %s queried, its current value is %s.', # self._name, # option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: raise TypeError( 'option set with %s, expected BooleanType' % type(value)) c_value = pointer(SANE_Bool(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(SANE_Int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType and type(value) is not FloatType: raise TypeError( 'option set with %s, expected IntType or FloatType' % type(value)) c_value = pointer(SANE_Fixed(SANE_FIX(value))) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: raise TypeError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: raise ValueError( 'value for option is longer than max string size') c_value = SANE_String(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: min, max, step = self._constraint if value < min: raise ValueError('value for option is less than min.') if value > max: raise ValueError('value for option is greater than max.') if step is not None and step > 0: - #if value % step != 0: - # raise ValueError( - # 'value for option is not evenly divisible by step.') - print step, value + # In theory this should be enforced, but in practice it is + # useful to sometimes let the backend adjust the values + # (such as with page size, where their may not be a perfect + # fit). If the value does not match the step, it will cause + # a SaneInexactValueError to be thrown, which the frontened + # can handle in different ways depending on the option being + # set. pass elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i .' % status, device=self._device) # if self._log: # self._log.debug('Option %s set to value %s.', self._name, value) # See SANE API 4.3.7 if info_flags.value & SANE_INFO_RELOAD_OPTIONS: self._device._load_options() raise SaneReloadOptionsError() # Catching this can not be avoided by constraint checking, as some # devices restrict option values without setting a constraint range # step. if info_flags.value & SANE_INFO_INEXACT: raise SaneInexactValueError() # TODO? if info_flags.value & SANE_INFO_RELOAD_PARAMS: pass value = property(__get_value, __set_value) # PUBLIC METHODS def is_soft_settable(self): """ Returns True if the option can be set by software. """ return self._capability & SANE_CAP_SOFT_SELECT def is_hard_settable(self): """ Returns True if the option can be set by hardware. """ return self._capability & SANE_CAP_HARD_SELECT def is_soft_gettable(self): """ Returns True if the option can be read by software. """ return self._capability & SANE_CAP_SOFT_DETECT def is_emulated(self): """ Returns True if the option is emulated by the backend driver. """ return self._capability & SANE_CAP_EMULATED # def is_automatic(self): # return self._capability & SANE_CAP_AUTOMATIC def is_active(self): """ Returns False if this device is unavailable because of the value of some other option. """ return not self._capability & SANE_CAP_INACTIVE # def is_advanced(self): # return self._capability & SANE_CAP_ADVANCED class ScanInfo(object): """ Contains the parameters and progress of a scan in progress. """ _width = 0 _height = 0 _depth = 0 _total_bytes = 0 def __init__(self, sane_parameters): """ Initialize the ScanInfo object from the sane_parameters. """ self._width = sane_parameters.pixels_per_line self._height = sane_parameters.lines self._depth = sane_parameters.depth self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines # Read only properties def __get_width(self): """Get the width of the current scan, in pixels.""" return self._width width = property(__get_width) def __get_height(self): """Get the height of the current scan, in pixels.""" return self._height height = property(__get_height) def __get_depth(self): """Get the depth of the current scan, in bits.""" return self._depth depth = property(__get_depth) def __get_total_bytes(self): """Get the total number of bytes comprising this scan.""" return self._total_bytes total_bytes = property(__get_total_bytes) \ No newline at end of file
onyxfish/nostaples
2cf2e8cac843cd550abb6e403cd83735fecd9c14
Very rough page size support.
diff --git a/constants.py b/constants.py index a835790..dac2a83 100644 --- a/constants.py +++ b/constants.py @@ -1,124 +1,143 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. ''' This module contains global configuration constants that are not likely to change often as well as enumeration-like state constants. ''' import os import gtk import Image from reportlab.lib.pagesizes import A0, A1, A2, A3, A4, A5, A6, \ B0, B1, B2, B3, B4, B5, B6, LETTER, LEGAL, ELEVENSEVENTEEN PAGESIZES = {'A0' : A0, 'A1' : A1, 'A2' : A2, 'A3' : A3, 'A4' : A4, 'A5' : A5, 'A6' : A6, 'B0' : B0, 'B1' : B1, 'B2' : B2, 'B3' : B3, 'B4' : B4, 'B5' : B5, 'B6' : B6, - 'LETTER' : LETTER, - 'LEGAL' : LEGAL, - 'ELEVENSEVENTEEN' : ELEVENSEVENTEEN} + 'Letter' : LETTER, + 'Legal' : LEGAL, + 'Ledger' : ELEVENSEVENTEEN} + +PAGESIZE_SORT_ORDER = ['A0', + 'A1', + 'A2', + 'A3', + 'A4', + 'A5', + 'A6', + 'B0', + 'B1', + 'B2', + 'B3', + 'B4', + 'B5', + 'B6', + 'Letter', + 'Legal', + 'Ledger'] DEFAULT_SHOW_TOOLBAR = True DEFAULT_SHOW_STATUSBAR = True DEFAULT_SHOW_THUMBNAILS = True DEFAULT_SHOW_ADJUSTMENTS = False DEFAULT_ROTATE_ALL_PAGES = False DEFAULT_ACTIVE_SCANNER = '' DEFAULT_SCAN_MODE = 'Color' DEFAULT_SCAN_RESOLUTION = '75' +DEFAULT_PAGE_SIZE = 'A4' DEFAULT_SAVE_PATH = '' DEFAULT_AUTHOR = os.getenv('LOGNAME') DEFAULT_SAVED_KEYWORDS = [] DEFAULT_PREVIEW_MODE = 'Bilinear (Default)' DEFAULT_THUMBNAIL_SIZE = 128 DEFAULT_SHOW_DOCUMENT_METADATA = True DEFAULT_BLACKLISTED_SCANNERS = [] DEFAULT_TOOLBAR_STYLE = 'System Default' THUMBNAILS_SCALING_MODE = Image.ANTIALIAS MAX_VALID_OPTION_VALUES = 11 SCAN_CANCELLED = -1 SCAN_FAILURE = 0 SCAN_SUCCESS = 1 RESPONSE_BLACKLIST_DEVICE = 1 GCONF_DIRECTORY = '/apps/nostaples' GCONF_TUPLE_SEPARATOR = '|' GCONF_LIST_SEPARATOR = '^' # TODO: rename to CONFIG_DIRECTORY APP_DIRECTORY = os.path.expanduser('~/.nostaples') LOGGING_CONFIG = os.path.join(os.path.dirname(__file__), 'logging.config') GUI_DIRECTORY = os.path.join(os.path.dirname(__file__), 'gui') PREVIEW_MODES = \ { 'Nearest (Fastest)': gtk.gdk.INTERP_NEAREST, 'Tiles': gtk.gdk.INTERP_TILES, 'Bilinear (Default)': gtk.gdk.INTERP_BILINEAR, 'Antialias (Smoothest)': gtk.gdk.INTERP_HYPER } PREVIEW_MODES_LIST = \ [ 'Nearest (Fastest)', 'Tiles', 'Bilinear (Default)', 'Antialias (Smoothest)' ] THUMBNAIL_SIZE_LIST = \ [ 32, 64, 128, 256 ] TOOLBAR_STYLES = \ { 'System Default': None, 'Icons Only': gtk.TOOLBAR_ICONS, 'Text Only': gtk.TOOLBAR_TEXT, 'Icons and Text (Stacked)': gtk.TOOLBAR_BOTH, 'Icons and Text (Side by side)': gtk.TOOLBAR_BOTH_HORIZ } TOOLBAR_STYLES_LIST = \ [ 'System Default', 'Icons Only', 'Text Only', 'Icons and Text (Stacked)', 'Icons and Text (Side by side)' ] \ No newline at end of file diff --git a/controllers/main.py b/controllers/main.py index ede0ae0..59ff452 100644 --- a/controllers/main.py +++ b/controllers/main.py @@ -1,749 +1,802 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{MainController}, which manages interaction between the L{MainModel} and L{MainView}. """ import commands import logging import os import re import threading import gobject import gtk from gtkmvc.controller import Controller from nostaples.models.page import PageModel import nostaples.sane as saneme from nostaples.utils.scanning import * class MainController(Controller): """ Manages interaction between the L{MainModel} and L{MainView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the MainController, as well as necessary sub-controllers and services. """ self.application = application Controller.__init__(self, application.get_main_model()) application.get_document_model().register_observer(self) application.get_preferences_model().register_observer(self) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ self.adapt('show_toolbar', 'show_toolbar_menu_item') self.adapt('show_statusbar', 'show_statusbar_menu_item') self.adapt('show_thumbnails', 'show_thumbnails_menu_item') self.adapt('show_adjustments', 'show_adjustments_menu_item') self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS # Menu Items def on_scan_window_destroy(self, window): """Exits the application.""" self.quit() def on_scan_menu_item_activate(self, menu_item): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_menu_item_activate(self, menu_item): """Refresh the list of connected scanners from SANE.""" self._update_available_scanners() def on_save_as_menu_item_activate(self, menu_item): """Saves the current document to a file.""" self.application.show_save_dialog() def on_delete_menu_item_activate(self, menu_item): self.application.get_document_controller().delete_selected() def on_preferences_menu_item_activate(self, menu_item): """Creates and displays a preferences dialog.""" self.application.show_preferences_dialog() def on_quit_menu_item_activate(self, menu_item): """Exits the application.""" self.quit() def on_zoom_in_menu_item_activate(self, menu_item): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_menu_item_activate(self, menu_item): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_menu_item_activate(self, menu_item): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_menu_item_activate(self, menu_item): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_available_scanner_menu_item_toggled(self, menu_item): """ Set the active scanner. TODO: Need a second scanner to properly test this... """ main_model = self.application.get_main_model() if menu_item.get_active(): for scanner in main_model.available_scanners: if scanner.display_name == menu_item.get_children()[0].get_text(): main_model.active_scanner = scanner return def on_valid_mode_menu_item_toggled(self, menu_item): """Sets the active scan mode.""" if menu_item.get_active(): self.application.get_main_model().active_mode = \ menu_item.get_children()[0].get_text() def on_valid_resolution_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_resolution = \ menu_item.get_children()[0].get_text() + + def on_valid_page_size_menu_item_toggled(self, menu_item): + """Sets the active scan resolution.""" + if menu_item.get_active(): + self.application.get_main_model().active_page_size = \ + menu_item.get_children()[0].get_text() def on_go_first_menu_item_activate(self, menu_item): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_menu_item_activate(self, menu_item): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_menu_item_activate(self, menu_item): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_menu_item_activate(self, menu_item): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() def on_contents_menu_item_clicked(self, menu_item): """TODO""" pass def on_about_menu_item_activate(self, menu_item): """Show the about dialog.""" self.application.show_about_dialog() # Toolbar Buttons def on_scan_button_clicked(self, button): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_button_clicked(self, button): self._update_available_scanners() def on_save_as_button_clicked(self, button): """Saves the current document to a file.""" self.application.show_save_dialog() def on_zoom_in_button_clicked(self, button): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_button_clicked(self, button): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_button_clicked(self, button): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_button_clicked(self, button): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_go_first_button_clicked(self, button): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_button_clicked(self, button): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_button_clicked(self, button): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_button_clicked(self, button): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() # Progress Window INTERFACE CALLBACKS def on_progress_window_delete_event(self, window, event): """ Emulate clicking of the cancel/close button and then hide the window. """ main_view = self.application.get_main_view() self.on_scan_cancel_button_clicked(None) main_view['progress_window'].hide() return True def on_scan_cancel_button_clicked(self, button): """ Cancel the current scan or, if the scan is finished, close the progress window. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress: assert self.cancel_event self.cancel_event.set() else: main_view['progress_window'].hide() def on_scan_again_button_clicked(self, button): """Initiate a new scan from the progress window.""" self._scan() def on_quick_save_button_clicked(self, button): """ Show the save dialog. If the user completes a save then disable the quick save button until another page is scanned. """ main_view = self.application.get_main_view() document_model = self.application.get_document_model() self.application.show_save_dialog() if document_model.count == 0: main_view['quick_save_button'].set_sensitive(False) # MainModel PROPERTY CALLBACKS def property_show_toolbar_value_change(self, model, old_value, new_value): """Update the visibility of the toolbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_toolbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['main_toolbar'].show() else: main_view['main_toolbar'].hide() def property_show_statusbar_value_change(self, model, old_value, new_value): """Update the visibility of the statusbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_statusbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['status_view_docking_viewport'].show() else: main_view['status_view_docking_viewport'].hide() def property_show_thumbnails_value_change(self, model, old_value, new_value): """Update the visibility of the thumbnails.""" main_view = self.application.get_main_view() menu_item = main_view['show_thumbnails_menu_item'] menu_item.set_active(new_value) self.application.get_document_controller().toggle_thumbnails_visible(new_value) def property_show_adjustments_value_change(self, model, old_value, new_value): """Update the visibility of the adjustments controls.""" document_controller = self.application.get_document_controller() main_view = self.application.get_main_view() menu_item = main_view['show_adjustments_menu_item'] menu_item.set_active(new_value) document_controller.toggle_adjustments_visible(new_value) def property_active_scanner_value_change(self, model, old_value, new_value): """ Update the menu and valid scanner options to match the new device. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() if new_value == None: return for menu_item in main_view['scanner_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value.display_name: menu_item.set_active(True) break def property_active_mode_value_change(self, model, old_value, new_value): """Select the active mode from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_mode_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_resolution_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_resolution_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break + + def property_active_page_size_value_change(self, model, old_value, new_value): + """Select the active resolution from in the menu.""" + main_view = self.application.get_main_view() + + if new_value == None: + return + + for menu_item in main_view['scan_page_size_sub_menu'].get_children(): + if menu_item.get_children()[0].get_text() == new_value: + menu_item.set_active(True) + break def property_available_scanners_value_change(self, model, old_value, new_value): """ Update the menu of available scanners. """ main_view = self.application.get_main_view() self._clear_available_scanners_sub_menu() # Generate the new menu if len(new_value) == 0: menu_item = gtk.MenuItem('No Scanners Connected') menu_item.set_sensitive(False) main_view['scanner_sub_menu'].append(menu_item) else: first_item = None for i in range(len(new_value)): # The first menu item defines the group if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i].display_name) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i].display_name) main_view['scanner_sub_menu'].append(menu_item) main_view['scanner_sub_menu'].show_all() def property_valid_modes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan modes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_modes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Modes") menu_item.set_sensitive(False) main_view['scan_mode_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled) main_view['scan_mode_sub_menu'].append(menu_item) main_view['scan_mode_sub_menu'].show_all() def property_valid_resolutions_value_change(self, model, old_value, new_value): """ Updates the list of valid scan resolutions for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_resolutions_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Resolutions") menu_item.set_sensitive(False) main_view['scan_resolution_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled) main_view['scan_resolution_sub_menu'].append(menu_item) main_view['scan_resolution_sub_menu'].show_all() + + def property_valid_page_sizes_value_change(self, model, old_value, new_value): + """ + Updates the list of valid scan page sizes for the current scanner. + """ + main_view = self.application.get_main_view() + + self._clear_scan_page_sizes_sub_menu() + + if len(new_value) == 0: + menu_item = gtk.MenuItem("No Page Sizes") + menu_item.set_sensitive(False) + main_view['scan_page_size_sub_menu'].append(menu_item) + else: + for i in range(len(new_value)): + if i == 0: + menu_item = gtk.RadioMenuItem( + None, new_value[i]) + first_item = menu_item + else: + menu_item = gtk.RadioMenuItem( + first_item, new_value[i]) + + menu_item.connect('toggled', self.on_valid_page_size_menu_item_toggled) + main_view['scan_page_size_sub_menu'].append(menu_item) + + main_view['scan_page_size_sub_menu'].show_all() + def property_scan_in_progress_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() def property_updating_available_scanners_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() # DocumentModel PROPERTY CALLBACKS def property_count_value_change(self, model, old_value, new_value): """Toggle available controls.""" self._toggle_document_controls() # PreferencesModel PROPERTY CALLBACKS def property_toolbar_style_value_change(self, model, old_value, new_value): """Toggle available controls.""" main_view = self.application.get_main_view() if new_value == 'System Default': # TODO - reset style to system default pass else: main_view['main_toolbar'].set_style(constants.TOOLBAR_STYLES[new_value]) # THREAD CALLBACKS def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned): main_view = self.application.get_main_view() short_bytes_scanned = float(bytes_scanned) / 1000 short_total_bytes = float(scan_info.total_bytes) / 1000 main_view['scan_progressbar'].set_fraction( float(bytes_scanned) / scan_info.total_bytes) main_view['scan_progressbar'].set_text( 'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes)) # TODO: multi page scans main_view['progress_secondary_label'].set_markup( '<i>Scanning page.</i>') def on_scan_succeeded(self, scanning_thread, pil_image): """ Append the new page to the current document. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['scan_progressbar'].set_fraction(1) main_view['scan_progressbar'].set_text('Scan complete') main_view['progress_secondary_label'].set_markup( '<i>Adding page to document.</i>') gtk.gdk.flush() new_page = PageModel(self.application, pil_image, int(main_model.active_resolution)) self.application.get_document_model().append(new_page) main_view['progress_secondary_label'].set_markup( '<i>Page added.</i>') main_view['scan_again_button'].set_sensitive(True) main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_failed(self, scanning_thread, reason): """ Set that scan is complete. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['progress_secondary_label'].set_markup( '<i>%s</i>' % reason) main_view['scan_again_button'].set_sensitive(True) if self.application.get_document_model().count > 0: main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_aborted(self, scanning_thread, exc_info): """ Change display to indicate that scanning failed and convey the to the user the reason why the thread aborted. If the failure was from a SANE exception then give the user the option to blacklist the device. If not, then reraise the error and let the sys.excepthook deal with it. """ self.on_scan_failed(scanning_thread, 'An error occurred.') if isinstance(exc_info[1], saneme.SaneError): self.run_device_exception_dialog(exc_info) else: raise exc_info[0], exc_info[1], exc_info[2] def on_update_available_scanners_thread_finished(self, update_thread, scanner_list): """Set the new list of available scanners.""" main_model = self.application.get_main_model() main_model.available_scanners = scanner_list main_model.updating_available_scanners = False def on_update_available_scanners_thread_aborted(self, update_thread, exc_info): """ Change the display to indicate that no scanners are available and reraise the exception so that it can be caught by the sys.excepthook. There is no reason to handle these cases with a special dialog, if the application failed to even enumerate the available devices then no other action will be possible. This should be fantastically rare. """ self.on_update_available_scanners_thread_finished(update_thread, []) raise exc_info[0], exc_info[1], exc_info[2] # PUBLIC METHODS def quit(self): """Exits the application.""" self.log.debug('Quit.') gtk.main_quit() def run_device_exception_dialog(self, exc_info): """ Display an error dialog that provides the user with the option of blacklisting the device which caused the error. TODO: Move into MainView. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() preferences_model = self.application.get_preferences_model() response = main_view.run_device_exception_dialog(exc_info) if response == constants.RESPONSE_BLACKLIST_DEVICE: temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(exc_info[1].device.display_name) temp_blacklist.sort() preferences_model.blacklisted_scanners = temp_blacklist # PRIVATE METHODS def _clear_available_scanners_sub_menu(self): """Clear the menu of available scanners.""" main_view = self.application.get_main_view() for child in main_view['scanner_sub_menu'].get_children(): main_view['scanner_sub_menu'].remove(child) def _clear_scan_modes_sub_menu(self): """Clear the menu of valid scan modes.""" main_view = self.application.get_main_view() for child in main_view['scan_mode_sub_menu'].get_children(): main_view['scan_mode_sub_menu'].remove(child) def _clear_scan_resolutions_sub_menu(self): """Clear the menu of valid scan resolutions.""" main_view = self.application.get_main_view() for child in main_view['scan_resolution_sub_menu'].get_children(): main_view['scan_resolution_sub_menu'].remove(child) + + def _clear_scan_page_sizes_sub_menu(self): + """Clear the menu of valid scan page sizes.""" + main_view = self.application.get_main_view() + + for child in main_view['scan_page_size_sub_menu'].get_children(): + main_view['scan_page_size_sub_menu'].remove(child) def _toggle_scan_controls(self): """Toggle whether or not the scan controls or accessible.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_scan_controls_sensitive(False) main_view.set_refresh_scanner_controls_sensitive(False) else: if main_model.active_scanner != None: main_view.set_scan_controls_sensitive(True) main_view.set_refresh_scanner_controls_sensitive(True) def _toggle_document_controls(self): """ Toggle available document controls based on the current scanner status and the number of scanned pages. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() # Disable all controls when the scanner is in use if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: count = self.application.get_document_model().count # Disable all controls if no pages are scanned if count == 0: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: # Enable most controls if any pages scanned main_view.set_file_controls_sensitive(True) main_view.set_delete_controls_sensitive(True) main_view.set_zoom_controls_sensitive(True) main_view.set_adjustment_controls_sensitive(True) # Only enable navigation if more than one page scanned if count > 1: main_view.set_navigation_controls_sensitive(True) else: main_view.set_navigation_controls_sensitive(False) def _update_status(self): """ Update the text of the statusbar based on the current state of the application. """ main_model = self.application.get_main_model() status_controller = self.application.get_status_controller() status_controller.pop(self.status_context) if main_model.scan_in_progress: status_controller.push(self.status_context, 'Scanning...') elif main_model.updating_available_scanners: status_controller.push(self.status_context, 'Querying hardware...') else: if main_model.active_scanner: status_controller.push(self.status_context, 'Ready with %s.' % main_model.active_scanner.display_name) else: status_controller.push(self.status_context, 'No scanner available.') def _scan(self): """Begin a scan.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() main_model.scan_in_progress = True scanning_thread = ScanningThread(main_model.active_scanner) scanning_thread.connect("progress", self.on_scan_progress) scanning_thread.connect("succeeded", self.on_scan_succeeded) scanning_thread.connect("failed", self.on_scan_failed) scanning_thread.connect("aborted", self.on_scan_aborted) self.cancel_event = scanning_thread.cancel_event main_view['progress_primary_label'].set_markup( '<big><b>%s</b></big>' % main_model.active_scanner.display_name) main_view['scan_progressbar'].set_fraction(0) main_view['scan_progressbar'].set_text('Waiting for data') main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>') mode = main_model.active_mode if main_model.active_mode else 'Not set' main_view['progress_mode_label'].set_markup(mode) dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set' main_view['progress_resolution_label'].set_markup(dpi) main_view['scan_again_button'].set_sensitive(False) main_view['quick_save_button'].set_sensitive(False) main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL) main_view['progress_window'].show_all() scanning_thread.start() def _update_available_scanners(self): """ Start a new update thread to query for available scanners. """ sane = self.application.get_sane() main_model = self.application.get_main_model() main_model.updating_available_scanners = True update_thread = UpdateAvailableScannersThread(sane) update_thread.connect("finished", self.on_update_available_scanners_thread_finished) update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted) update_thread.start() \ No newline at end of file diff --git a/gui/scan_window.glade b/gui/scan_window.glade index b76303e..eb58c4b 100644 --- a/gui/scan_window.glade +++ b/gui/scan_window.glade @@ -1,925 +1,944 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> -<!--Generated with glade3 3.4.5 on Sun Mar 8 12:20:09 2009 --> +<!--Generated with glade3 3.4.5 on Tue Mar 31 10:35:43 2009 --> <glade-interface> <widget class="GtkWindow" id="progress_window"> <property name="width_request">400</property> <property name="height_request">200</property> <property name="title" translatable="yes">Scan in progress...</property> <property name="resizable">False</property> <property name="modal">True</property> <property name="window_position">GTK_WIN_POS_CENTER</property> <property name="destroy_with_parent">True</property> <property name="icon_name">scanner</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property> <property name="skip_taskbar_hint">True</property> <property name="skip_pager_hint">True</property> <property name="transient_for">scan_window</property> <signal name="delete_event" handler="on_progress_window_delete_event"/> <child> <widget class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkLabel" id="progress_primary_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">&lt;big&gt;&lt;b&gt;Scan in progress...&lt;/b&gt;&lt;/big&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <widget class="GtkVBox" id="vbox4"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkVBox" id="vbox3"> <property name="visible">True</property> <child> <widget class="GtkHBox" id="hbox2"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="static_mode_label"> <property name="width_request">90</property> <property name="visible">True</property> <property name="xalign">1</property> <property name="label" translatable="yes">&lt;b&gt;Mode:&lt;/b&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkLabel" id="progress_mode_label"> <property name="visible">True</property> <property name="label" translatable="yes">Color</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </widget> </child> <child> <widget class="GtkHBox" id="hbox5"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="static_page_size_label"> <property name="width_request">90</property> <property name="visible">True</property> <property name="xalign">1</property> <property name="label" translatable="yes">&lt;b&gt;Page Size:&lt;/b&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkLabel" id="progress_page_size_label"> <property name="visible">True</property> <property name="label" translatable="yes">Letter (TODO)</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkHBox" id="hbox3"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="static_resolution_label"> <property name="width_request">90</property> <property name="visible">True</property> <property name="xalign">1</property> <property name="label" translatable="yes">&lt;b&gt;Resolution:&lt;/b&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkLabel" id="progress_resolution_label"> <property name="visible">True</property> <property name="label" translatable="yes">150 DPI</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="position">2</property> </packing> </child> </widget> </child> <child> <widget class="GtkVBox" id="vbox4"> <property name="visible">True</property> <child> <widget class="GtkProgressBar" id="scan_progressbar"> <property name="visible">True</property> <property name="show_text">True</property> <property name="text" translatable="yes">X of Y bytes receieved.</property> </widget> <packing> <property name="fill">False</property> </packing> </child> <child> <widget class="GtkLabel" id="progress_secondary_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">&lt;i&gt;Scanning page 1 of Z.&lt;/i&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </widget> </child> <child> <widget class="GtkHBox" id="hbox1"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkButton" id="scan_cancel_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="label" translatable="yes">gtk-cancel</property> <property name="use_stock">True</property> <property name="response_id">0</property> <signal name="clicked" handler="on_scan_cancel_button_clicked"/> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="pack_type">GTK_PACK_END</property> <property name="position">2</property> </packing> </child> <child> - <widget class="GtkButton" id="scan_again_button"> + <widget class="GtkButton" id="quick_save_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="response_id">0</property> - <signal name="clicked" handler="on_scan_again_button_clicked"/> + <signal name="clicked" handler="on_quick_save_button_clicked"/> <child> - <widget class="GtkHBox" id="hbox4"> + <widget class="GtkHBox" id="hbox6"> <property name="visible">True</property> <child> - <widget class="GtkImage" id="image1"> + <widget class="GtkImage" id="image2"> <property name="visible">True</property> - <property name="icon_name">scanner</property> + <property name="stock">gtk-save-as</property> </widget> </child> <child> - <widget class="GtkLabel" id="label1"> + <widget class="GtkLabel" id="label2"> <property name="visible">True</property> - <property name="label" translatable="yes">Scan Again</property> - <property name="use_markup">True</property> + <property name="label" translatable="yes">Quick Save</property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> </child> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="pack_type">GTK_PACK_END</property> <property name="position">1</property> </packing> </child> <child> - <widget class="GtkButton" id="quick_save_button"> + <widget class="GtkButton" id="scan_again_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="response_id">0</property> - <signal name="clicked" handler="on_quick_save_button_clicked"/> + <signal name="clicked" handler="on_scan_again_button_clicked"/> <child> - <widget class="GtkHBox" id="hbox6"> + <widget class="GtkHBox" id="hbox4"> <property name="visible">True</property> <child> - <widget class="GtkImage" id="image2"> + <widget class="GtkImage" id="image1"> <property name="visible">True</property> - <property name="stock">gtk-save-as</property> + <property name="icon_name">scanner</property> </widget> </child> <child> - <widget class="GtkLabel" id="label2"> + <widget class="GtkLabel" id="label1"> <property name="visible">True</property> - <property name="label" translatable="yes">Quick Save</property> + <property name="label" translatable="yes">Scan Again</property> + <property name="use_markup">True</property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> </child> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="pack_type">GTK_PACK_END</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </widget> </child> </widget> </child> </widget> <widget class="GtkWindow" id="scan_window"> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="title" translatable="yes">NoStaples</property> <property name="window_position">GTK_WIN_POS_CENTER</property> <property name="default_width">600</property> <property name="default_height">400</property> <signal name="destroy" handler="on_scan_window_destroy"/> <signal name="size_allocate" handler="on_scan_window_size_allocate"/> <child> <widget class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <child> <widget class="GtkMenuBar" id="menubar1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <child> <widget class="GtkMenuItem" id="menuitem1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">_File</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <child> <widget class="GtkImageMenuItem" id="scan_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">S_can</property> <property name="use_underline">True</property> <signal name="activate" handler="on_scan_menu_item_activate"/> <child internal-child="image"> <widget class="GtkImage" id="menu-item-image2"> <property name="visible">True</property> <property name="icon_name">scanner</property> </widget> </child> </widget> </child> <child> <widget class="GtkImageMenuItem" id="refresh_available_scanners_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">Refresh Available Scanners</property> <property name="use_underline">True</property> <signal name="activate" handler="on_refresh_available_scanners_menu_item_activate"/> <child internal-child="image"> <widget class="GtkImage" id="menu-item-image4"> <property name="stock">gtk-refresh</property> </widget> </child> </widget> </child> <child> <widget class="GtkSeparatorMenuItem" id="separatormenuitem7"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> </widget> </child> <child> <widget class="GtkImageMenuItem" id="save_as_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">Save _As...</property> <property name="use_underline">True</property> <signal name="activate" handler="on_save_as_menu_item_activate"/> <accelerator key="S" modifiers="GDK_CONTROL_MASK" signal="activate"/> <child internal-child="image"> <widget class="GtkImage" id="menu-item-image1"> <property name="stock">gtk-save-as</property> </widget> </child> </widget> </child> <child> <widget class="GtkSeparatorMenuItem" id="separatormenuitem1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> </widget> </child> <child> <widget class="GtkImageMenuItem" id="quit_menu_item"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">gtk-quit</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_quit_menu_item_activate"/> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="menuitem2"> <property name="visible">True</property> <property name="label" translatable="yes">_Edit</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu4"> <property name="visible">True</property> <child> <widget class="GtkImageMenuItem" id="delete_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-delete</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_delete_menu_item_activate"/> <accelerator key="Delete" modifiers="" signal="activate"/> </widget> </child> <child> <widget class="GtkSeparatorMenuItem" id="separatormenuitem4"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> </widget> </child> <child> <widget class="GtkImageMenuItem" id="preferences_menu_item"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">gtk-preferences</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_preferences_menu_item_activate"/> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="view_menu"> <property name="visible">True</property> <property name="label" translatable="yes">_View</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu2"> <property name="visible">True</property> <child> <widget class="GtkCheckMenuItem" id="show_toolbar_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Toolbar</property> <property name="use_underline">True</property> <property name="active">True</property> <signal name="toggled" handler="on_show_toolbar_menu_item_toggled"/> </widget> </child> <child> <widget class="GtkCheckMenuItem" id="show_statusbar_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Statusbar</property> <property name="use_underline">True</property> <property name="active">True</property> <signal name="toggled" handler="on_show_statusbar_menu_item_toggled"/> </widget> </child> <child> <widget class="GtkCheckMenuItem" id="show_thumbnails_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">Thumb_nails</property> <property name="use_underline">True</property> <property name="active">True</property> <signal name="toggled" handler="on_show_thumbnails_menu_item_toggled"/> </widget> </child> <child> <widget class="GtkCheckMenuItem" id="show_adjustments_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Adjustments</property> <property name="use_underline">True</property> <signal name="toggled" handler="on_show_adjustments_menu_item_toggled"/> </widget> </child> <child> <widget class="GtkSeparatorMenuItem" id="separatormenuitem5"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> </widget> </child> <child> <widget class="GtkImageMenuItem" id="zoom_in_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-zoom-in</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_zoom_in_menu_item_activate"/> <accelerator key="plus" modifiers="GDK_CONTROL_MASK" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="zoom_out_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-zoom-out</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_zoom_out_menu_item_activate"/> <accelerator key="minus" modifiers="GDK_CONTROL_MASK" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="zoom_one_to_one_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-zoom-100</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_zoom_one_to_one_menu_item_activate"/> <accelerator key="1" modifiers="GDK_CONTROL_MASK" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="zoom_best_fit_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-zoom-fit</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_zoom_best_fit_menu_item_activate"/> <accelerator key="F" modifiers="GDK_CONTROL_MASK" signal="activate"/> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="menuitem9"> <property name="visible">True</property> <property name="label" translatable="yes">_Tools</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu6"> <property name="visible">True</property> <child> <widget class="GtkMenuItem" id="rotate_clockwise_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Rotate Clockwise</property> <property name="use_underline">True</property> <signal name="activate" handler="on_rotate_clockwise_menu_item_activate"/> </widget> </child> <child> <widget class="GtkMenuItem" id="rotate_counter_clockwise_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">Rotate _Counterclockwise</property> <property name="use_underline">True</property> <signal name="activate" handler="on_rotate_counter_clockwise_menu_item_activate"/> </widget> </child> <child> <widget class="GtkCheckMenuItem" id="rotate_all_pages_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">Apply rotation to all _pages?</property> <property name="use_underline">True</property> <signal name="toggled" handler="on_rotate_all_pages_menu_item_toggled"/> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="options_menu"> <property name="visible">True</property> <property name="label" translatable="yes">_Options</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu7"> <property name="visible">True</property> <child> <widget class="GtkMenuItem" id="scanner_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Scanner</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="scanner_sub_menu"> <property name="visible">True</property> <child> <widget class="GtkMenuItem" id="menuitem5"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="label" translatable="yes">None</property> <property name="use_underline">True</property> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="scan_mode_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Mode</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="scan_mode_sub_menu"> <property name="visible">True</property> <child> <widget class="GtkMenuItem" id="menuitem8"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="label" translatable="yes">None</property> <property name="use_underline">True</property> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="scan_resolution_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Resolution</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="scan_resolution_sub_menu"> <property name="visible">True</property> <child> <widget class="GtkMenuItem" id="menuitem10"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="label" translatable="yes">None</property> <property name="use_underline">True</property> </widget> </child> </widget> </child> </widget> </child> + <child> + <widget class="GtkMenuItem" id="scan_page_size_menu_item"> + <property name="visible">True</property> + <property name="label" translatable="yes">_Page Size</property> + <property name="use_underline">True</property> + <child> + <widget class="GtkMenu" id="scan_page_size_sub_menu"> + <property name="visible">True</property> + <child> + <widget class="GtkMenuItem" id="menuitem7"> + <property name="visible">True</property> + <property name="label" translatable="yes">None</property> + <property name="use_underline">True</property> + </widget> + </child> + </widget> + </child> + </widget> + </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="menuitem3"> <property name="visible">True</property> <property name="label" translatable="yes">_Go</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu5"> <property name="visible">True</property> <child> <widget class="GtkImageMenuItem" id="go_first_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-goto-first</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_go_first_menu_item_activate"/> <accelerator key="Home" modifiers="" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="go_previous_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-go-back</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_go_previous_menu_item_activate"/> <accelerator key="Left" modifiers="GDK_MOD1_MASK" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="go_next_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-go-forward</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_go_next_menu_item_activate"/> <accelerator key="Right" modifiers="GDK_MOD1_MASK" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="go_last_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-goto-last</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_go_last_menu_item_activate"/> <accelerator key="End" modifiers="" signal="activate"/> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="menuitem4"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">_Help</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu3"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <child> <widget class="GtkImageMenuItem" id="contents_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Contents</property> <property name="use_underline">True</property> <accelerator key="F1" modifiers="" signal="activate"/> <child internal-child="image"> <widget class="GtkImage" id="menu-item-image3"> <property name="visible">True</property> <property name="stock">gtk-help</property> </widget> </child> </widget> </child> <child> <widget class="GtkImageMenuItem" id="about_menu_item"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">gtk-about</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_about_menu_item_activate"/> </widget> </child> </widget> </child> </widget> </child> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkToolbar" id="main_toolbar"> <property name="visible">True</property> <property name="icon_size">GTK_ICON_SIZE_SMALL_TOOLBAR</property> <child> <widget class="GtkToolButton" id="scan_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Scan</property> <property name="label" translatable="yes">Scan</property> <property name="icon_name">scanner</property> <signal name="clicked" handler="on_scan_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="refresh_available_scanners_button"> <property name="visible">True</property> <property name="label" translatable="yes">Refresh Available Scanners</property> <property name="stock_id">gtk-refresh</property> <signal name="clicked" handler="on_refresh_available_scanners_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="save_as_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Save As...</property> <property name="label" translatable="yes">Save As</property> <property name="icon_name">document-save-as</property> <signal name="clicked" handler="on_save_as_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkSeparatorToolItem" id="toolbutton1"> <property name="visible">True</property> </widget> </child> <child> <widget class="GtkToolButton" id="zoom_in_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Zoom In</property> <property name="label" translatable="yes">Zoom In</property> <property name="icon_name">zoom-in</property> <signal name="clicked" handler="on_zoom_in_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="zoom_out_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Zoom Out</property> <property name="label" translatable="yes">Zoom Out</property> <property name="icon_name">zoom-out</property> <signal name="clicked" handler="on_zoom_out_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="zoom_one_to_one_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Normal Size</property> <property name="label" translatable="yes">Normal Size</property> <property name="icon_name">zoom-original</property> <signal name="clicked" handler="on_zoom_one_to_one_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="zoom_best_fit_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Best Fit</property> <property name="label" translatable="yes">Best Fit</property> <property name="icon_name">zoom-fit-best</property> <signal name="clicked" handler="on_zoom_best_fit_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkSeparatorToolItem" id="toolbutton2"> <property name="visible">True</property> </widget> </child> <child> <widget class="GtkToolButton" id="rotate_counter_clockwise_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Rotate Counterclockwise</property> <property name="label" translatable="yes">Rotate Counterclockwise</property> <property name="icon_name">object-rotate-left</property> <signal name="clicked" handler="on_rotate_counter_clockwise_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="rotate_clockwise_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Rotate Clockwise</property> <property name="label" translatable="yes">Rotate Clockwise</property> <property name="icon_name">object-rotate-right</property> <signal name="clicked" handler="on_rotate_clockwise_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkSeparatorToolItem" id="toolbutton4"> <property name="visible">True</property> </widget> </child> <child> <widget class="GtkToolButton" id="go_first_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">First</property> <property name="label" translatable="yes">First</property> <property name="stock_id">gtk-goto-first</property> <signal name="clicked" handler="on_go_first_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="go_previous_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Back</property> <property name="label" translatable="yes">Back</property> <property name="stock_id">gtk-go-back</property> <signal name="clicked" handler="on_go_previous_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="go_next_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Forward</property> <property name="label" translatable="yes">Forward</property> <property name="stock_id">gtk-go-forward</property> <signal name="clicked" handler="on_go_next_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="go_last_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Last</property> <property name="label" translatable="yes">Last</property> <property name="stock_id">gtk-goto-last</property> <signal name="clicked" handler="on_go_last_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> </widget> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child> <widget class="GtkViewport" id="document_view_docking_viewport"> <property name="visible">True</property> <property name="resize_mode">GTK_RESIZE_QUEUE</property> <child> <placeholder/> </child> </widget> <packing> <property name="position">2</property> </packing> </child> <child> <widget class="GtkViewport" id="status_view_docking_viewport"> <property name="visible">True</property> <property name="resize_mode">GTK_RESIZE_QUEUE</property> <property name="shadow_type">GTK_SHADOW_NONE</property> <child> <placeholder/> </child> </widget> <packing> <property name="expand">False</property> <property name="position">3</property> </packing> </child> </widget> </child> </widget> </glade-interface> diff --git a/models/main.py b/models/main.py index 248bfc9..22785e1 100644 --- a/models/main.py +++ b/models/main.py @@ -1,714 +1,830 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from reportlab.lib.pagesizes import inch as points_per_inch from reportlab.lib.pagesizes import cm as points_per_cm from nostaples import constants import nostaples.sane as saneme from nostaples.utils import properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'active_page_size' : None, 'available_scanners' : [], # [] of saneme.Device 'unavailable_scanners' : [], # [] of (saneme.Device.display_name, reason) tuples 'valid_modes' : [], 'valid_resolutions' : [], 'valid_page_sizes' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) -# self.active_page_size = state_manager.init_state( -# 'page_size', constants.DEFAULT_PAGE_SIZE, -# self.state_page_size_change) + self.active_page_size = state_manager.init_state( + 'page_size', constants.DEFAULT_PAGE_SIZE, + self.state_page_size_change) # PROPERTY SETTERS set_prop_show_toolbar = properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it's option constraints can be queried without error. if value is not None: # Verify that the proper type is being set assert isinstance(value, saneme.Device) # Open the new scanner try: self.log.debug( 'Setting active scanner to %s.' % value.display_name) value.open() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Get valid options from the new device and then reset the # previous options if they exist on the new device self._update_valid_modes() self.active_mode = self.active_mode self._update_valid_resolutions() self.active_resolution = self.active_resolution self._update_valid_page_sizes() self.active_page_size = self.active_page_size # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notifications self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_mode = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value self.log.debug( 'Setting active mode to %s.' % value) self.active_scanner.options['mode'].value = value except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed, this will # also force this value to be set again, so its safe to # return immediately self._reload_scanner_options() return # Never persist None to state if value is not None: self.application.get_state_manager()['scan_mode'] = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_resolution = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value self.log.debug( 'Setting active resolution to %s.' % value) self.active_scanner.options['resolution'].value = int(value) except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed, this will # also force this value to be set again, so its safe to # return immediately self._reload_scanner_options() return + + # Update available page sizes if resolution is relevant + if self.active_scanner.options['tl-x'].constraint_type == \ + saneme.OPTION_UNIT_PIXEL: + self._update_valid_page_sizes() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_resolution'] = value # Emit change notification self.notify_property_value_change( - 'active_resolution', None, value) + 'active_resolution', None, value) def set_prop_active_page_size(self, value): - # TODO - pass + """ + Update the scanner options and write state to the StateManager. + + See L{set_prop_active_scanner} for detailed comments. + """ + main_controller = self.application.get_main_controller() + + # Set new property value + self._prop_active_page_size = value + + # Check if a valid scanner has been loaded (not None) + if isinstance(self.active_scanner, saneme.Device): + # The device should always be open if a value is being set + assert self.active_scanner.is_open() + + # Store the current scanner value for comparison + try: + tl_x = self.active_scanner.options['tl-x'].value + tl_y = self.active_scanner.options['tl-y'].value + br_x = self.active_scanner.options['br-x'].value + br_y = self.active_scanner.options['br-y'].value + except saneme.SaneError: + exc_info = sys.exc_info() + main_controller.run_device_exception_dialog(exc_info) + + # Never re-set a value or set None to a device option + if value is not None: + if self.active_scanner.options['tl-x'].unit == saneme.OPTION_UNIT_PIXEL: + # TODO + if self.valid_resolutions == None: + raise AssertionError() + + resolution = max([int(i) for i in self.valid_resolutions]) + page_width = int(resolution * constants.PAGESIZES[value][0] / points_per_inch) + page_height = int(resolution * constants.PAGESIZES[value][1] / points_per_inch) + else: + page_width = constants.PAGESIZES[value][0] + page_height = constants.PAGESIZES[value][1] + + needs_reload = False + + if br_x - tl_x != page_width and br_y - tl_y != page_height: + try: + # Set the new option value + self.log.debug( + 'Setting active page size to %s.' % value) + + self.active_scanner.options['br-x'].value = tl_x + page_width + except saneme.SaneInexactValueError: + # TODO - what if "exact" value isn't in the list? + pass + except saneme.SaneReloadOptionsError: + # Reload any options that may have changed, this will + # also force this value to be set again, so its safe to + # return immediately + needs_reload == True + + try: + # Set the new option value + self.log.debug( + 'Setting active page size to %s.' % value) + + self.active_scanner.options['br-y'].value = tl_y + page_height + except saneme.SaneInexactValueError: + # TODO - what if "exact" value isn't in the list? + pass + except saneme.SaneReloadOptionsError: + # Reload any options that may have changed, this will + # also force this value to be set again, so its safe to + # return immediately + needs_reload == True + + if needs_reload: + self._reload_scanner_options() + return + + # Never persist None to state + if value is not None: + self.application.get_state_manager()['page_size'] = value + + # Emit change notification + self.notify_property_value_change( + 'active_page_size', None, value) def set_prop_available_scanners(self, value): """ Takes a new list of scanners, removes any which are blacklisted or unsupported, sets the new list, updates the active_scanner, and emits appropriate property callbacks. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() # Remove blacklisted scanners value = \ [scanner for scanner in value if not \ scanner.display_name in preferences_model.blacklisted_scanners] # Remove scanners that do not support necessary options or fail to # open entirely new_unavailable_scanners = [] # TODO - move somewhere more appropriate? unsupported_scanner_error = \ 'Scanner %s is unsupported for the following reason: %s' for scanner in value: try: scanner.open() unsupported = False # Enforce mode option requirements if not scanner.has_option('mode'): reason = 'No \'mode\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue mode = scanner.options['mode'] if not self.is_settable_option(mode): reason = 'Unsettable \'mode\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue if not mode.constraint_type == saneme.OPTION_CONSTRAINT_STRING_LIST: reason = '\'Mode\' option does not include a STRING_LIST constraint.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # Enforce resolution option requirements if not scanner.has_option('resolution'): reason = 'No \'resolution\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue resolution = scanner.options['resolution'] if not self.is_settable_option(resolution): reason = 'Unsettable \'resolution\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue if resolution.constraint_type == saneme.OPTION_CONSTRAINT_NONE: reason = '\'Resolution\' option does not specify a constraint.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # See SANE API 4.5.2 if resolution.type != saneme.OPTION_TYPE_INT and \ resolution.type != saneme.OPTION_TYPE_FLOAT: reason = '\'Resolution\' option is not of type INT or FLOAT.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # See SANE API 4.5.2 if not resolution.unit == saneme.OPTION_UNIT_DPI: reason = '\'Resolution\' option is not measured in DPI units.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # Enforce scan area option requirements scan_area_option_names = ['tl-x', 'tl-y', 'br-x', 'br-y'] supported = True for option_name in scan_area_option_names: if not scanner.has_option(option_name): supported = False if not supported: reason = 'No \'scan area\' options.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue scan_area_options = \ [scanner.options[o] for o in scan_area_option_names] supported = True for option in scan_area_options: if option.type != saneme.OPTION_TYPE_INT: supported = False if not supported: reason = '\'Scan area\' options are not of type INT.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue supported = True for option in scan_area_options: if option.unit != saneme.OPTION_UNIT_PIXEL and \ option.unit != saneme.OPTION_UNIT_MM: supported = False if not supported: reason = '\'Scan area\' options are not measured in unit PIXEL or MM.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue supported = True for option in scan_area_options: if option.constraint_type != saneme.OPTION_CONSTRAINT_RANGE: supported = False if not supported: reason = '\'Scan area\' options do not specify a RANGE constraint.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue scanner.close() except saneme.SaneError: reason = 'Exception raised while attempting to query device options.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue self._prop_unavailable_scanners = new_unavailable_scanners self._prop_available_scanners = value self.notify_property_value_change( 'unavailable_scanners', None, new_unavailable_scanners) self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None elif self._prop_active_scanner not in value: self.active_scanner = value[0] def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) if len(value) == 0: self.active_mode = None elif self.active_mode not in value: self.active_mode = value[0] def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) if len(value) == 0: self.active_resolution = None elif self.active_resolution not in value: self.active_resolution = value[0] def set_prop_valid_page_sizes(self, value): - # TODO - pass + """ + Set the list of valid scan page sizes, update the active page size + and write state to the StateManager. + + See L{set_prop_available_scanners} for detailed comments. + """ + self._prop_valid_page_sizes = value + + self.notify_property_value_change( + 'valid_page_sizes', None, value) + + if len(value) == 0: + self.active_page_size = None + elif self.active_page_size not in value: + self.active_page_size = value[0] # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution -# def state_scan_page_size_change(self): -# """Read state, validating the input.""" -# state_manager = self.application.get_state_manager() -# -# if state_manager['scan_page_size'] in self.valid_page_sizes: -# self.active_page_size = state_manager['scan_page_size'] -# else: -# state_manager['scan_page_size'] = self.active_page_size + def state_page_size_change(self): + """Read state, validating the input.""" + state_manager = self.application.get_state_manager() + + if state_manager['scan_page_size'] in self.valid_page_sizes: + self.active_page_size = state_manager['scan_page_size'] + else: + state_manager['scan_page_size'] = self.active_page_size # INTERNAL METHODS def is_settable_option(self, option): """ Verify an option supports minimum capabilities needed to be used by NoStaples. """ return option.is_active() and \ option.is_soft_gettable() and \ option.is_soft_settable() def _update_valid_modes(self): """ Update valid modes from the active scanner. """ self.valid_modes = self.active_scanner.options['mode'].constraint def _update_valid_resolutions(self): """ Update valid resolutions from the active scanner. """ if self.active_scanner.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_RANGE: min, max, step = self.active_scanner.options['resolution'].constraint # Fix for ticket #34. if step is None or step == 0: step = 1 resolutions = [] # If there are not an excessive number, include every possible # resolution if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: i = min while i <= max: resolutions.append(str(i)) i = i + step # Otherwise, take a crack at building a sensible set of options # that meet that constraint criteria else: # THE OLD METHOD: DID NOT WORK # i = 1 # increment = (max - min) / (constants.MAX_VALID_OPTION_VALUES - 1) # while (i <= constants.MAX_VALID_OPTION_VALUES - 2): # unrounded = min + (i * increment) # rounded = int(round(unrounded / step) * step) # resolutions.append(str(rounded)) # i = i + 1 # resolutions.insert(0, str(min)) # resolutions.append(str(max)) i = min tested_resolutions = [] while i <= max: try: self.active_scanner.options['resolution'].value = i except saneme.SANE_INFO_INEXACT: pass except saneme.SANE_INFO_RELOAD_PARAMS: pass tested_resolutions.append( self.active_scanner.options['resolution'].value) i = i + step # Prune duplicates # http://code.activestate.com/recipes/52560/ uniques = {} for j in tested_resolutions: uniques[j] = True resolutions = [str(k) for k in uniques.keys()] self._prop_valid_resolutions = resolutions elif self.active_scanner.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_VALUE_LIST: # Convert values to strings for display self.valid_resolutions = \ [str(i) for i in self.active_scanner.options['resolution'].constraint] elif self.active_scanner.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST: self.valid_resolutions = \ self.active_scanner.options['resolution'].constraint else: raise AssertionError('Unsupported constraint type.') def _update_valid_page_sizes(self): """ Update valid page sizes from the active scanner. """ tl_x = self.active_scanner.options['tl-x'] tl_y = self.active_scanner.options['tl-y'] br_x = self.active_scanner.options['br-x'] br_y = self.active_scanner.options['br-y'] sizes = [] - resolution = int(self.active_resolution) - # TODO - THIS SHOULD WORK, BE RESOLUTION NEEDS TO HAVE BEEN - # PUSHED/UPDATED (FROM CONSTRAINT) BEFORE THIS IS VALID for name, size in constants.PAGESIZES.iteritems(): if tl_x.unit == saneme.OPTION_UNIT_PIXEL: + # TODO? + if self.valid_resolutions == None: + break + + resolution = max([int(i) for i in self.valid_resolutions]) + page_width = int(resolution * size[0] / points_per_inch) page_height = int(resolution * size[1] / points_per_inch) - #print name, page_width, page_height + max_x = br_x.constraint[1] - tl_x.constraint[0] + max_y = br_y.constraint[1] - tl_y.constraint[0] - if page_width < br_x.constraint[2] - tl_x.constraint[2] and \ - page_height < br_y.constraint[2] - tl_y.cosntraint[2]: + if page_width <= max_x and page_height <= max_y: sizes.append(name) elif tl_x.unit == saneme.OPTION_UNIT_MM: page_width = int(size[0] / (points_per_cm / 10)) page_height = int(size[1] / (points_per_cm / 10)) - #print name, page_width, page_height + max_x = br_x.constraint[1] - tl_x.constraint[0] + max_y = br_y.constraint[1] - tl_y.constraint[0] - if page_width < br_x.constraint[2] - tl_x.constraint[2] and \ - page_height < br_y.constraint[2] - tl_y.cosntraint[2]: + if page_width <= max_x and page_height <= max_y: sizes.append(name) else: raise AssertionError() - - print sizes + + def page_size_sort(x, y): + """ + Sort paper sizes according to their order in a constant list. + """ + sort_x = constants.PAGESIZE_SORT_ORDER.index(x) + sort_y = constants.PAGESIZE_SORT_ORDER.index(y) + if sort_x > sort_y: + return 1 + elif sort_x == sort_y: + return 0 + else: + return -1 + + sizes.sort(page_size_sort) + self.valid_page_sizes = sizes def _reload_scanner_options(self): """ Get current scanner options from the active_scanner. Useful for reloading any option that may have changed in response to a SaneReloadOptionsError. """ main_controller = self.application.get_main_controller() self.log.debug('Reloading scanner options.') try: # Read updated values from the device new_mode = self.active_scanner.options['mode'].value new_resolution = str(self.active_scanner.options['resolution'].value) #new_page_size = ??? # Reload valid options self._update_valid_modes() self._update_valid_resolutions() self._update_valid_page_sizes() # Reset new values (in case they were overwritten) self.active_mode = new_mode self.active_resolution = new_resolution - #self.active_page_size = new_resolution + #self.active_page_size = new_page_size except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) self.log.debug('Scanner options reloaded.') \ No newline at end of file diff --git a/sane/saneme.py b/sane/saneme.py index d527ddb..079e3db 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -357,657 +357,659 @@ class Device(object): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater_update_options access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: # Lineart if sane_parameters.depth == 1: pil_image = Image.frombuffer( '1', (scan_info.width, scan_info.height), data_array, 'raw', '1', 0, 1) # Grayscale elif sane_parameters.depth == 8: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) else: raise AssertionError( 'Unexpected bit depth for monochrome scan format: %i' % sane_parameters.depth) elif sane_parameters.format == SANE_FRAME_RGB.value: # Color pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Internal methods def _load_options(self): """ Update the list of available options for this device. This is called when the Device is first instantiated and in response to any SANE_INFO_RELOAD_OPTIONS flags when setting option values. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') option_value = pointer(c_int()) status = sane_control_option( self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: raise SaneUnsupportedOperationError( 'sane_control_option reported that a value was outside the option\'s constraint.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) option_count = option_value.contents.value if self._log: self._log.debug('Device queried, %i option(s) found.', option_count) self._options.clear() i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) self._options[coption.contents.name] = Option( self, i, coption.contents, self._log) i = i + 1 class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capability = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number # String attributes should never be None self._name = ctypes_option.name if ctypes_option.name else '' self._title = ctypes_option.title if ctypes_option.title else '' self._description = ctypes_option.desc if ctypes_option.desc else '' self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: if self._type == SANE_TYPE_FIXED.value: self._constraint = ( SANE_UNFIX(ctypes_option.constraint.range.contents.min), SANE_UNFIX(ctypes_option.constraint.range.contents.max), SANE_UNFIX(ctypes_option.constraint.range.contents.quant)) else: self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 if self._type == SANE_TYPE_FIXED.value: self._constraint = [SANE_UNFIX(i) for i in self._constraint] elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 if self._type == SANE_TYPE_FIXED.value: self._constraint = [str(SANE_UNFIX(int(i))) for i in self._constraint] else: self._constraint = None # Read only properties def __get_name(self): """ Get the short-form name of this option, e.g. 'mode'. May be an empty string, but never None. """ return self._name name = property(__get_name) def __get_title(self): """ Get the full name of this option, e.g. 'Scan mode'. May be an empty string, but never None. """ return self._title title = property(__get_title) def __get_description(self): """ Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' May be an empty string, but never None. """ return self._description description = property(__get_description) def __get_type(self): """ Get the type of this option, e.g. OPTION_TYPE_STRING. """ return self._type type = property(__get_type) def __get_unit(self): """ Get the unit of this option, e.g.OPTION_UNIT_DPI. """ return self._unit unit = property(__get_unit) def __get_constraint_type(self): """ Get the type of constraint on this option, e.g. OPTION_CONSTRAINT_RANGE. """ return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_VALUE_LIST then this is a list of ints/floats which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """value Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option( handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i.' % status, device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value elif self._type == SANE_TYPE_FIXED.value: option_value = SANE_UNFIX(option_value.value) else: option_value = option_value.contents.value # if self._log: # self._log.debug( # 'Option %s queried, its current value is %s.', # self._name, # option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: raise TypeError( 'option set with %s, expected BooleanType' % type(value)) c_value = pointer(SANE_Bool(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(SANE_Int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType and type(value) is not FloatType: raise TypeError( 'option set with %s, expected IntType or FloatType' % type(value)) c_value = pointer(SANE_Fixed(SANE_FIX(value))) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: raise TypeError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: raise ValueError( 'value for option is longer than max string size') c_value = SANE_String(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: min, max, step = self._constraint if value < min: raise ValueError('value for option is less than min.') if value > max: raise ValueError('value for option is greater than max.') if step is not None and step > 0: - if value % step != 0: - raise ValueError( - 'value for option is not evenly divisible by step.') + #if value % step != 0: + # raise ValueError( + # 'value for option is not evenly divisible by step.') + print step, value + pass elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i .' % status, device=self._device) # if self._log: # self._log.debug('Option %s set to value %s.', self._name, value) # See SANE API 4.3.7 if info_flags.value & SANE_INFO_RELOAD_OPTIONS: self._device._load_options() raise SaneReloadOptionsError() # Catching this can not be avoided by constraint checking, as some # devices restrict option values without setting a constraint range # step. if info_flags.value & SANE_INFO_INEXACT: raise SaneInexactValueError() # TODO? if info_flags.value & SANE_INFO_RELOAD_PARAMS: pass value = property(__get_value, __set_value) # PUBLIC METHODS def is_soft_settable(self): """ Returns True if the option can be set by software. """ return self._capability & SANE_CAP_SOFT_SELECT def is_hard_settable(self): """ Returns True if the option can be set by hardware. """ return self._capability & SANE_CAP_HARD_SELECT def is_soft_gettable(self): """ Returns True if the option can be read by software. """ return self._capability & SANE_CAP_SOFT_DETECT def is_emulated(self): """ Returns True if the option is emulated by the backend driver. """ return self._capability & SANE_CAP_EMULATED # def is_automatic(self): # return self._capability & SANE_CAP_AUTOMATIC def is_active(self): """ Returns False if this device is unavailable because of the value of some other option. """ return not self._capability & SANE_CAP_INACTIVE # def is_advanced(self): # return self._capability & SANE_CAP_ADVANCED class ScanInfo(object): """ Contains the parameters and progress of a scan in progress. """ _width = 0 _height = 0 _depth = 0 _total_bytes = 0 def __init__(self, sane_parameters): """ Initialize the ScanInfo object from the sane_parameters. """ self._width = sane_parameters.pixels_per_line self._height = sane_parameters.lines self._depth = sane_parameters.depth self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines # Read only properties def __get_width(self): """Get the width of the current scan, in pixels.""" return self._width width = property(__get_width) def __get_height(self): """Get the height of the current scan, in pixels.""" return self._height height = property(__get_height) def __get_depth(self): """Get the depth of the current scan, in bits.""" return self._depth depth = property(__get_depth) def __get_total_bytes(self): """Get the total number of bytes comprising this scan.""" return self._total_bytes total_bytes = property(__get_total_bytes) \ No newline at end of file diff --git a/views/main.py b/views/main.py index d6ecf17..1f08f38 100644 --- a/views/main.py +++ b/views/main.py @@ -1,178 +1,179 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainView which exposes the application's main window. """ import logging import os import gtk from gtkmvc.view import View from nostaples import constants class MainView(View): """ Exposes the application's main window. """ def __init__(self, application): """ Constructs the MainView, including setting up controls that could not be configured in Glade and constructing sub-views. """ self.application = application scan_window_glade = os.path.join( constants.GUI_DIRECTORY, 'scan_window.glade') View.__init__( self, application.get_main_controller(), scan_window_glade, ['scan_window', 'progress_window'], None, False) self.log = logging.getLogger(self.__class__.__name__) # Setup controls which can not be configured in Glade self['scan_window'].set_geometry_hints(min_width=600, min_height=400) # Setup sub views document_view = self.application.get_document_view() document_view['document_view_horizontal_box'].reparent( self['document_view_docking_viewport']) self['document_view_docking_viewport'].show_all() status_view = self.application.get_status_view() status_view['statusbar'].reparent( self['status_view_docking_viewport']) self['status_view_docking_viewport'].show_all() # All controls are disabled by default, they become # avaiable when an event indicates that they should be. self.set_scan_controls_sensitive(False) self.set_file_controls_sensitive(False) self.set_delete_controls_sensitive(False) self.set_zoom_controls_sensitive(False) self.set_adjustment_controls_sensitive(False) self.set_navigation_controls_sensitive(False) document_view.set_adjustments_sensitive(False) application.get_main_controller().register_view(self) self.log.debug('Created.') def set_file_controls_sensitive(self, sensitive): """ Enables or disables all gui widgets related to saving. """ self['save_as_menu_item'].set_sensitive(sensitive) self['save_as_button'].set_sensitive(sensitive) def set_scan_controls_sensitive(self, sensitive): """ Enables or disables all gui widgets related to scanning and setting of scanner options. """ self['scan_menu_item'].set_sensitive(sensitive) self['scan_button'].set_sensitive(sensitive) self['scanner_menu_item'].set_sensitive(sensitive) self['scan_mode_menu_item'].set_sensitive(sensitive) self['scan_resolution_menu_item'].set_sensitive(sensitive) + self['scan_page_size_menu_item'].set_sensitive(sensitive) def set_refresh_scanner_controls_sensitive(self, sensitive): """ Enable or disable all gui widgets related to refreshing the available hardware for scanning. """ self['refresh_available_scanners_menu_item'].set_sensitive(sensitive) self['refresh_available_scanners_button'].set_sensitive(sensitive) def set_delete_controls_sensitive(self, sensitive): """ Enables or disables all gui widgets related to deleting or reordering pages. """ self['delete_menu_item'].set_sensitive(sensitive) def set_zoom_controls_sensitive(self, sensitive): """ Enables or disables all gui widgets related to zooming. """ self['zoom_in_menu_item'].set_sensitive(sensitive) self['zoom_out_menu_item'].set_sensitive(sensitive) self['zoom_one_to_one_menu_item'].set_sensitive(sensitive) self['zoom_best_fit_menu_item'].set_sensitive(sensitive) self['zoom_in_button'].set_sensitive(sensitive) self['zoom_out_button'].set_sensitive(sensitive) self['zoom_one_to_one_button'].set_sensitive(sensitive) self['zoom_best_fit_button'].set_sensitive(sensitive) def set_adjustment_controls_sensitive(self, sensitive): """ Enables or disables all gui widgets related to making adjustments to the current page. """ self['rotate_counter_clockwise_menu_item'].set_sensitive(sensitive) self['rotate_clockwise_menu_item'].set_sensitive(sensitive) self['rotate_all_pages_menu_item'].set_sensitive(sensitive) self['rotate_counter_clockwise_button'].set_sensitive(sensitive) self['rotate_clockwise_button'].set_sensitive(sensitive) self.application.get_document_view().set_adjustments_sensitive(sensitive) def set_navigation_controls_sensitive(self, sensitive): """ Enables or disables all gui widgets related to navigation. """ self['go_first_menu_item'].set_sensitive(sensitive) self['go_previous_menu_item'].set_sensitive(sensitive) self['go_next_menu_item'].set_sensitive(sensitive) self['go_last_menu_item'].set_sensitive(sensitive) self['go_first_button'].set_sensitive(sensitive) self['go_previous_button'].set_sensitive(sensitive) self['go_next_button'].set_sensitive(sensitive) self['go_last_button'].set_sensitive(sensitive) def run_device_exception_dialog(self, exc_info): """ Display an error dialog that provides the user with the option of blacklisting the device which caused the error. TODO: Rebuild dialog in Glade. """ dialog = gtk.MessageDialog( parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_NONE) dialog.set_title('') primary = "<big><b>A hardware exception has been logged.</b></big>" secondary = '<b>Device:</b> %s\n<b>Exception:</b> %s\n\n%s' % ( exc_info[1].device.display_name, exc_info[1].message, 'If this error continues to occur you may choose to blacklist the device so that it no longer appears in the list of available scanners.') dialog.set_markup(primary) dialog.format_secondary_markup(secondary) dialog.add_button('Blacklist Device', constants.RESPONSE_BLACKLIST_DEVICE) dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) response = dialog.run() dialog.destroy() return response \ No newline at end of file
onyxfish/nostaples
83572093c23f2df6f7f1ab99d0002acd0d0e7172
Variety of incremental work toward page size support.
diff --git a/controllers/save.py b/controllers/save.py index 4153dcd..c0d19d9 100644 --- a/controllers/save.py +++ b/controllers/save.py @@ -1,310 +1,309 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{SaveController}, which manages interaction between the L{SaveModel} and L{SaveView}. """ import logging import os import sys import tempfile import gtk from gtkmvc.controller import Controller import Image, ImageEnhance from reportlab.pdfgen.canvas import Canvas as PdfCanvas from reportlab.lib.pagesizes import landscape, portrait -from reportlab.lib.units import inch as points_per_inch -from reportlab.lib.units import mm as points_per_mm +from reportlab.lib.pagesizes import inch as points_per_inch from nostaples import constants import nostaples.utils.gui class SaveController(Controller): """ Manages interaction between the L{SaveModel} and L{SaveView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the SaveController. """ self.application = application Controller.__init__(self, application.get_save_model()) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) preferences_model = self.application.get_preferences_model() save_model = self.application.get_save_model() # Force refresh of keyword list keywords_liststore = view['keywords_entry'].get_liststore() keywords_liststore.clear() for keyword in preferences_model.saved_keywords: keywords_liststore.append([keyword]) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ self.adapt('title', 'title_entry') self.adapt('author', 'author_entry') self.adapt('keywords', 'keywords_entry') self.adapt('show_document_metadata', 'document_metadata_expander') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS def on_title_from_filename_button_clicked(self, button): """ Copy the selected filename to the pdf title property. """ save_view = self.application.get_save_view() title = save_view['save_dialog'].get_filename() if not title: save_view['title_entry'].set_text('') return title = title.split('/')[-1] if title[-4:] == '.pdf': title = title[:-4] save_view['title_entry'].set_text(title) def on_clear_title_button_clicked(self, button): """Clear the title.""" self.application.get_save_model().title = '' def on_clear_author_button_clicked(self, button): """Clear the author.""" self.application.get_save_model().author = '' def on_clear_keywords_button_clicked(self, button): """Clear the keywords.""" self.application.get_save_model().keywords = '' def on_save_dialog_response(self, dialog, response): """ Determine the selected file type and invoke the method that saves that file type. """ save_model = self.application.get_save_model() save_view = self.application.get_save_view() main_view = self.application.get_main_view() save_view['save_dialog'].hide() if response != gtk.RESPONSE_ACCEPT: return main_view['scan_window'].window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH)) nostaples.utils.gui.flush_pending_events() save_model.filename = save_view['save_dialog'].get_filename() filename_filter = save_view['save_dialog'].get_filter() if filename_filter.get_name() == 'PDF Files': if save_model.filename[-4:] != '.pdf': save_model.filename = ''.join([save_model.filename, '.pdf']) self._save_pdf() else: self.log.error('Unknown file type: %s.' % save_model.filename) self._update_saved_keywords() main_view['scan_window'].window.set_cursor(None) save_model.save_path = save_view['save_dialog'].get_current_folder() # PROPERTY CALLBACKS def property_saved_keywords_value_change(self, model, old_value, new_value): """ Update the keywords auto-completion control with the new keywords. """ save_view = self.application.get_save_view() keywords_liststore = save_view['keywords_entry'].get_liststore() keywords_liststore.clear() for keyword in new_value: keywords_liststore.append([keyword]) # PRIVATE METHODS def _save_pdf(self): """ Output the current document to a PDF file using ReportLab. """ save_model = self.application.get_save_model() save_view = self.application.get_save_view() document_model = self.application.get_document_model() # TODO: seperate saving code into its own thread? # Setup output pdf pdf = PdfCanvas(save_model.filename) pdf.setTitle(save_model.title) pdf.setAuthor(save_model.author) pdf.setKeywords(save_model.keywords) # Generate pages page_iter = document_model.get_iter_first() while page_iter: current_page = document_model.get_value(page_iter, 0) # Write transformed image temp_file_path = ''.join([tempfile.mktemp(), '.bmp']) current_page.pil_image.save(temp_file_path) assert os.path.exists(temp_file_path), \ 'Temporary bitmap file was not created by PIL.' width_in_inches = \ int(current_page.width / current_page.resolution) height_in_inches = \ int(current_page.height / current_page.resolution) # NB: Because not all SANE backends support specifying the size # of the scan area, the best we can do is scan at the default # setting and then convert that to an appropriate PDF. For the # vast majority of scanners we hope that this would be either # letter or A4. pdf_width, pdf_height = self._determine_best_fitting_pagesize( width_in_inches, height_in_inches) pdf.setPageSize((pdf_width, pdf_height)) pdf.drawImage( temp_file_path, 0, 0, width=pdf_width, height=pdf_height, preserveAspectRatio=True) pdf.showPage() os.remove(temp_file_path) page_iter = document_model.iter_next(page_iter) # Save complete PDF pdf.save() assert os.path.exists(save_model.filename), \ 'Final PDF file was not created by ReportLab.' document_model.clear() def _determine_best_fitting_pagesize(self, width_in_inches, height_in_inches): """ Searches through the possible page sizes and finds the smallest one that will contain the image without cropping. """ image_width_in_points = width_in_inches * points_per_inch image_height_in_points = height_in_inches * points_per_inch nearest_size = None nearest_distance = sys.maxint for size in constants.PAGESIZES.values(): # Orient the size to match the page if image_width_in_points > image_height_in_points: size = landscape(size) else: size = portrait(size) # Only compare the size if its large enough to contain the entire # image if size[0] < image_width_in_points or \ size[1] < image_height_in_points: continue # Compute distance for comparison distance = \ size[0] - image_width_in_points + \ size[1] - image_height_in_points # Save if closer than prior nearest distance if distance < nearest_distance: nearest_distance = distance nearest_size = size # Stop searching if a perfect match is found if nearest_distance == 0: break assert nearest_size != None, 'No nearest size found.' return nearest_size def _update_saved_keywords(self): """ Update the saved keywords with any new keywords that have been used. """ preferences_model = self.application.get_preferences_model() save_model = self.application.get_save_model() new_keywords = [] for keyword in save_model.keywords.split(): if keyword not in preferences_model.saved_keywords: new_keywords.append(keyword) if new_keywords: temp_list = [] temp_list.extend(preferences_model.saved_keywords) temp_list.extend(new_keywords) temp_list.sort() preferences_model.saved_keywords = temp_list # PUBLIC METHODS def run(self): """Run the save dialog.""" save_model = self.application.get_save_model() save_view = self.application.get_save_view() status_controller = self.application.get_status_controller() save_view['save_dialog'].set_current_folder(save_model.save_path) save_view['save_dialog'].set_current_name('') status_controller.push(self.status_context, 'Saving...') save_view.run() status_controller.pop(self.status_context) \ No newline at end of file diff --git a/models/main.py b/models/main.py index d2ab70b..248bfc9 100644 --- a/models/main.py +++ b/models/main.py @@ -1,691 +1,714 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model +from reportlab.lib.pagesizes import inch as points_per_inch +from reportlab.lib.pagesizes import cm as points_per_cm from nostaples import constants import nostaples.sane as saneme from nostaples.utils import properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, + 'active_page_size' : None, 'available_scanners' : [], # [] of saneme.Device 'unavailable_scanners' : [], # [] of (saneme.Device.display_name, reason) tuples 'valid_modes' : [], 'valid_resolutions' : [], - 'valid_page_sizes' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ - - print self.scan_area Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) +# self.active_page_size = state_manager.init_state( +# 'page_size', constants.DEFAULT_PAGE_SIZE, +# self.state_page_size_change) + # PROPERTY SETTERS set_prop_show_toolbar = properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it's option constraints can be queried without error. if value is not None: # Verify that the proper type is being set assert isinstance(value, saneme.Device) # Open the new scanner - try: - value.open() - except saneme.SaneError: - exc_info = sys.exc_info() - main_controller.run_device_exception_dialog(exc_info) - - # Load the option constraints (valid_modes, etc.) for the new device - self._load_scanner_option_constraints() - - # Manually constrain option values - if self._prop_active_mode not in self._prop_valid_modes: - self._prop_active_mode = self._prop_valid_modes[0] - - if self._prop_active_resolution not in self._prop_valid_resolutions: - self._prop_active_resolution = self._prop_valid_resolutions[0] - - # Manually push option values to new device try: - try: - value.options['mode'].value = self._prop_active_mode - except saneme.SaneReloadOptionsError: - pass - - try: - value.options['resolution'].value = \ - int(self._prop_active_resolution) - except saneme.SaneReloadOptionsError: - pass + self.log.debug( + 'Setting active scanner to %s.' % value.display_name) + value.open() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) - - # Emit change notifications for manually updated properties - - self.notify_property_value_change( - 'valid_modes', None, self.valid_modes) - - self.notify_property_value_change( - 'valid_resolutions', None, self.valid_resolutions) - - self.notify_property_value_change( - 'active_mode', None, self.active_mode) - - self.notify_property_value_change( - 'active_resolution', None, self.active_resolution) + + # Get valid options from the new device and then reset the + # previous options if they exist on the new device + self._update_valid_modes() + self.active_mode = self.active_mode + self._update_valid_resolutions() + self.active_resolution = self.active_resolution + self._update_valid_page_sizes() + self.active_page_size = self.active_page_size # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notifications self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() - + # Set new property value self._prop_active_mode = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value + self.log.debug( + 'Setting active mode to %s.' % value) self.active_scanner.options['mode'].value = value except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed, this will # also force this value to be set again, so its safe to # return immediately self._reload_scanner_options() return # Never persist None to state if value is not None: self.application.get_state_manager()['scan_mode'] = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_resolution = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value + self.log.debug( + 'Setting active resolution to %s.' % value) self.active_scanner.options['resolution'].value = int(value) except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed, this will # also force this value to be set again, so its safe to # return immediately self._reload_scanner_options() return # Never persist None to state if value is not None: self.application.get_state_manager()['scan_resolution'] = value # Emit change notification self.notify_property_value_change( 'active_resolution', None, value) + def set_prop_active_page_size(self, value): + # TODO + pass + def set_prop_available_scanners(self, value): """ Takes a new list of scanners, removes any which are blacklisted or unsupported, sets the new list, updates the active_scanner, and emits appropriate property callbacks. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() # Remove blacklisted scanners value = \ [scanner for scanner in value if not \ scanner.display_name in preferences_model.blacklisted_scanners] # Remove scanners that do not support necessary options or fail to # open entirely new_unavailable_scanners = [] # TODO - move somewhere more appropriate? unsupported_scanner_error = \ 'Scanner %s is unsupported for the following reason: %s' for scanner in value: try: scanner.open() unsupported = False # Enforce mode option requirements if not scanner.has_option('mode'): reason = 'No \'mode\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue mode = scanner.options['mode'] if not self.is_settable_option(mode): reason = 'Unsettable \'mode\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue if not mode.constraint_type == saneme.OPTION_CONSTRAINT_STRING_LIST: reason = '\'Mode\' option does not include a STRING_LIST constraint.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # Enforce resolution option requirements if not scanner.has_option('resolution'): reason = 'No \'resolution\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue resolution = scanner.options['resolution'] if not self.is_settable_option(resolution): reason = 'Unsettable \'resolution\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue + + if resolution.constraint_type == saneme.OPTION_CONSTRAINT_NONE: + reason = '\'Resolution\' option does not specify a constraint.' + self.log.info(unsupported_scanner_error % + (scanner.display_name, reason)) + new_unavailable_scanners.append((scanner.display_name, reason)) + value.remove(scanner) + continue # See SANE API 4.5.2 if resolution.type != saneme.OPTION_TYPE_INT and \ resolution.type != saneme.OPTION_TYPE_FLOAT: reason = '\'Resolution\' option is not of type INT or FLOAT.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # See SANE API 4.5.2 if not resolution.unit == saneme.OPTION_UNIT_DPI: reason = '\'Resolution\' option is not measured in DPI units.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue # Enforce scan area option requirements scan_area_option_names = ['tl-x', 'tl-y', 'br-x', 'br-y'] supported = True for option_name in scan_area_option_names: if not scanner.has_option(option_name): supported = False if not supported: reason = 'No \'scan area\' options.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue scan_area_options = \ [scanner.options[o] for o in scan_area_option_names] supported = True for option in scan_area_options: if option.type != saneme.OPTION_TYPE_INT: supported = False if not supported: reason = '\'Scan area\' options are not of type INT.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue supported = True for option in scan_area_options: if option.unit != saneme.OPTION_UNIT_PIXEL and \ option.unit != saneme.OPTION_UNIT_MM: supported = False if not supported: reason = '\'Scan area\' options are not measured in unit PIXEL or MM.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue supported = True for option in scan_area_options: if option.constraint_type != saneme.OPTION_CONSTRAINT_RANGE: supported = False if not supported: reason = '\'Scan area\' options do not specify a RANGE constraint.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue scanner.close() except saneme.SaneError: reason = 'Exception raised while attempting to query device options.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) continue self._prop_unavailable_scanners = new_unavailable_scanners self._prop_available_scanners = value self.notify_property_value_change( 'unavailable_scanners', None, new_unavailable_scanners) self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None elif self._prop_active_scanner not in value: self.active_scanner = value[0] def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) if len(value) == 0: self.active_mode = None elif self.active_mode not in value: self.active_mode = value[0] def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) if len(value) == 0: self.active_resolution = None elif self.active_resolution not in value: self.active_resolution = value[0] - - def set_prop_scan_area(self, value): - """ - Set the valid scan area for the current scanner. Derive and set - valid pages sizes. - - See L{set_prop_available_scanners} for detailed comments. - """ - self._prop_scan_area = value - - self.notify_property_value_change( - 'scan_area', None, value) def set_prop_valid_page_sizes(self, value): + # TODO pass # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution + +# def state_scan_page_size_change(self): +# """Read state, validating the input.""" +# state_manager = self.application.get_state_manager() +# +# if state_manager['scan_page_size'] in self.valid_page_sizes: +# self.active_page_size = state_manager['scan_page_size'] +# else: +# state_manager['scan_page_size'] = self.active_page_size # INTERNAL METHODS def is_settable_option(self, option): """ Verify an option supports minimum capabilities needed to be used by NoStaples. """ return option.is_active() and \ option.is_soft_gettable() and \ option.is_soft_settable() - def _load_scanner_option_constraints(self): + def _update_valid_modes(self): """ - Load the option constraints from a specified scanner. + Update valid modes from the active scanner. """ - main_controller = self.application.get_main_controller() - - try: - # Mode - self._prop_valid_modes = self.active_scanner.options['mode'].constraint + self.valid_modes = self.active_scanner.options['mode'].constraint + + def _update_valid_resolutions(self): + """ + Update valid resolutions from the active scanner. + """ + if self.active_scanner.options['resolution'].constraint_type == \ + saneme.OPTION_CONSTRAINT_RANGE: + min, max, step = self.active_scanner.options['resolution'].constraint + + # Fix for ticket #34. + if step is None or step == 0: + step = 1 - # Resolution - if self.active_scanner.options['resolution'].constraint_type == \ - saneme.OPTION_CONSTRAINT_RANGE: - min, max, step = self.active_scanner.options['resolution'].constraint + resolutions = [] + + # If there are not an excessive number, include every possible + # resolution + if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: + i = min + while i <= max: + resolutions.append(str(i)) + i = i + step + # Otherwise, take a crack at building a sensible set of options + # that meet that constraint criteria + else: + # THE OLD METHOD: DID NOT WORK +# i = 1 +# increment = (max - min) / (constants.MAX_VALID_OPTION_VALUES - 1) +# while (i <= constants.MAX_VALID_OPTION_VALUES - 2): +# unrounded = min + (i * increment) +# rounded = int(round(unrounded / step) * step) +# resolutions.append(str(rounded)) +# i = i + 1 +# resolutions.insert(0, str(min)) +# resolutions.append(str(max)) + + i = min + tested_resolutions = [] + while i <= max: + try: + self.active_scanner.options['resolution'].value = i + except saneme.SANE_INFO_INEXACT: + pass + except saneme.SANE_INFO_RELOAD_PARAMS: + pass + + tested_resolutions.append( + self.active_scanner.options['resolution'].value) + i = i + step - # Fix for ticket #34. - if step is None or step == 0: - step = 1 + # Prune duplicates + # http://code.activestate.com/recipes/52560/ + uniques = {} + for j in tested_resolutions: + uniques[j] = True - resolutions = [] + resolutions = [str(k) for k in uniques.keys()] - # If there are not an excessive number, include every possible - # resolution - if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: - i = min - while i <= max: - resolutions.append(str(i)) - i = i + step - # Otherwise, take a crack at building a sensible set of options - # that mean that constraint criteria - else: - i = 1 - increment = (max - min) / (constants.MAX_VALID_OPTION_VALUES - 1) - while (i <= constants.MAX_VALID_OPTION_VALUES - 2): - unrounded = min + (i * increment) - rounded = int(round(unrounded / step) * step) - resolutions.append(str(rounded)) - i = i + 1 - resolutions.insert(0, str(min)) - resolutions.append(str(max)) - - self._prop_valid_resolutions = resolutions - elif self.active_scanner.options['resolution'].constraint_type == \ - saneme.OPTION_CONSTRAINT_VALUE_LIST: - # Convert values to strings for display - self._prop_valid_resolutions = \ - [str(i) for i in self.active_scanner.options['resolution'].constraint] - elif self.active_scanner.options['resolution'].constraint_type == \ - saneme.OPTION_CONSTRAINT_STRING_LIST: - self._prop_valid_resolutions = \ - self.active_scanner.options['resolution'].constraint + self._prop_valid_resolutions = resolutions + elif self.active_scanner.options['resolution'].constraint_type == \ + saneme.OPTION_CONSTRAINT_VALUE_LIST: + # Convert values to strings for display + self.valid_resolutions = \ + [str(i) for i in self.active_scanner.options['resolution'].constraint] + elif self.active_scanner.options['resolution'].constraint_type == \ + saneme.OPTION_CONSTRAINT_STRING_LIST: + self.valid_resolutions = \ + self.active_scanner.options['resolution'].constraint + else: + raise AssertionError('Unsupported constraint type.') + + def _update_valid_page_sizes(self): + """ + Update valid page sizes from the active scanner. + """ + tl_x = self.active_scanner.options['tl-x'] + tl_y = self.active_scanner.options['tl-y'] + br_x = self.active_scanner.options['br-x'] + br_y = self.active_scanner.options['br-y'] + + sizes = [] + resolution = int(self.active_resolution) + + # TODO - THIS SHOULD WORK, BE RESOLUTION NEEDS TO HAVE BEEN + # PUSHED/UPDATED (FROM CONSTRAINT) BEFORE THIS IS VALID + for name, size in constants.PAGESIZES.iteritems(): + if tl_x.unit == saneme.OPTION_UNIT_PIXEL: + page_width = int(resolution * size[0] / points_per_inch) + page_height = int(resolution * size[1] / points_per_inch) + + #print name, page_width, page_height + + if page_width < br_x.constraint[2] - tl_x.constraint[2] and \ + page_height < br_y.constraint[2] - tl_y.cosntraint[2]: + sizes.append(name) + elif tl_x.unit == saneme.OPTION_UNIT_MM: + page_width = int(size[0] / (points_per_cm / 10)) + page_height = int(size[1] / (points_per_cm / 10)) + + #print name, page_width, page_height + + if page_width < br_x.constraint[2] - tl_x.constraint[2] and \ + page_height < br_y.constraint[2] - tl_y.cosntraint[2]: + sizes.append(name) else: - raise AssertionError('Unsupported constraint type.') + raise AssertionError() - # Page size - tl_x = self.active_scanner.options['tl-x'] - tl_y = self.active_scanner.options['tl-y'] - br_x = self.active_scanner.options['br-x'] - br_y = self.active_scanner.options['br-y'] - - sizes = [] - - # TODO -# for pagesize in constants.PAGESIZES.values(): -# if tl_x.unit == saneme.OPTION_UNIT_PIXEL: -# print self.active_scanner.options['resolution'].value -# print br_x.constraint -# try: -# self.active_scanner.options['resolution'].value = 150 -# except: -# pass -# print self.active_scanner.options['resolution'].value -# print br_x.constraint -# elif tl_x.unit == saneme.OPTION_UNIT_MM: -# pass -# else: -# raise AssertionError() - except saneme.SaneError: - exc_info = sys.exc_info() - main_controller.run_device_exception_dialog(exc_info) + print sizes def _reload_scanner_options(self): """ Get current scanner options from the active_scanner. Useful for reloading any option that may have changed in response to a SaneReloadOptionsError. """ main_controller = self.application.get_main_controller() self.log.debug('Reloading scanner options.') try: - # Load the option constraints - self._load_scanner_option_constraints() - - # Push notifications of changes - self.notify_property_value_change( - 'valid_modes', None, self.valid_modes) + # Read updated values from the device + new_mode = self.active_scanner.options['mode'].value + new_resolution = str(self.active_scanner.options['resolution'].value) + #new_page_size = ??? - self.notify_property_value_change( - 'valid_resolutions', None, self.valid_resolutions) + # Reload valid options + self._update_valid_modes() + self._update_valid_resolutions() + self._update_valid_page_sizes() - # Read updated values from the device - self.active_mode = self.active_scanner.options['mode'].value - self.active_resolution = str(self.active_scanner.options['resolution'].value) + # Reset new values (in case they were overwritten) + self.active_mode = new_mode + self.active_resolution = new_resolution + #self.active_page_size = new_resolution except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) self.log.debug('Scanner options reloaded.') \ No newline at end of file
onyxfish/nostaples
a983e264d544f84083cb1231c47cf588844331c7
Revised handling of SANE's ReloadOptions flag.
diff --git a/sane/saneme.py b/sane/saneme.py index 2e693f1..7e12524 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -1,1012 +1,1013 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module contains the Pythonic implementation of the SANE API. The flat C functions have been wrapped in a set of objects and all ctypes of the underlying implmentation have been hidden from the user's view. This enumerations and definiations which are absolutely necessary to the end user have been redeclared. """ # TODO: document what exceptions can be thrown by each method, # including those that could bubble up from array import * import atexit import ctypes from types import * from PIL import Image from errors import * from saneh import * # Redeclare saneh enumerations which are visible to the application (OPTION_TYPE_BOOL, OPTION_TYPE_INT, # Automatically converted from SANE_TYPE_FIXED OPTION_TYPE_FLOAT, OPTION_TYPE_STRING, OPTION_TYPE_BUTTON, OPTION_TYPE_GROUP) = xrange(6) (OPTION_UNIT_NONE, OPTION_UNIT_PIXEL, OPTION_UNIT_BIT, OPTION_UNIT_MM, OPTION_UNIT_DPI, OPTION_UNIT_PERCENT, OPTION_UNIT_MICROSECOND) = xrange(7) (OPTION_CONSTRAINT_NONE, OPTION_CONSTRAINT_RANGE, OPTION_CONSTRAINT_VALUE_LIST, OPTION_CONSTRAINT_STRING_LIST) = xrange(4) class SaneMe(object): """ The top-level object for interacting with the SANE API. Handles polling for devices. This object should only be instantiated once. """ _log = None _version = None # (major, minor, build) _devices = [] def __init__(self, log=None): """ Create the SANE object, perform setup, and register the cleanup function. @param log: an optional Python logging object to log to. """ self._log = log self._setup() atexit.register(self._shutdown) # Read only properties def __get_version(self): """Get the current installed version of SANE.""" return self._version version = property(__get_version) def _setup(self): """ Iniitalize SANE and retrieve the current installed version. """ version_code = SANE_Int() auth_callback = SANE_Auth_Callback(self._sane_auth_callback) status = sane_init(byref(version_code), auth_callback) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_init returned an invalid status: %i.' % status) self._version = (SANE_VERSION_MAJOR(version_code), SANE_VERSION_MINOR(version_code), SANE_VERSION_BUILD(version_code)) if self._log: self._log.info('SANE version %s initalized.', self._version) def _sane_auth_callback(self, resource, username, password): """ TODO """ raise NotImplementedError( 'sane_auth_callback requested, but not yet implemented.') def _shutdown(self): """ Deinitialize SANE. This code would go in __del__, but it is not guaranteed that method will be called and sane_exit must be called to release resources. To ensure this method is called it is registered with atexit. """ for device in self._devices: if device.is_open(): device.close() sane_exit() self._version = None if self._log: self._log.info('SANE deinitialized.') # Public Methods def get_device_list(self): """ Poll for connected devices. This method may take several seconds to return. Note that SANE is exited and re-inited before querying for devices to workaround a limitation in SANE's USB driver which causes the device list to only be updated on init. This means that all settings applied to all devices will be B{lost} and must be restored by the calling application. This was found documented here: U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html} """ if not self._version: raise AssertionError('version was None') # See docstring for details on this voodoo self._shutdown() self._setup() cdevices = POINTER(POINTER(SANE_Device))() status = sane_get_devices(byref(cdevices), SANE_Bool(0)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_get_devices ran out of memory.') else: raise SaneUnknownError( 'sane_get_devices returned an invalid status: %i.' % status) device_count = 0 self._devices = [] while cdevices[device_count]: self._devices.append( Device(cdevices[device_count].contents, self._log)) device_count += 1 if self._log: self._log.info('SANE queried, %i device(s) found.', device_count) return self._devices def get_device_by_name(self, name): """ Retrieve a L{Device} by name. Must be preceded by a call to L{get_device_list}. """ for device in self._devices: if device.name == name: return device raise SaneNoSuchDeviceError( 'The requested device does not exist.') class Device(object): """ This is the primary object for interacting with SANE. It represents a single device and handles enumeration of options, getting and setting of options, and starting and stopping of scanning jobs. """ _log = None _handle = None _name = '' _vendor = '' _model = '' _type = '' _display_name = '' _options = {} def __init__(self, ctypes_device, log=None): """ Sets the Devices properties from a ctypes SANE_Device and queries for its available options. """ self._log = log # String attributes should never be None self._name = ctypes_device.name if ctypes_device.name else '' self._vendor = ctypes_device.vendor if ctypes_device.vendor else '' self._model = ctypes_device.model if ctypes_device.model else '' self._type = ctypes_device.type if ctypes_device.type else '' self._display_name = ' '.join([self._vendor, self._model]) # Read only properties def __get_name(self): """ Get the complete SANE identifier for this device, e.g. 'lexmark:libusb:002:006'. """ return self._name name = property(__get_name) def __get_vendor(self): """Get the manufacturer of this device, e.g. 'Lexmark'.""" return self._vendor vendor = property(__get_vendor) def __get_model(self): """Get the specific model of this device, e.g. 'X1100/rev. B2'.""" return self._model model = property(__get_model) def __get_type(self): """Get the type of this device, e.g. 'flatbed scanner'.""" return self._type type = property(__get_type) def __get_display_name(self): """ Get an appropriate name to use for displaying this device to a user, e.g. 'Lexmark X1100/rev. B2'.""" return self._display_name display_name = property(__get_display_name) def __get_options(self): """Get the dictionary of options that this device has.""" return self._options options = property(__get_options) - - # Internal methods - - def _update_options(self): - """ - Update the list of available options for this device. As these - are immutable, this should only need to be called when the Device - is first instantiated. - """ - if not self._handle: - raise AssertionError('device handle was None.') - if self._handle == c_void_p(None): - raise AssertionError('device handle was a null pointer.') - - option_value = pointer(c_int()) - status = sane_control_option( - self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) - - if status == SANE_STATUS_GOOD.value: - pass - elif status == SANE_STATUS_UNSUPPORTED.value: - raise SaneUnsupportedOperationError( - 'sane_control_option reported that a value was outside the option\'s constraint.', - device=self) - elif status == SANE_STATUS_INVAL.value: - raise SaneInvalidParameterError( - 'sane_open reported that the device name was invalid.', - device=self) - elif status == SANE_STATUS_IO_ERROR.value: - raise SaneIOError( - 'sane_open reported a communications error.', - device=self) - elif status == SANE_STATUS_NO_MEM.value: - raise SaneOutOfMemoryError( - 'sane_open ran out of memory.', - device=self) - elif status == SANE_STATUS_ACCESS_DENIED.value: - raise SaneAccessDeniedError( - 'sane_open requires greater access to open the device.', - device=self) - else: - raise SaneUnknownError( - 'sane_open returned an invalid status: %i.' % status, - device=self) - - option_count = option_value.contents.value - - if self._log: - self._log.debug('Device queried, %i option(s) found.', option_count) - - self._options.clear() - - i = 1 - while(i < option_count - 1): - coption = sane_get_option_descriptor(self._handle, i) - self._options[coption.contents.name] = Option( - self, i, coption.contents, self._log) - i = i + 1 - - # Methods for use only by Options - - def _get_handle(self): - """ - Verify that the device is open and get the current open handle. - - To be called by Options of this device so that they may set themselves. - """ - if not self._handle: - raise AssertionError('device handle was None.') - if self._handle == c_void_p(None): - raise AssertionError('device handle was a null pointer.') - - return self._handle # Public methods def open(self): """ Open a new handle to this device. Must be called before any operations (including getting or setting options) are performed on this device. """ if self._handle: raise AssertionError('device handle already exists.') self._handle = SANE_Handle() status = sane_open(self.name, byref(self._handle)) # If and exception will be thrown, nullify device handle # so is_open() will return false for the device. if status != SANE_STATUS_GOOD.value: self._handle = None if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_open reported that the device was busy.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) - self._update_options() + self._load_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) def has_option(self, option_name): """Return true if option_name is available for this scanner.""" return (option_name in self.options.keys()) def scan(self, progress_callback=None): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( - 'sane_read requires greater access to open the device.', + 'sane_read requires greater_update_options access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: # Lineart if sane_parameters.depth == 1: pil_image = Image.frombuffer( '1', (scan_info.width, scan_info.height), data_array, 'raw', '1', 0, 1) # Grayscale elif sane_parameters.depth == 8: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) else: raise AssertionError( 'Unexpected bit depth for monochrome scan format: %i' % sane_parameters.depth) elif sane_parameters.format == SANE_FRAME_RGB.value: # Color pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image + + # Methods for use only by Options + + def _get_handle(self): + """ + Verify that the device is open and get the current open handle. + + To be called by Options of this device so that they may set themselves. + """ + if not self._handle: + raise AssertionError('device handle was None.') + if self._handle == c_void_p(None): + raise AssertionError('device handle was a null pointer.') + + return self._handle + + # Internal methods + + def _load_options(self): + """ + Update the list of available options for this device. This is called + when the Device is first instantiated and in response to any + SANE_INFO_RELOAD_OPTIONS flags when setting option values. + """ + if not self._handle: + raise AssertionError('device handle was None.') + if self._handle == c_void_p(None): + raise AssertionError('device handle was a null pointer.') + + option_value = pointer(c_int()) + status = sane_control_option( + self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) + + if status == SANE_STATUS_GOOD.value: + pass + elif status == SANE_STATUS_UNSUPPORTED.value: + raise SaneUnsupportedOperationError( + 'sane_control_option reported that a value was outside the option\'s constraint.', + device=self) + elif status == SANE_STATUS_INVAL.value: + raise SaneInvalidParameterError( + 'sane_open reported that the device name was invalid.', + device=self) + elif status == SANE_STATUS_IO_ERROR.value: + raise SaneIOError( + 'sane_open reported a communications error.', + device=self) + elif status == SANE_STATUS_NO_MEM.value: + raise SaneOutOfMemoryError( + 'sane_open ran out of memory.', + device=self) + elif status == SANE_STATUS_ACCESS_DENIED.value: + raise SaneAccessDeniedError( + 'sane_open requires greater access to open the device.', + device=self) + else: + raise SaneUnknownError( + 'sane_open returned an invalid status: %i.' % status, + device=self) + + option_count = option_value.contents.value + + if self._log: + self._log.debug('Device queried, %i option(s) found.', option_count) + + self._options.clear() + + i = 1 + while(i < option_count - 1): + coption = sane_get_option_descriptor(self._handle, i) + self._options[coption.contents.name] = Option( + self, i, coption.contents, self._log) + i = i + 1 class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capability = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number # String attributes should never be None self._name = ctypes_option.name if ctypes_option.name else '' self._title = ctypes_option.title if ctypes_option.title else '' self._description = ctypes_option.desc if ctypes_option.desc else '' self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: if self._type == SANE_TYPE_FIXED.value: self._constraint = ( SANE_UNFIX(ctypes_option.constraint.range.contents.min), SANE_UNFIX(ctypes_option.constraint.range.contents.max), SANE_UNFIX(ctypes_option.constraint.range.contents.quant)) else: self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 if self._type == SANE_TYPE_FIXED.value: self._constraint = [SANE_UNFIX(i) for i in self._constraint] elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 if self._type == SANE_TYPE_FIXED.value: self._constraint = [str(SANE_UNFIX(int(i))) for i in self._constraint] else: self._constraint = None # Read only properties def __get_name(self): """ Get the short-form name of this option, e.g. 'mode'. May be an empty string, but never None. """ return self._name name = property(__get_name) def __get_title(self): """ Get the full name of this option, e.g. 'Scan mode'. May be an empty string, but never None. """ return self._title title = property(__get_title) def __get_description(self): """ Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' May be an empty string, but never None. """ return self._description description = property(__get_description) def __get_type(self): """ Get the type of this option, e.g. OPTION_TYPE_STRING. """ return self._type type = property(__get_type) def __get_unit(self): """ Get the unit of this option, e.g.OPTION_UNIT_DPI. """ return self._unit unit = property(__get_unit) def __get_constraint_type(self): """ Get the type of constraint on this option, e.g. OPTION_CONSTRAINT_RANGE. """ return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_VALUE_LIST then this is a list of ints/floats which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """value Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option( handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i.' % status, device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value elif self._type == SANE_TYPE_FIXED.value: option_value = SANE_UNFIX(option_value.value) else: option_value = option_value.contents.value if self._log: self._log.debug( 'Option %s queried, its current value is %s.', self._name, option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: raise TypeError( 'option set with %s, expected BooleanType' % type(value)) c_value = pointer(SANE_Bool(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(SANE_Int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType and type(value) is not FloatType: raise TypeError( 'option set with %s, expected IntType or FloatType' % type(value)) c_value = pointer(SANE_Fixed(SANE_FIX(value))) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: raise TypeError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: raise ValueError( 'value for option is longer than max string size') c_value = SANE_String(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: min, max, step = self._constraint if value < min: raise ValueError('value for option is less than min.') if value > max: raise ValueError('value for option is greater than max.') if step is not None and step > 0: if value % step != 0: raise ValueError( 'value for option is not evenly divisible by step.') elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i .' % status, device=self._device) if self._log: self._log.debug('Option %s set to value %s.', self._name, value) # See SANE API 4.3.7 if info_flags.value & SANE_INFO_RELOAD_OPTIONS: + self._device._load_options() raise SaneReloadOptionsError() # Catching this can not be avoided by constraint checking, as some # devices restrict option values without setting a constraint range # step. if info_flags.value & SANE_INFO_INEXACT: raise SaneInexactValueError() # TODO? if info_flags.value & SANE_INFO_RELOAD_PARAMS: pass value = property(__get_value, __set_value) # PUBLIC METHODS def is_soft_settable(self): """ Returns True if the option can be set by software. """ return self._capability & SANE_CAP_SOFT_SELECT def is_hard_settable(self): """ Returns True if the option can be set by hardware. """ return self._capability & SANE_CAP_HARD_SELECT def is_soft_gettable(self): """ Returns True if the option can be read by software. """ return self._capability & SANE_CAP_SOFT_DETECT def is_emulated(self): """ Returns True if the option is emulated by the backend driver. """ return self._capability & SANE_CAP_EMULATED # def is_automatic(self): # return self._capability & SANE_CAP_AUTOMATIC def is_active(self): """ Returns False if this device is unavailable because of the value of some other option. """ return not self._capability & SANE_CAP_INACTIVE # def is_advanced(self): # return self._capability & SANE_CAP_ADVANCED class ScanInfo(object): """ Contains the parameters and progress of a scan in progress. """ _width = 0 _height = 0 _depth = 0 _total_bytes = 0 def __init__(self, sane_parameters): """ Initialize the ScanInfo object from the sane_parameters. """ self._width = sane_parameters.pixels_per_line self._height = sane_parameters.lines self._depth = sane_parameters.depth self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines # Read only properties def __get_width(self): """Get the width of the current scan, in pixels.""" return self._width width = property(__get_width) def __get_height(self): """Get the height of the current scan, in pixels.""" return self._height height = property(__get_height) def __get_depth(self): """Get the depth of the current scan, in bits.""" return self._depth depth = property(__get_depth) def __get_total_bytes(self): """Get the total number of bytes comprising this scan.""" return self._total_bytes total_bytes = property(__get_total_bytes) \ No newline at end of file
onyxfish/nostaples
fdd247d63d1217022d4170cc30a3d60d69e2046e
Added state validation to preferences properties.
diff --git a/controllers/preferences.py b/controllers/preferences.py index cbc4be8..d89d7b1 100644 --- a/controllers/preferences.py +++ b/controllers/preferences.py @@ -1,286 +1,290 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{PreferencesController}, which manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ import logging import gtk from gtkmvc.controller import Controller from nostaples import constants -from nostaples.utils.gui import read_combobox +from nostaples.utils.gui import read_combobox, write_combobox class PreferencesController(Controller): """ Manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the PreferencesController. """ self.application = application Controller.__init__(self, application.get_preferences_model()) application.get_main_model().register_observer(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ pass # USER INTERFACE CALLBACKS def on_preview_mode_combobox_changed(self, combobox): """Update the preview mode in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.preview_mode = \ read_combobox(preferences_view['preview_mode_combobox']) def on_thumbnail_size_combobox_changed(self, combobox): """Update the thumbnail size in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.thumbnail_size = \ int(read_combobox(preferences_view['thumbnail_size_combobox'])) def on_toolbar_style_combobox_changed(self, combobox): """Update the toolbar style in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.toolbar_style = \ read_combobox(preferences_view['toolbar_style_combobox']) def on_remove_from_blacklist_button_clicked(self, button): """ Remove the currently selected blacklist device from the list. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['blacklist_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.remove(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_add_to_blacklist_button_clicked(self, button): """ Move the currently selected available scanner to the blacklist. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['available_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_remove_from_keywords_button_clicked(self, button): """ Remove the currently selected keyword from the list. """ preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['keywords_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_keywords = list(preferences_model.saved_keywords) temp_keywords.remove(selection_text) preferences_model.saved_keywords = temp_keywords def on_blacklist_tree_view_selection_changed(self, selection): """Update the available device controls.""" self._toggle_device_controls() - + def on_available_tree_view_selection_changed(self, selection): """Update the available device controls.""" self._toggle_device_controls() def on_preferences_dialog_response(self, dialog, response): """Close the preferences dialog.""" preferences_view = self.application.get_preferences_view() preferences_view['preferences_dialog'].hide() # PROPERTY CALLBACKS def property_preview_mode_value_change(self, model, old_value, new_value): - # TODO - set the combobox (in case the change came form state) - pass + """Select the active preview mode in the combobox.""" + preferences_view = self.application.get_preferences_view() + + write_combobox(preferences_view['preview_mode_combobox'], new_value) def property_thumbnail_size_value_change(self, model, old_value, new_value): - # TODO - set the combobox (in case the change came form state) - pass + """Select the active thumbnail size in the combobox.""" + preferences_view = self.application.get_preferences_view() + + write_combobox(preferences_view['thumbnail_size_combobox'], new_value) def property_toolbar_style_value_change(self, model, old_value, new_value): - # TODO - set the combobox (in case the change came form state) - pass + """Select the active toolbar style in the combobox.""" + preferences_view = self.application.get_preferences_view() + + write_combobox(preferences_view['toolbar_style_combobox'], new_value) def property_blacklisted_scanners_value_change(self, model, old_value, new_value): """Update blacklisted scanners liststore.""" preferences_view = self.application.get_preferences_view() blacklist_liststore = preferences_view['blacklist_tree_view'].get_model() blacklist_liststore.clear() for blacklist_item in new_value: blacklist_liststore.append([blacklist_item]) self._toggle_device_controls() def property_saved_keywords_value_change(self, model, old_value, new_value): """Update keywords liststore.""" preferences_view = self.application.get_preferences_view() keywords_liststore = preferences_view['keywords_tree_view'].get_model() keywords_liststore.clear() for keyword in new_value: keywords_liststore.append([keyword]) # MainModel PROPERTY CALLBACKS def property_available_scanners_value_change(self, model, old_value, new_value): """Update available scanners liststore.""" preferences_view = self.application.get_preferences_view() available_liststore = preferences_view['available_tree_view'].get_model() available_liststore.clear() for available_item in new_value: available_liststore.append([available_item.display_name]) self._toggle_device_controls() def property_unavailable_scanners_value_change(self, model, old_value, new_value): """Update unavailable scanners liststore.""" preferences_view = self.application.get_preferences_view() unavailable_liststore = preferences_view['unavailable_tree_view'].get_model() unavailable_liststore.clear() for unavailable_item in new_value: unavailable_liststore.append(list(unavailable_item)) def property_updating_available_scanners_value_change(self, model, old_value, new_value): """ Disable device management controls while devices are being updated. """ self._toggle_device_controls() # PUBLIC METHODS def run(self): """Run the preferences dialog.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() # Force property updates when dialog is run: this handles the case # where the PreferencesController has not been created until now # so it has not been receiving property notifications. self.property_blacklisted_scanners_value_change( preferences_model, None, preferences_model.blacklisted_scanners) self.property_saved_keywords_value_change( preferences_model, None, preferences_model.saved_keywords) self.property_available_scanners_value_change( main_model, None, main_model.available_scanners) self.property_unavailable_scanners_value_change( preferences_model, None, main_model.unavailable_scanners) preferences_view.run() # PRIVATE METHODS def _toggle_device_controls(self): """ Toggle the availability of the scanner management controls based on the state of the application. """ main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() if main_model.updating_available_scanners: preferences_view['remove_from_blacklist_button'].set_sensitive(False) preferences_view['add_to_blacklist_button'].set_sensitive(False) else: if preferences_view['blacklist_tree_view'].get_selection().count_selected_rows() > 0: - #if len(preferences_model.blacklisted_scanners) > 0: preferences_view['remove_from_blacklist_button'].set_sensitive(True) else: preferences_view['remove_from_blacklist_button'].set_sensitive(False) if preferences_view['available_tree_view'].get_selection().count_selected_rows() > 0: - #if len(main_model.available_scanners) > 0: preferences_view['add_to_blacklist_button'].set_sensitive(True) else: preferences_view['add_to_blacklist_button'].set_sensitive(False) \ No newline at end of file diff --git a/models/main.py b/models/main.py index 7e179b1..a501f8f 100644 --- a/models/main.py +++ b/models/main.py @@ -1,562 +1,562 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme -import nostaples.utils.properties +from nostaples.utils import properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device 'unavailable_scanners' : [], # [] of (saneme.Device.display_name, reason) tuples 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, - nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) + properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, - nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) + properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, - nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) + properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, - nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) + properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, - nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) + properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS - set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( + set_prop_show_toolbar = properties.StatefulPropertySetter( 'show_toolbar') - set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( + set_prop_show_statusbar = properties.StatefulPropertySetter( 'show_statusbar') - set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( + set_prop_show_thumbnails = properties.StatefulPropertySetter( 'show_thumbnails') - set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( + set_prop_show_adjustments = properties.StatefulPropertySetter( 'show_adjustments') - set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( + set_prop_rotate_all_pages = properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it's option constraints can be queried without error. if value is not None: # Verify that the proper type is being set assert isinstance(value, saneme.Device) # Open the new scanner try: value.open() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Load the option constraints (valid_modes, etc.) for the new device self._load_scanner_option_constraints(value) # Manually constrain option values if self._prop_active_mode not in self._prop_valid_modes: self._prop_active_mode = self._prop_valid_modes[0] if self._prop_active_resolution not in self._prop_valid_resolutions: self._prop_active_resolution = self._prop_valid_resolutions[0] # Manually push option values to new device try: try: value.options['mode'].value = self._prop_active_mode except saneme.SaneReloadOptionsError: pass try: value.options['resolution'].value = \ int(self._prop_active_resolution) except saneme.SaneReloadOptionsError: pass except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Emit change notifications for manually updated properties self.notify_property_value_change( 'valid_modes', None, self.valid_modes) self.notify_property_value_change( 'valid_resolutions', None, self.valid_resolutions) self.notify_property_value_change( 'active_mode', None, self.active_mode) self.notify_property_value_change( 'active_resolution', None, self.active_resolution) # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notifications self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_mode = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value self.active_scanner.options['mode'].value = value except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_mode'] = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_resolution = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value self.active_scanner.options['resolution'].value = int(value) except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_resolution'] = value # Emit change notification self.notify_property_value_change( 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ Takes a new list of scanners, removes any which are blacklisted or unsupported, sets the new list, updates the active_scanner, and emits appropriate property callbacks. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() # Remove blacklisted scanners value = \ [scanner for scanner in value if not \ scanner.display_name in preferences_model.blacklisted_scanners] # Remove scanners that do not support necessary options or fail to # open entirely new_unavailable_scanners = [] # TODO - move somewhere more appropriate? unsupported_scanner_error = \ 'Scanner %s is unsupported for the following reason: %s' for scanner in value: try: scanner.open() unsupported = False # Enforce mode option requirements if not scanner.has_option('mode'): reason = 'No \'mode\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) mode = scanner.options['mode'] if not self.is_settable_option(mode): reason = 'Unsettable \'mode\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) if not mode.constraint_type == saneme.OPTION_CONSTRAINT_STRING_LIST: reason = '\'Mode\' option does not include a STRING_LIST constraint.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) # Enforce resolution option requirements if not scanner.has_option('resolution'): reason = 'No \'resolution\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) resolution = scanner.options['resolution'] if not self.is_settable_option(resolution): reason = 'Unsettable \'resolution\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) # See SANE API 4.5.2 if resolution.type != saneme.OPTION_TYPE_INT and \ resolution.type != saneme.OPTION_TYPE_FLOAT: reason = '\'Resolution\' option is not of type INT or FLOAT.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) # See SANE API 4.5.2 if not resolution.unit == saneme.OPTION_UNIT_DPI: reason = '\'Resolution\' option is not measured in DPI units.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) scanner.close() except saneme.SaneError: reason = 'Exception raised while attempting to query device options.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) self._prop_unavailable_scanners = new_unavailable_scanners self._prop_available_scanners = value self.notify_property_value_change( 'unavailable_scanners', None, new_unavailable_scanners) self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None elif self._prop_active_scanner not in value: self.active_scanner = value[0] def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) if len(value) == 0: self.active_mode = None elif self.active_mode not in value: self.active_mode = value[0] def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) if len(value) == 0: self.active_resolution = None elif self.active_resolution not in value: self.active_resolution = value[0] # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution # INTERNAL METHODS def is_settable_option(self, option): """ Verify an option supports minimum capabilities needed to be used by NoStaples. """ return option.is_active() and \ option.is_soft_gettable() and \ option.is_soft_settable() def _load_scanner_option_constraints(self, sane_device): """ Load the option constraints from a specified scanner. """ main_controller = self.application.get_main_controller() try: assert sane_device.options['mode'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST self._prop_valid_modes = sane_device.options['mode'].constraint if sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_RANGE: min, max, step = sane_device.options['resolution'].constraint # Fix for ticket #34. if step is None or step == 0: step = 1 resolutions = [] # If there are not an excessive number, include every possible # resolution if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: i = min while i <= max: resolutions.append(str(i)) i = i + step # Otherwise, take a crack at building a sensible set of options # that mean that constraint criteria else: i = 1 increment = (max - min) / (constants.MAX_VALID_OPTION_VALUES - 1) while (i <= constants.MAX_VALID_OPTION_VALUES - 2): unrounded = min + (i * increment) rounded = int(round(unrounded / step) * step) resolutions.append(str(rounded)) i = i + 1 resolutions.insert(0, str(min)) resolutions.append(str(max)) self._prop_valid_resolutions = resolutions elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_VALUE_LIST: # Convert values to strings for display self._prop_valid_resolutions = \ [str(i) for i in sane_device.options['resolution'].constraint] elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST: self._prop_valid_resolutions = \ sane_device.options['resolution'].constraint else: raise AssertionError('Unsupported constraint type.') except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) def _load_scanner_option_values(self): """ Get current scanner options from the active_scanner. Useful for reloading any option that may have changed in response to a SaneReloadOptionsError. """ main_controller = self.application.get_main_controller() try: # TODO: ReloadOptions should reload constraints as well as values! self.active_mode = self.active_scanner.options['mode'].value self.active_resolution = str(self.active_scanner.options['resolution'].value) except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) \ No newline at end of file diff --git a/models/preferences.py b/models/preferences.py index 146d412..b29d2a4 100644 --- a/models/preferences.py +++ b/models/preferences.py @@ -1,92 +1,95 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the PreferencesModel, which manages user settings. """ import logging from gtkmvc.model import Model from nostaples import constants -import nostaples.utils.properties +from nostaples.utils import properties class PreferencesModel(Model): """ Manages user settings. """ __properties__ = \ { 'preview_mode' : constants.DEFAULT_PREVIEW_MODE, 'thumbnail_size' : constants.DEFAULT_THUMBNAIL_SIZE, 'toolbar_style' : constants.DEFAULT_TOOLBAR_STYLE, 'blacklisted_scanners' : [], # List of scanner display names 'saved_keywords' : '', } def __init__(self, application): """ Constructs the PreferencesModel. """ Model.__init__(self) self.application = application self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() self.preview_mode = state_manager.init_state( 'preview_mode', constants.DEFAULT_PREVIEW_MODE, - nostaples.utils.properties.PropertyStateCallback(self, 'preview_mode')) + properties.GuardedPropertyStateCallback( + self, 'preview_mode', constants.PREVIEW_MODES_LIST)) self.thumbnail_size = state_manager.init_state( 'thumbnail_size', constants.DEFAULT_THUMBNAIL_SIZE, - nostaples.utils.properties.PropertyStateCallback(self, 'thumbnail_size')) + properties.GuardedPropertyStateCallback( + self, 'thumbnail_size', constants.THUMBNAIL_SIZE_LIST)) self.toolbar_style = state_manager.init_state( 'toolbar_style', constants.DEFAULT_TOOLBAR_STYLE, - nostaples.utils.properties.PropertyStateCallback(self, 'toolbar_style')) + properties.GuardedPropertyStateCallback( + self, 'toolbar_style', constants.TOOLBAR_STYLES_LIST)) self.blacklisted_scanners = state_manager.init_state( 'blacklisted_scanners', constants.DEFAULT_BLACKLISTED_SCANNERS, - nostaples.utils.properties.PropertyStateCallback(self, 'blacklisted_scanners')) + properties.PropertyStateCallback(self, 'blacklisted_scanners')) self.saved_keywords = state_manager.init_state( 'saved_keywords', constants.DEFAULT_SAVED_KEYWORDS, - nostaples.utils.properties.PropertyStateCallback(self, 'saved_keywords')) + properties.PropertyStateCallback(self, 'saved_keywords')) # PROPERTY SETTERS - set_prop_preview_mode = nostaples.utils.properties.StatefulPropertySetter( + set_prop_preview_mode = properties.StatefulPropertySetter( 'preview_mode') - set_prop_thumbnail_size = nostaples.utils.properties.StatefulPropertySetter( + set_prop_thumbnail_size = properties.StatefulPropertySetter( 'thumbnail_size') - set_prop_toolbar_style = nostaples.utils.properties.StatefulPropertySetter( + set_prop_toolbar_style = properties.StatefulPropertySetter( 'toolbar_style') - set_prop_blacklisted_scanners = nostaples.utils.properties.StatefulPropertySetter( + set_prop_blacklisted_scanners = properties.StatefulPropertySetter( 'blacklisted_scanners') - set_prop_saved_keywords = nostaples.utils.properties.StatefulPropertySetter( + set_prop_saved_keywords = properties.StatefulPropertySetter( 'saved_keywords') \ No newline at end of file diff --git a/utils/gui.py b/utils/gui.py index 1064386..1f0588c 100644 --- a/utils/gui.py +++ b/utils/gui.py @@ -1,171 +1,195 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds utility methods for populating and reading from pygtk controls. """ import gtk import gobject class KeywordsCompletionEntry(gtk.Entry): """ A specialized gtk.Entry widget which integrates completion support for tags or keywords stored in a gtk.ListStore. Inspired by U{http://www.oluyede.org/blog/2005/04/25/pygtk-entrymulticompletion/}. """ def __init__(self): """ Construct the widget and setup its completion handler. """ gtk.Entry.__init__(self) self.completion = gtk.EntryCompletion() self.completion.set_model(gtk.ListStore(gobject.TYPE_STRING)) self.completion.set_text_column(0) self.completion.set_match_func(self.matching_function, None) self.completion.set_popup_completion(True) self.completion.connect("match-selected", self.on_match_selected) self.set_completion(self.completion) self.connect("activate", self.on_entry_activate) def matching_function(self, completion, key_string, iter, data): """ Match partial keywords. For an explanation of why match_test is validated, see here: U{http://faq.pygtk.org/index.py?file=faq13.028.htp&req=show} """ model = self.completion.get_model() match_test = model[iter][0] # Attempting to match a row which has been created, # but not set. if not match_test: return False # If nothing has been keyed, no match if len(key_string) == 0: return False # If the last character was a space then no match if key_string[-1] == " ": return False # Get characters keyed since last space word = key_string.split()[-1] return match_test.startswith(word) def on_match_selected(self, completion, model, iter): """ Insert matches into text without overwriting existing keywords. """ current_text = self.get_text() # If no other words, then the new word is the only text if len(current_text) == 0 or current_text.find(" ") == -1: current_text = "%s " % (model[iter][0]) # Append new word to existing words else: current_text = " ".join(current_text.split()[:-1]) current_text = "%s %s " % (current_text, model[iter][0]) self.set_text(current_text) self.set_position(-1) # stop the event propagation return True def on_entry_activate(self, entry): """ Move to next keyword. """ + #if len(main_model.available_scanners) > 0: self.set_text("%s " % self.get_text()) self.set_position(-1) + print 'NOT FOUND' def get_liststore(self): """ Return the gtk.ListStore containing the keywords. """ return self.completion.get_model() def flush_pending_events(): """ This event flushes any pending idle operations without returning to the GTK main loop. It can be used to ensure that all GUI updates have been processed prior to a long-running operation. Do NOT use if any calls to gobject.idle_add have been made as those idle methods will cause an infinite loop. """ while gtk.events_pending() : gtk.main_iteration(False) def setup_combobox(combobox, item_list, selection): """ Sets up a simple combobox. + print 'NOT FOUND' @type combobox: gtk.ComboBox @param combobox: The combobox to be setup. @type item_list: list of strings. @param item_list: The items to add to the menu box. @type selection: string @param selection: The item to be selected by default. """ - liststore = gtk.ListStore(gobject.TYPE_STRING) + liststore = gtk.ListStore(type(item_list[0])) combobox.clear() combobox.set_model(liststore) cell = gtk.CellRendererText() combobox.pack_start(cell, True) combobox.add_attribute(cell, 'text', 0) for item in item_list: liststore.append([item]) try: index = item_list.index(selection) except ValueError: index = 0 combobox.set_active(index) def read_combobox(combobox): """ Reads the currently selected item from a simple combobox. @type combobox: gtk.ComboBox @param combobox: The combobox to read from. """ liststore = combobox.get_model() active = combobox.get_active() if active < 0: return None - return liststore[active][0] \ No newline at end of file + return liststore[active][0] + +def write_combobox(combobox, value): + """ + Selects a value in a simple combobox. + + @type combobox: gtk.ComboBox + @param combobox: The combobox to set. + """ + liststore = combobox.get_model() + + row_iter = liststore.get_iter_first() + + while row_iter: + if liststore.get_value(row_iter, 0) == value: + combobox.set_active_iter(row_iter) + break + + row_iter = liststore.iter_next(row_iter) + + if row_iter == None: + raise ValueError \ No newline at end of file diff --git a/utils/properties.py b/utils/properties.py index 54d93d1..4ec00c3 100644 --- a/utils/properties.py +++ b/utils/properties.py @@ -1,77 +1,107 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the utilities that ease the burden of working with python-gtkmvc properties. """ class StatefulPropertySetter(object): """ This callable object can override the python-gtkmvc accessor functions created for properties in gtkmvc.support.metaclass_base.py. It handles not only notifying observers of changes in the property, but also persist changes to the state backend. """ def __init__(self, property_name): """ Store the property name which is visible to the application as well as its attribute name. """ self.property_name = property_name self.property_attr_name = '_prop_%s' % self.property_name def __call__(self, cls, value): """ Write state and notify observers of changes. For more details on how this works see L{models.main.MainModel.set_prop_active_scanner}. """ old_value = getattr(cls, self.property_attr_name) if old_value == value: return setattr(cls, self.property_attr_name, value) cls.application.get_state_manager()[self.property_name] = value cls.notify_property_value_change( self.property_name, old_value, value) class PropertyStateCallback(object): """ This callable object encasuplates the most common reaction to a state callback: setting the attribute on the model (which in turn causes property notifications, etc). """ def __init__(self, model, property_name): """ Store property a name as well as the model that owns this property. """ self.model = model self.property_name = property_name def __call__(self): """ Set the property attribute on the model, initiating observer callbacks, etc. """ setattr( self.model, self.property_name, - self.model.application.get_state_manager()[self.property_name]) \ No newline at end of file + self.model.application.get_state_manager()[self.property_name]) + +class GuardedPropertyStateCallback(object): + """ + This callable object performs the same function as PropertyStateCallback, + but it also validates that the value coming from GConf is valid (by + comparing it to a list of valid values). If the value is invalid than the + original value is reset in GConf. + """ + def __init__(self, model, property_name, value_list): + """ + Store property a name as well as the model + that owns this property. + """ + self.model = model + self.property_name = property_name + self.value_list = value_list + + def __call__(self): + """ + Set the property attribute on the model, initiating + observer callbacks, etc. + """ + state_manager = self.model.application.get_state_manager() + + if state_manager[self.property_name] in self.value_list: + setattr(self.model, + self.property_name, state_manager[self.property_name]) + else: + state_manager[self.property_name] = getattr( + self.model, self.property_name) \ No newline at end of file
onyxfish/nostaples
5b17407f020d6d04941a197da64b69255209ca30
Fixed some syntax for readability.
diff --git a/controllers/preferences.py b/controllers/preferences.py index bee3c88..cbc4be8 100644 --- a/controllers/preferences.py +++ b/controllers/preferences.py @@ -1,286 +1,286 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{PreferencesController}, which manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ import logging import gtk from gtkmvc.controller import Controller from nostaples import constants from nostaples.utils.gui import read_combobox class PreferencesController(Controller): """ Manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the PreferencesController. """ self.application = application Controller.__init__(self, application.get_preferences_model()) application.get_main_model().register_observer(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ pass # USER INTERFACE CALLBACKS def on_preview_mode_combobox_changed(self, combobox): """Update the preview mode in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.preview_mode = \ read_combobox(preferences_view['preview_mode_combobox']) def on_thumbnail_size_combobox_changed(self, combobox): """Update the thumbnail size in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.thumbnail_size = \ int(read_combobox(preferences_view['thumbnail_size_combobox'])) def on_toolbar_style_combobox_changed(self, combobox): """Update the toolbar style in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.toolbar_style = \ read_combobox(preferences_view['toolbar_style_combobox']) def on_remove_from_blacklist_button_clicked(self, button): """ Remove the currently selected blacklist device from the list. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['blacklist_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.remove(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_add_to_blacklist_button_clicked(self, button): """ Move the currently selected available scanner to the blacklist. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['available_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_remove_from_keywords_button_clicked(self, button): """ Remove the currently selected keyword from the list. """ preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['keywords_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_keywords = list(preferences_model.saved_keywords) temp_keywords.remove(selection_text) preferences_model.saved_keywords = temp_keywords def on_blacklist_tree_view_selection_changed(self, selection): """Update the available device controls.""" self._toggle_device_controls() def on_available_tree_view_selection_changed(self, selection): """Update the available device controls.""" self._toggle_device_controls() def on_preferences_dialog_response(self, dialog, response): """Close the preferences dialog.""" preferences_view = self.application.get_preferences_view() preferences_view['preferences_dialog'].hide() # PROPERTY CALLBACKS def property_preview_mode_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_thumbnail_size_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_toolbar_style_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_blacklisted_scanners_value_change(self, model, old_value, new_value): """Update blacklisted scanners liststore.""" preferences_view = self.application.get_preferences_view() blacklist_liststore = preferences_view['blacklist_tree_view'].get_model() blacklist_liststore.clear() for blacklist_item in new_value: blacklist_liststore.append([blacklist_item]) self._toggle_device_controls() def property_saved_keywords_value_change(self, model, old_value, new_value): """Update keywords liststore.""" preferences_view = self.application.get_preferences_view() keywords_liststore = preferences_view['keywords_tree_view'].get_model() keywords_liststore.clear() for keyword in new_value: keywords_liststore.append([keyword]) # MainModel PROPERTY CALLBACKS def property_available_scanners_value_change(self, model, old_value, new_value): """Update available scanners liststore.""" preferences_view = self.application.get_preferences_view() available_liststore = preferences_view['available_tree_view'].get_model() available_liststore.clear() for available_item in new_value: available_liststore.append([available_item.display_name]) self._toggle_device_controls() def property_unavailable_scanners_value_change(self, model, old_value, new_value): """Update unavailable scanners liststore.""" preferences_view = self.application.get_preferences_view() unavailable_liststore = preferences_view['unavailable_tree_view'].get_model() unavailable_liststore.clear() for unavailable_item in new_value: - unavailable_liststore.append([unavailable_item[0], unavailable_item[1]]) + unavailable_liststore.append(list(unavailable_item)) def property_updating_available_scanners_value_change(self, model, old_value, new_value): """ Disable device management controls while devices are being updated. """ self._toggle_device_controls() # PUBLIC METHODS def run(self): """Run the preferences dialog.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() # Force property updates when dialog is run: this handles the case # where the PreferencesController has not been created until now # so it has not been receiving property notifications. self.property_blacklisted_scanners_value_change( preferences_model, None, preferences_model.blacklisted_scanners) self.property_saved_keywords_value_change( preferences_model, None, preferences_model.saved_keywords) self.property_available_scanners_value_change( main_model, None, main_model.available_scanners) self.property_unavailable_scanners_value_change( preferences_model, None, main_model.unavailable_scanners) preferences_view.run() # PRIVATE METHODS def _toggle_device_controls(self): """ Toggle the availability of the scanner management controls based on the state of the application. """ main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() if main_model.updating_available_scanners: preferences_view['remove_from_blacklist_button'].set_sensitive(False) preferences_view['add_to_blacklist_button'].set_sensitive(False) else: if preferences_view['blacklist_tree_view'].get_selection().count_selected_rows() > 0: #if len(preferences_model.blacklisted_scanners) > 0: preferences_view['remove_from_blacklist_button'].set_sensitive(True) else: preferences_view['remove_from_blacklist_button'].set_sensitive(False) if preferences_view['available_tree_view'].get_selection().count_selected_rows() > 0: #if len(main_model.available_scanners) > 0: preferences_view['add_to_blacklist_button'].set_sensitive(True) else: preferences_view['add_to_blacklist_button'].set_sensitive(False) \ No newline at end of file
onyxfish/nostaples
273f387c76801f1f67cfb6a3c8c4647c2c506113
Fixed silly bug in previous commit. 'Reason' tooltips now work correctly.
diff --git a/controllers/preferences.py b/controllers/preferences.py index e57458a..bee3c88 100644 --- a/controllers/preferences.py +++ b/controllers/preferences.py @@ -1,286 +1,286 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{PreferencesController}, which manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ import logging import gtk from gtkmvc.controller import Controller from nostaples import constants from nostaples.utils.gui import read_combobox class PreferencesController(Controller): """ Manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the PreferencesController. """ self.application = application Controller.__init__(self, application.get_preferences_model()) application.get_main_model().register_observer(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ pass # USER INTERFACE CALLBACKS def on_preview_mode_combobox_changed(self, combobox): """Update the preview mode in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.preview_mode = \ read_combobox(preferences_view['preview_mode_combobox']) def on_thumbnail_size_combobox_changed(self, combobox): """Update the thumbnail size in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.thumbnail_size = \ int(read_combobox(preferences_view['thumbnail_size_combobox'])) def on_toolbar_style_combobox_changed(self, combobox): """Update the toolbar style in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.toolbar_style = \ read_combobox(preferences_view['toolbar_style_combobox']) def on_remove_from_blacklist_button_clicked(self, button): """ Remove the currently selected blacklist device from the list. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['blacklist_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.remove(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_add_to_blacklist_button_clicked(self, button): """ Move the currently selected available scanner to the blacklist. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['available_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_remove_from_keywords_button_clicked(self, button): """ Remove the currently selected keyword from the list. """ preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['keywords_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_keywords = list(preferences_model.saved_keywords) temp_keywords.remove(selection_text) preferences_model.saved_keywords = temp_keywords def on_blacklist_tree_view_selection_changed(self, selection): """Update the available device controls.""" self._toggle_device_controls() def on_available_tree_view_selection_changed(self, selection): """Update the available device controls.""" self._toggle_device_controls() def on_preferences_dialog_response(self, dialog, response): """Close the preferences dialog.""" preferences_view = self.application.get_preferences_view() preferences_view['preferences_dialog'].hide() # PROPERTY CALLBACKS def property_preview_mode_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_thumbnail_size_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_toolbar_style_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_blacklisted_scanners_value_change(self, model, old_value, new_value): """Update blacklisted scanners liststore.""" preferences_view = self.application.get_preferences_view() blacklist_liststore = preferences_view['blacklist_tree_view'].get_model() blacklist_liststore.clear() for blacklist_item in new_value: blacklist_liststore.append([blacklist_item]) self._toggle_device_controls() def property_saved_keywords_value_change(self, model, old_value, new_value): """Update keywords liststore.""" preferences_view = self.application.get_preferences_view() keywords_liststore = preferences_view['keywords_tree_view'].get_model() keywords_liststore.clear() for keyword in new_value: keywords_liststore.append([keyword]) # MainModel PROPERTY CALLBACKS def property_available_scanners_value_change(self, model, old_value, new_value): """Update available scanners liststore.""" preferences_view = self.application.get_preferences_view() available_liststore = preferences_view['available_tree_view'].get_model() available_liststore.clear() for available_item in new_value: available_liststore.append([available_item.display_name]) self._toggle_device_controls() def property_unavailable_scanners_value_change(self, model, old_value, new_value): """Update unavailable scanners liststore.""" preferences_view = self.application.get_preferences_view() unavailable_liststore = preferences_view['unavailable_tree_view'].get_model() unavailable_liststore.clear() for unavailable_item in new_value: - unavailable_liststore.append([unavailable_item]) + unavailable_liststore.append([unavailable_item[0], unavailable_item[1]]) def property_updating_available_scanners_value_change(self, model, old_value, new_value): """ Disable device management controls while devices are being updated. """ self._toggle_device_controls() # PUBLIC METHODS def run(self): """Run the preferences dialog.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() # Force property updates when dialog is run: this handles the case # where the PreferencesController has not been created until now # so it has not been receiving property notifications. self.property_blacklisted_scanners_value_change( preferences_model, None, preferences_model.blacklisted_scanners) self.property_saved_keywords_value_change( preferences_model, None, preferences_model.saved_keywords) self.property_available_scanners_value_change( main_model, None, main_model.available_scanners) self.property_unavailable_scanners_value_change( preferences_model, None, main_model.unavailable_scanners) preferences_view.run() # PRIVATE METHODS def _toggle_device_controls(self): """ Toggle the availability of the scanner management controls based on the state of the application. """ main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() if main_model.updating_available_scanners: preferences_view['remove_from_blacklist_button'].set_sensitive(False) preferences_view['add_to_blacklist_button'].set_sensitive(False) else: if preferences_view['blacklist_tree_view'].get_selection().count_selected_rows() > 0: #if len(preferences_model.blacklisted_scanners) > 0: preferences_view['remove_from_blacklist_button'].set_sensitive(True) else: preferences_view['remove_from_blacklist_button'].set_sensitive(False) if preferences_view['available_tree_view'].get_selection().count_selected_rows() > 0: #if len(main_model.available_scanners) > 0: preferences_view['add_to_blacklist_button'].set_sensitive(True) else: preferences_view['add_to_blacklist_button'].set_sensitive(False) \ No newline at end of file
onyxfish/nostaples
de9cfad4932f8fff76ca34ec3e2e5d0c2c5234e4
Added 'reason' tooltips to unavailable scanners list.
diff --git a/controllers/preferences.py b/controllers/preferences.py index dd0b917..e57458a 100644 --- a/controllers/preferences.py +++ b/controllers/preferences.py @@ -1,286 +1,286 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{PreferencesController}, which manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ import logging import gtk from gtkmvc.controller import Controller from nostaples import constants from nostaples.utils.gui import read_combobox class PreferencesController(Controller): """ Manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the PreferencesController. """ self.application = application Controller.__init__(self, application.get_preferences_model()) application.get_main_model().register_observer(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ pass # USER INTERFACE CALLBACKS def on_preview_mode_combobox_changed(self, combobox): """Update the preview mode in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.preview_mode = \ read_combobox(preferences_view['preview_mode_combobox']) def on_thumbnail_size_combobox_changed(self, combobox): """Update the thumbnail size in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.thumbnail_size = \ int(read_combobox(preferences_view['thumbnail_size_combobox'])) def on_toolbar_style_combobox_changed(self, combobox): """Update the toolbar style in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.toolbar_style = \ read_combobox(preferences_view['toolbar_style_combobox']) def on_remove_from_blacklist_button_clicked(self, button): """ Remove the currently selected blacklist device from the list. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['blacklist_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.remove(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_add_to_blacklist_button_clicked(self, button): """ Move the currently selected available scanner to the blacklist. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['available_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_remove_from_keywords_button_clicked(self, button): """ Remove the currently selected keyword from the list. """ preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['keywords_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_keywords = list(preferences_model.saved_keywords) temp_keywords.remove(selection_text) preferences_model.saved_keywords = temp_keywords def on_blacklist_tree_view_selection_changed(self, selection): """Update the available device controls.""" self._toggle_device_controls() def on_available_tree_view_selection_changed(self, selection): """Update the available device controls.""" self._toggle_device_controls() def on_preferences_dialog_response(self, dialog, response): """Close the preferences dialog.""" preferences_view = self.application.get_preferences_view() preferences_view['preferences_dialog'].hide() # PROPERTY CALLBACKS def property_preview_mode_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_thumbnail_size_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_toolbar_style_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_blacklisted_scanners_value_change(self, model, old_value, new_value): """Update blacklisted scanners liststore.""" preferences_view = self.application.get_preferences_view() blacklist_liststore = preferences_view['blacklist_tree_view'].get_model() blacklist_liststore.clear() for blacklist_item in new_value: blacklist_liststore.append([blacklist_item]) self._toggle_device_controls() def property_saved_keywords_value_change(self, model, old_value, new_value): """Update keywords liststore.""" preferences_view = self.application.get_preferences_view() keywords_liststore = preferences_view['keywords_tree_view'].get_model() keywords_liststore.clear() for keyword in new_value: keywords_liststore.append([keyword]) # MainModel PROPERTY CALLBACKS def property_available_scanners_value_change(self, model, old_value, new_value): """Update available scanners liststore.""" preferences_view = self.application.get_preferences_view() available_liststore = preferences_view['available_tree_view'].get_model() available_liststore.clear() for available_item in new_value: available_liststore.append([available_item.display_name]) self._toggle_device_controls() def property_unavailable_scanners_value_change(self, model, old_value, new_value): """Update unavailable scanners liststore.""" preferences_view = self.application.get_preferences_view() unavailable_liststore = preferences_view['unavailable_tree_view'].get_model() unavailable_liststore.clear() for unavailable_item in new_value: - unavailable_liststore.append([unavailable_item[0]]) + unavailable_liststore.append([unavailable_item]) def property_updating_available_scanners_value_change(self, model, old_value, new_value): """ Disable device management controls while devices are being updated. """ self._toggle_device_controls() # PUBLIC METHODS def run(self): """Run the preferences dialog.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() # Force property updates when dialog is run: this handles the case # where the PreferencesController has not been created until now # so it has not been receiving property notifications. self.property_blacklisted_scanners_value_change( preferences_model, None, preferences_model.blacklisted_scanners) self.property_saved_keywords_value_change( preferences_model, None, preferences_model.saved_keywords) self.property_available_scanners_value_change( main_model, None, main_model.available_scanners) self.property_unavailable_scanners_value_change( preferences_model, None, main_model.unavailable_scanners) preferences_view.run() # PRIVATE METHODS def _toggle_device_controls(self): """ Toggle the availability of the scanner management controls based on the state of the application. """ main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() if main_model.updating_available_scanners: preferences_view['remove_from_blacklist_button'].set_sensitive(False) preferences_view['add_to_blacklist_button'].set_sensitive(False) else: if preferences_view['blacklist_tree_view'].get_selection().count_selected_rows() > 0: #if len(preferences_model.blacklisted_scanners) > 0: preferences_view['remove_from_blacklist_button'].set_sensitive(True) else: preferences_view['remove_from_blacklist_button'].set_sensitive(False) if preferences_view['available_tree_view'].get_selection().count_selected_rows() > 0: #if len(main_model.available_scanners) > 0: preferences_view['add_to_blacklist_button'].set_sensitive(True) else: preferences_view['add_to_blacklist_button'].set_sensitive(False) \ No newline at end of file diff --git a/models/main.py b/models/main.py index 3f67d27..7e179b1 100644 --- a/models/main.py +++ b/models/main.py @@ -1,562 +1,562 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme import nostaples.utils.properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device 'unavailable_scanners' : [], # [] of (saneme.Device.display_name, reason) tuples 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it's option constraints can be queried without error. if value is not None: # Verify that the proper type is being set assert isinstance(value, saneme.Device) # Open the new scanner try: value.open() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Load the option constraints (valid_modes, etc.) for the new device self._load_scanner_option_constraints(value) # Manually constrain option values if self._prop_active_mode not in self._prop_valid_modes: self._prop_active_mode = self._prop_valid_modes[0] if self._prop_active_resolution not in self._prop_valid_resolutions: self._prop_active_resolution = self._prop_valid_resolutions[0] # Manually push option values to new device try: try: value.options['mode'].value = self._prop_active_mode except saneme.SaneReloadOptionsError: pass try: value.options['resolution'].value = \ int(self._prop_active_resolution) except saneme.SaneReloadOptionsError: pass except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Emit change notifications for manually updated properties self.notify_property_value_change( 'valid_modes', None, self.valid_modes) self.notify_property_value_change( 'valid_resolutions', None, self.valid_resolutions) self.notify_property_value_change( 'active_mode', None, self.active_mode) self.notify_property_value_change( 'active_resolution', None, self.active_resolution) # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notifications self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_mode = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value self.active_scanner.options['mode'].value = value except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_mode'] = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_resolution = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value self.active_scanner.options['resolution'].value = int(value) except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_resolution'] = value # Emit change notification self.notify_property_value_change( 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ Takes a new list of scanners, removes any which are blacklisted or unsupported, sets the new list, updates the active_scanner, and emits appropriate property callbacks. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() # Remove blacklisted scanners value = \ [scanner for scanner in value if not \ scanner.display_name in preferences_model.blacklisted_scanners] # Remove scanners that do not support necessary options or fail to # open entirely new_unavailable_scanners = [] # TODO - move somewhere more appropriate? unsupported_scanner_error = \ - 'Scanner %s is unsupported for the following reason: %s.' + 'Scanner %s is unsupported for the following reason: %s' for scanner in value: try: scanner.open() unsupported = False # Enforce mode option requirements if not scanner.has_option('mode'): reason = 'No \'mode\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) mode = scanner.options['mode'] if not self.is_settable_option(mode): reason = 'Unsettable \'mode\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) if not mode.constraint_type == saneme.OPTION_CONSTRAINT_STRING_LIST: reason = '\'Mode\' option does not include a STRING_LIST constraint.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) # Enforce resolution option requirements if not scanner.has_option('resolution'): reason = 'No \'resolution\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) resolution = scanner.options['resolution'] if not self.is_settable_option(resolution): reason = 'Unsettable \'resolution\' option.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) # See SANE API 4.5.2 if resolution.type != saneme.OPTION_TYPE_INT and \ resolution.type != saneme.OPTION_TYPE_FLOAT: reason = '\'Resolution\' option is not of type INT or FLOAT.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) # See SANE API 4.5.2 if not resolution.unit == saneme.OPTION_UNIT_DPI: reason = '\'Resolution\' option is not measured in DPI units.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) scanner.close() except saneme.SaneError: - reason = 'Exception raised while querying device options.' + reason = 'Exception raised while attempting to query device options.' self.log.info(unsupported_scanner_error % (scanner.display_name, reason)) new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) self._prop_unavailable_scanners = new_unavailable_scanners self._prop_available_scanners = value self.notify_property_value_change( 'unavailable_scanners', None, new_unavailable_scanners) self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None elif self._prop_active_scanner not in value: self.active_scanner = value[0] def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) if len(value) == 0: self.active_mode = None elif self.active_mode not in value: self.active_mode = value[0] def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) if len(value) == 0: self.active_resolution = None elif self.active_resolution not in value: self.active_resolution = value[0] # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution # INTERNAL METHODS def is_settable_option(self, option): """ Verify an option supports minimum capabilities needed to be used by NoStaples. """ return option.is_active() and \ option.is_soft_gettable() and \ option.is_soft_settable() def _load_scanner_option_constraints(self, sane_device): """ Load the option constraints from a specified scanner. """ main_controller = self.application.get_main_controller() try: assert sane_device.options['mode'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST self._prop_valid_modes = sane_device.options['mode'].constraint if sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_RANGE: min, max, step = sane_device.options['resolution'].constraint # Fix for ticket #34. if step is None or step == 0: step = 1 resolutions = [] # If there are not an excessive number, include every possible # resolution if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: i = min while i <= max: resolutions.append(str(i)) i = i + step # Otherwise, take a crack at building a sensible set of options # that mean that constraint criteria else: i = 1 increment = (max - min) / (constants.MAX_VALID_OPTION_VALUES - 1) while (i <= constants.MAX_VALID_OPTION_VALUES - 2): unrounded = min + (i * increment) rounded = int(round(unrounded / step) * step) resolutions.append(str(rounded)) i = i + 1 resolutions.insert(0, str(min)) resolutions.append(str(max)) self._prop_valid_resolutions = resolutions elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_VALUE_LIST: # Convert values to strings for display self._prop_valid_resolutions = \ [str(i) for i in sane_device.options['resolution'].constraint] elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST: self._prop_valid_resolutions = \ sane_device.options['resolution'].constraint else: raise AssertionError('Unsupported constraint type.') except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) def _load_scanner_option_values(self): """ Get current scanner options from the active_scanner. Useful for reloading any option that may have changed in response to a SaneReloadOptionsError. """ main_controller = self.application.get_main_controller() try: # TODO: ReloadOptions should reload constraints as well as values! self.active_mode = self.active_scanner.options['mode'].value self.active_resolution = str(self.active_scanner.options['resolution'].value) except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) \ No newline at end of file diff --git a/views/preferences.py b/views/preferences.py index a1a8c3e..f277848 100644 --- a/views/preferences.py +++ b/views/preferences.py @@ -1,172 +1,173 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the PreferencesView which exposes user settings through a dialog seperate from the main application window. """ import logging import os import gtk from gtkmvc.view import View from nostaples import constants from nostaples.utils.gui import read_combobox, setup_combobox class PreferencesView(View): """ Exposes user settings through a dialog seperate from the main application window. """ def __init__(self, application): """ Constructs the PreferencesView, including setting up controls that could not be configured in Glade. """ self.application = application preferences_controller = application.get_preferences_controller() preferences_dialog_glade = os.path.join( constants.GUI_DIRECTORY, 'preferences_dialog.glade') View.__init__( self, preferences_controller, preferences_dialog_glade, 'preferences_dialog', None, False) self.log = logging.getLogger(self.__class__.__name__) # Can not configure this via constructor do to the multiple # root windows in the Main View. self['preferences_dialog'].set_transient_for( application.get_main_view()['scan_window']) # These two combobox's are setup dynamically. Because of this they # must have their signal handlers connected manually. Otherwise # their signals will fire before the view creation is finished. setup_combobox( self['preview_mode_combobox'], constants.PREVIEW_MODES_LIST, application.get_preferences_model().preview_mode) self['preview_mode_combobox'].connect( 'changed', preferences_controller.on_preview_mode_combobox_changed) setup_combobox( self['thumbnail_size_combobox'], constants.THUMBNAIL_SIZE_LIST, application.get_preferences_model().thumbnail_size) self['thumbnail_size_combobox'].connect( 'changed', preferences_controller.on_thumbnail_size_combobox_changed) setup_combobox( self['toolbar_style_combobox'], constants.TOOLBAR_STYLES_LIST, application.get_preferences_model().toolbar_style) self['toolbar_style_combobox'].connect( 'changed', preferences_controller.on_toolbar_style_combobox_changed) # Setup the unavailable scanners tree view - unavailable_liststore = gtk.ListStore(str) + unavailable_liststore = gtk.ListStore(str, str) self['unavailable_tree_view'] = gtk.TreeView() self['unavailable_tree_view'].set_model(unavailable_liststore) self['unavailable_column'] = gtk.TreeViewColumn(None) self['unavailable_cell'] = gtk.CellRendererText() self['unavailable_tree_view'].append_column(self['unavailable_column']) self['unavailable_column'].pack_start(self['unavailable_cell'], True) self['unavailable_column'].add_attribute( self['unavailable_cell'], 'text', 0) self['unavailable_tree_view'].get_selection().set_mode( gtk.SELECTION_NONE) self['unavailable_tree_view'].set_headers_visible(False) self['unavailable_tree_view'].set_property('can-focus', False) + self['unavailable_tree_view'].set_tooltip_column(1) self['unavailable_scrolled_window'].add(self['unavailable_tree_view']) self['unavailable_scrolled_window'].show_all() # Setup the blacklist tree view blacklist_liststore = gtk.ListStore(str) self['blacklist_tree_view'] = gtk.TreeView() self['blacklist_tree_view'].set_model(blacklist_liststore) self['blacklist_column'] = gtk.TreeViewColumn(None) self['blacklist_cell'] = gtk.CellRendererText() self['blacklist_tree_view'].append_column(self['blacklist_column']) self['blacklist_column'].pack_start(self['blacklist_cell'], True) self['blacklist_column'].add_attribute(self['blacklist_cell'], 'text', 0) self['blacklist_tree_view'].get_selection().set_mode( gtk.SELECTION_SINGLE) self['blacklist_tree_view'].set_headers_visible(False) self['blacklist_tree_view'].set_property('can-focus', False) self['blacklist_scrolled_window'].add(self['blacklist_tree_view']) self['blacklist_scrolled_window'].show_all() self['blacklist_tree_view'].get_selection().connect( 'changed', preferences_controller.on_blacklist_tree_view_selection_changed) # Setup the available devices tree view available_liststore = gtk.ListStore(str) self['available_tree_view'] = gtk.TreeView() self['available_tree_view'].set_model(available_liststore) self['available_column'] = gtk.TreeViewColumn(None) self['available_cell'] = gtk.CellRendererText() self['available_tree_view'].append_column(self['available_column']) self['available_column'].pack_start(self['available_cell'], True) self['available_column'].add_attribute(self['available_cell'], 'text', 0) self['available_tree_view'].get_selection().set_mode( gtk.SELECTION_SINGLE) self['available_tree_view'].set_headers_visible(False) self['available_tree_view'].set_property('can-focus', False) self['available_scrolled_window'].add(self['available_tree_view']) self['available_scrolled_window'].show_all() self['available_tree_view'].get_selection().connect( 'changed', preferences_controller.on_available_tree_view_selection_changed) # Setup the keywords tree view keywords_liststore = gtk.ListStore(str) self['keywords_tree_view'] = gtk.TreeView() self['keywords_tree_view'].set_model(keywords_liststore) self['keywords_column'] = gtk.TreeViewColumn(None) self['keywords_cell'] = gtk.CellRendererText() self['keywords_tree_view'].append_column(self['keywords_column']) self['keywords_column'].pack_start(self['keywords_cell'], True) self['keywords_column'].add_attribute(self['keywords_cell'], 'text', 0) self['keywords_tree_view'].get_selection().set_mode( gtk.SELECTION_SINGLE) self['keywords_tree_view'].set_headers_visible(False) self['keywords_tree_view'].set_property('can-focus', False) self['keywords_scrolled_window'].add(self['keywords_tree_view']) self['keywords_scrolled_window'].show_all() application.get_preferences_controller().register_view(self) self.log.debug('Created.') def run(self): """Run the modal preferences dialog.""" self['preferences_dialog'].run() \ No newline at end of file
onyxfish/nostaples
5035cbeb59dfb97e90c5621c1b8d3dc0de80e22d
Added 'reason' for each device that is unsupported.
diff --git a/controllers/preferences.py b/controllers/preferences.py index e57458a..dd0b917 100644 --- a/controllers/preferences.py +++ b/controllers/preferences.py @@ -1,286 +1,286 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{PreferencesController}, which manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ import logging import gtk from gtkmvc.controller import Controller from nostaples import constants from nostaples.utils.gui import read_combobox class PreferencesController(Controller): """ Manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the PreferencesController. """ self.application = application Controller.__init__(self, application.get_preferences_model()) application.get_main_model().register_observer(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ pass # USER INTERFACE CALLBACKS def on_preview_mode_combobox_changed(self, combobox): """Update the preview mode in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.preview_mode = \ read_combobox(preferences_view['preview_mode_combobox']) def on_thumbnail_size_combobox_changed(self, combobox): """Update the thumbnail size in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.thumbnail_size = \ int(read_combobox(preferences_view['thumbnail_size_combobox'])) def on_toolbar_style_combobox_changed(self, combobox): """Update the toolbar style in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.toolbar_style = \ read_combobox(preferences_view['toolbar_style_combobox']) def on_remove_from_blacklist_button_clicked(self, button): """ Remove the currently selected blacklist device from the list. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['blacklist_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.remove(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_add_to_blacklist_button_clicked(self, button): """ Move the currently selected available scanner to the blacklist. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['available_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_remove_from_keywords_button_clicked(self, button): """ Remove the currently selected keyword from the list. """ preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['keywords_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_keywords = list(preferences_model.saved_keywords) temp_keywords.remove(selection_text) preferences_model.saved_keywords = temp_keywords def on_blacklist_tree_view_selection_changed(self, selection): """Update the available device controls.""" self._toggle_device_controls() def on_available_tree_view_selection_changed(self, selection): """Update the available device controls.""" self._toggle_device_controls() def on_preferences_dialog_response(self, dialog, response): """Close the preferences dialog.""" preferences_view = self.application.get_preferences_view() preferences_view['preferences_dialog'].hide() # PROPERTY CALLBACKS def property_preview_mode_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_thumbnail_size_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_toolbar_style_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_blacklisted_scanners_value_change(self, model, old_value, new_value): """Update blacklisted scanners liststore.""" preferences_view = self.application.get_preferences_view() blacklist_liststore = preferences_view['blacklist_tree_view'].get_model() blacklist_liststore.clear() for blacklist_item in new_value: blacklist_liststore.append([blacklist_item]) self._toggle_device_controls() def property_saved_keywords_value_change(self, model, old_value, new_value): """Update keywords liststore.""" preferences_view = self.application.get_preferences_view() keywords_liststore = preferences_view['keywords_tree_view'].get_model() keywords_liststore.clear() for keyword in new_value: keywords_liststore.append([keyword]) # MainModel PROPERTY CALLBACKS def property_available_scanners_value_change(self, model, old_value, new_value): """Update available scanners liststore.""" preferences_view = self.application.get_preferences_view() available_liststore = preferences_view['available_tree_view'].get_model() available_liststore.clear() for available_item in new_value: available_liststore.append([available_item.display_name]) self._toggle_device_controls() def property_unavailable_scanners_value_change(self, model, old_value, new_value): """Update unavailable scanners liststore.""" preferences_view = self.application.get_preferences_view() unavailable_liststore = preferences_view['unavailable_tree_view'].get_model() unavailable_liststore.clear() for unavailable_item in new_value: - unavailable_liststore.append([unavailable_item]) + unavailable_liststore.append([unavailable_item[0]]) def property_updating_available_scanners_value_change(self, model, old_value, new_value): """ Disable device management controls while devices are being updated. """ self._toggle_device_controls() # PUBLIC METHODS def run(self): """Run the preferences dialog.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() # Force property updates when dialog is run: this handles the case # where the PreferencesController has not been created until now # so it has not been receiving property notifications. self.property_blacklisted_scanners_value_change( preferences_model, None, preferences_model.blacklisted_scanners) self.property_saved_keywords_value_change( preferences_model, None, preferences_model.saved_keywords) self.property_available_scanners_value_change( main_model, None, main_model.available_scanners) self.property_unavailable_scanners_value_change( preferences_model, None, main_model.unavailable_scanners) preferences_view.run() # PRIVATE METHODS def _toggle_device_controls(self): """ Toggle the availability of the scanner management controls based on the state of the application. """ main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() if main_model.updating_available_scanners: preferences_view['remove_from_blacklist_button'].set_sensitive(False) preferences_view['add_to_blacklist_button'].set_sensitive(False) else: if preferences_view['blacklist_tree_view'].get_selection().count_selected_rows() > 0: #if len(preferences_model.blacklisted_scanners) > 0: preferences_view['remove_from_blacklist_button'].set_sensitive(True) else: preferences_view['remove_from_blacklist_button'].set_sensitive(False) if preferences_view['available_tree_view'].get_selection().count_selected_rows() > 0: #if len(main_model.available_scanners) > 0: preferences_view['add_to_blacklist_button'].set_sensitive(True) else: preferences_view['add_to_blacklist_button'].set_sensitive(False) \ No newline at end of file diff --git a/models/main.py b/models/main.py index 17eb915..3f67d27 100644 --- a/models/main.py +++ b/models/main.py @@ -1,549 +1,562 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme import nostaples.utils.properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device - 'unavailable_scanners' : [], # [] of saneme.Device.display_name's + 'unavailable_scanners' : [], # [] of (saneme.Device.display_name, reason) tuples 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it's option constraints can be queried without error. if value is not None: # Verify that the proper type is being set assert isinstance(value, saneme.Device) # Open the new scanner try: value.open() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Load the option constraints (valid_modes, etc.) for the new device self._load_scanner_option_constraints(value) # Manually constrain option values if self._prop_active_mode not in self._prop_valid_modes: self._prop_active_mode = self._prop_valid_modes[0] if self._prop_active_resolution not in self._prop_valid_resolutions: self._prop_active_resolution = self._prop_valid_resolutions[0] # Manually push option values to new device try: try: value.options['mode'].value = self._prop_active_mode except saneme.SaneReloadOptionsError: pass try: value.options['resolution'].value = \ int(self._prop_active_resolution) except saneme.SaneReloadOptionsError: pass except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Emit change notifications for manually updated properties self.notify_property_value_change( 'valid_modes', None, self.valid_modes) self.notify_property_value_change( 'valid_resolutions', None, self.valid_resolutions) self.notify_property_value_change( 'active_mode', None, self.active_mode) self.notify_property_value_change( 'active_resolution', None, self.active_resolution) # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notifications self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_mode = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value self.active_scanner.options['mode'].value = value except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_mode'] = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_resolution = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value self.active_scanner.options['resolution'].value = int(value) except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_resolution'] = value # Emit change notification self.notify_property_value_change( 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ Takes a new list of scanners, removes any which are blacklisted or unsupported, sets the new list, updates the active_scanner, and emits appropriate property callbacks. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() # Remove blacklisted scanners value = \ [scanner for scanner in value if not \ scanner.display_name in preferences_model.blacklisted_scanners] # Remove scanners that do not support necessary options or fail to # open entirely new_unavailable_scanners = [] # TODO - move somewhere more appropriate? unsupported_scanner_error = \ 'Scanner %s is unsupported for the following reason: %s.' for scanner in value: try: scanner.open() unsupported = False # Enforce mode option requirements if not scanner.has_option('mode'): + reason = 'No \'mode\' option.' self.log.info(unsupported_scanner_error % - (scanner.display_name, 'No \'mode\' option.')) - unsupported = True + (scanner.display_name, reason)) + new_unavailable_scanners.append((scanner.display_name, reason)) + value.remove(scanner) mode = scanner.options['mode'] if not self.is_settable_option(mode): + reason = 'Unsettable \'mode\' option.' self.log.info(unsupported_scanner_error % - (scanner.display_name, 'Unsettable \'mode\' option.')) - unsupported = True + (scanner.display_name, reason)) + new_unavailable_scanners.append((scanner.display_name, reason)) + value.remove(scanner) if not mode.constraint_type == saneme.OPTION_CONSTRAINT_STRING_LIST: + reason = '\'Mode\' option does not include a STRING_LIST constraint.' self.log.info(unsupported_scanner_error % - (scanner.display_name, '\'Mode\' option does not include a STRING_LIST constraint.')) - unsupported = True + (scanner.display_name, reason)) + new_unavailable_scanners.append((scanner.display_name, reason)) + value.remove(scanner) # Enforce resolution option requirements if not scanner.has_option('resolution'): + reason = 'No \'resolution\' option.' self.log.info(unsupported_scanner_error % - (scanner.display_name, 'No \'resolution\' option.')) - unsupported = True + (scanner.display_name, reason)) + new_unavailable_scanners.append((scanner.display_name, reason)) + value.remove(scanner) resolution = scanner.options['resolution'] if not self.is_settable_option(resolution): + reason = 'Unsettable \'resolution\' option.' self.log.info(unsupported_scanner_error % - (scanner.display_name, 'Unsettable \'resolution\' option.')) - unsupported = True + (scanner.display_name, reason)) + new_unavailable_scanners.append((scanner.display_name, reason)) + value.remove(scanner) # See SANE API 4.5.2 if resolution.type != saneme.OPTION_TYPE_INT and \ resolution.type != saneme.OPTION_TYPE_FLOAT: + reason = '\'Resolution\' option is not of type INT or FLOAT.' self.log.info(unsupported_scanner_error % - (scanner.display_name, '\'Resolution\' option is not of type INT or FLOAT.')) - unsupported = True + (scanner.display_name, reason)) + new_unavailable_scanners.append((scanner.display_name, reason)) + value.remove(scanner) # See SANE API 4.5.2 if not resolution.unit == saneme.OPTION_UNIT_DPI: + reason = '\'Resolution\' option is not measured in DPI units.' self.log.info(unsupported_scanner_error % - (scanner.display_name, '\'Resolution\' option is not measured in DPI units.')) - unsupported = True - - if unsupported: - new_unavailable_scanners.append(scanner.display_name) + (scanner.display_name, reason)) + new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) scanner.close() except saneme.SaneError: - new_unavailable_scanners.append(scanner.display_name) + reason = 'Exception raised while querying device options.' + self.log.info(unsupported_scanner_error % + (scanner.display_name, reason)) + new_unavailable_scanners.append((scanner.display_name, reason)) value.remove(scanner) self._prop_unavailable_scanners = new_unavailable_scanners self._prop_available_scanners = value self.notify_property_value_change( 'unavailable_scanners', None, new_unavailable_scanners) self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None elif self._prop_active_scanner not in value: self.active_scanner = value[0] def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) if len(value) == 0: self.active_mode = None elif self.active_mode not in value: self.active_mode = value[0] def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) if len(value) == 0: self.active_resolution = None elif self.active_resolution not in value: self.active_resolution = value[0] # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution # INTERNAL METHODS def is_settable_option(self, option): """ Verify an option supports minimum capabilities needed to be used by NoStaples. """ return option.is_active() and \ option.is_soft_gettable() and \ option.is_soft_settable() def _load_scanner_option_constraints(self, sane_device): """ Load the option constraints from a specified scanner. """ main_controller = self.application.get_main_controller() try: assert sane_device.options['mode'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST self._prop_valid_modes = sane_device.options['mode'].constraint if sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_RANGE: min, max, step = sane_device.options['resolution'].constraint # Fix for ticket #34. if step is None or step == 0: step = 1 resolutions = [] # If there are not an excessive number, include every possible # resolution if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: i = min while i <= max: resolutions.append(str(i)) i = i + step # Otherwise, take a crack at building a sensible set of options # that mean that constraint criteria else: i = 1 increment = (max - min) / (constants.MAX_VALID_OPTION_VALUES - 1) while (i <= constants.MAX_VALID_OPTION_VALUES - 2): unrounded = min + (i * increment) rounded = int(round(unrounded / step) * step) resolutions.append(str(rounded)) i = i + 1 resolutions.insert(0, str(min)) resolutions.append(str(max)) self._prop_valid_resolutions = resolutions elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_VALUE_LIST: # Convert values to strings for display self._prop_valid_resolutions = \ [str(i) for i in sane_device.options['resolution'].constraint] elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST: self._prop_valid_resolutions = \ sane_device.options['resolution'].constraint else: raise AssertionError('Unsupported constraint type.') except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) def _load_scanner_option_values(self): """ Get current scanner options from the active_scanner. Useful for reloading any option that may have changed in response to a SaneReloadOptionsError. """ main_controller = self.application.get_main_controller() try: # TODO: ReloadOptions should reload constraints as well as values! self.active_mode = self.active_scanner.options['mode'].value self.active_resolution = str(self.active_scanner.options['resolution'].value) except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) \ No newline at end of file
onyxfish/nostaples
227b75ea46385ee2e793218363922dbfb1596300
Added much better debugging output for unsupported devices.
diff --git a/models/main.py b/models/main.py index 65ce77e..17eb915 100644 --- a/models/main.py +++ b/models/main.py @@ -1,539 +1,549 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme import nostaples.utils.properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device 'unavailable_scanners' : [], # [] of saneme.Device.display_name's 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it's option constraints can be queried without error. if value is not None: # Verify that the proper type is being set assert isinstance(value, saneme.Device) # Open the new scanner try: value.open() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Load the option constraints (valid_modes, etc.) for the new device self._load_scanner_option_constraints(value) # Manually constrain option values if self._prop_active_mode not in self._prop_valid_modes: self._prop_active_mode = self._prop_valid_modes[0] if self._prop_active_resolution not in self._prop_valid_resolutions: self._prop_active_resolution = self._prop_valid_resolutions[0] # Manually push option values to new device try: try: value.options['mode'].value = self._prop_active_mode except saneme.SaneReloadOptionsError: pass try: value.options['resolution'].value = \ int(self._prop_active_resolution) except saneme.SaneReloadOptionsError: pass except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Emit change notifications for manually updated properties self.notify_property_value_change( 'valid_modes', None, self.valid_modes) self.notify_property_value_change( 'valid_resolutions', None, self.valid_resolutions) self.notify_property_value_change( 'active_mode', None, self.active_mode) self.notify_property_value_change( 'active_resolution', None, self.active_resolution) # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notifications self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_mode = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value self.active_scanner.options['mode'].value = value except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_mode'] = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_resolution = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value self.active_scanner.options['resolution'].value = int(value) except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_resolution'] = value # Emit change notification self.notify_property_value_change( 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ Takes a new list of scanners, removes any which are blacklisted or unsupported, sets the new list, updates the active_scanner, and emits appropriate property callbacks. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() # Remove blacklisted scanners value = \ [scanner for scanner in value if not \ scanner.display_name in preferences_model.blacklisted_scanners] # Remove scanners that do not support necessary options or fail to # open entirely new_unavailable_scanners = [] + + # TODO - move somewhere more appropriate? + unsupported_scanner_error = \ + 'Scanner %s is unsupported for the following reason: %s.' for scanner in value: try: scanner.open() - if not scanner.has_option('mode') or \ - not self.is_supported_mode_option(scanner.options['mode']) or \ - not scanner.has_option('resolution') or \ - not self.is_supported_resolution_option(scanner.options['resolution']): + unsupported = False + + # Enforce mode option requirements + if not scanner.has_option('mode'): + self.log.info(unsupported_scanner_error % + (scanner.display_name, 'No \'mode\' option.')) + unsupported = True + + mode = scanner.options['mode'] + + if not self.is_settable_option(mode): + self.log.info(unsupported_scanner_error % + (scanner.display_name, 'Unsettable \'mode\' option.')) + unsupported = True + + if not mode.constraint_type == saneme.OPTION_CONSTRAINT_STRING_LIST: + self.log.info(unsupported_scanner_error % + (scanner.display_name, '\'Mode\' option does not include a STRING_LIST constraint.')) + unsupported = True + + # Enforce resolution option requirements + if not scanner.has_option('resolution'): + self.log.info(unsupported_scanner_error % + (scanner.display_name, 'No \'resolution\' option.')) + unsupported = True + + resolution = scanner.options['resolution'] + + if not self.is_settable_option(resolution): + self.log.info(unsupported_scanner_error % + (scanner.display_name, 'Unsettable \'resolution\' option.')) + unsupported = True + + # See SANE API 4.5.2 + if resolution.type != saneme.OPTION_TYPE_INT and \ + resolution.type != saneme.OPTION_TYPE_FLOAT: + self.log.info(unsupported_scanner_error % + (scanner.display_name, '\'Resolution\' option is not of type INT or FLOAT.')) + unsupported = True + + # See SANE API 4.5.2 + if not resolution.unit == saneme.OPTION_UNIT_DPI: + self.log.info(unsupported_scanner_error % + (scanner.display_name, '\'Resolution\' option is not measured in DPI units.')) + unsupported = True + + if unsupported: new_unavailable_scanners.append(scanner.display_name) value.remove(scanner) scanner.close() except saneme.SaneError: new_unavailable_scanners.append(scanner.display_name) value.remove(scanner) self._prop_unavailable_scanners = new_unavailable_scanners self._prop_available_scanners = value self.notify_property_value_change( 'unavailable_scanners', None, new_unavailable_scanners) self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None elif self._prop_active_scanner not in value: self.active_scanner = value[0] def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) if len(value) == 0: self.active_mode = None elif self.active_mode not in value: self.active_mode = value[0] def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) if len(value) == 0: self.active_resolution = None elif self.active_resolution not in value: self.active_resolution = value[0] # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution # INTERNAL METHODS - def is_supported_option(self, option): + def is_settable_option(self, option): """ Verify an option supports minimum capabilities needed to be used by NoStaples. """ return option.is_active() and \ option.is_soft_gettable() and \ option.is_soft_settable() - def is_supported_mode_option(self, option): - """ - Verify that the mode option supports minimum capabilities needed to be - used by NoStaples. - """ - if not self.is_supported_option(option): - return False - - if not option.constraint_type == \ - saneme.OPTION_CONSTRAINT_STRING_LIST: - return False - - return True - - def is_supported_resolution_option(self, option): - """ - Verify that the resolution option supports minimum capabilities needed - to be used by NoStaples. - - Where noted these stem from the SANE API standards. Others are - simply limitations on what has currently been implemented in - NoStaples. - """ - if not self.is_supported_option(option): - return False - - # See SANE API 4.5.2 - if option.type != saneme.OPTION_TYPE_INT and \ - option.type != saneme.OPTION_TYPE_FLOAT: - return False - - # See SANE API 4.5.2 - if not option.unit == saneme.OPTION_UNIT_DPI: - return False - - return True - def _load_scanner_option_constraints(self, sane_device): """ Load the option constraints from a specified scanner. """ main_controller = self.application.get_main_controller() try: assert sane_device.options['mode'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST self._prop_valid_modes = sane_device.options['mode'].constraint if sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_RANGE: min, max, step = sane_device.options['resolution'].constraint # Fix for ticket #34. if step is None or step == 0: step = 1 resolutions = [] # If there are not an excessive number, include every possible # resolution if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: i = min while i <= max: resolutions.append(str(i)) i = i + step # Otherwise, take a crack at building a sensible set of options # that mean that constraint criteria else: i = 1 increment = (max - min) / (constants.MAX_VALID_OPTION_VALUES - 1) while (i <= constants.MAX_VALID_OPTION_VALUES - 2): unrounded = min + (i * increment) rounded = int(round(unrounded / step) * step) resolutions.append(str(rounded)) i = i + 1 resolutions.insert(0, str(min)) resolutions.append(str(max)) self._prop_valid_resolutions = resolutions elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_VALUE_LIST: # Convert values to strings for display self._prop_valid_resolutions = \ [str(i) for i in sane_device.options['resolution'].constraint] elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST: self._prop_valid_resolutions = \ sane_device.options['resolution'].constraint else: raise AssertionError('Unsupported constraint type.') except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) def _load_scanner_option_values(self): """ Get current scanner options from the active_scanner. Useful for reloading any option that may have changed in response to a SaneReloadOptionsError. """ main_controller = self.application.get_main_controller() try: # TODO: ReloadOptions should reload constraints as well as values! self.active_mode = self.active_scanner.options['mode'].value self.active_resolution = str(self.active_scanner.options['resolution'].value) except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) \ No newline at end of file
onyxfish/nostaples
c8a8c8a3a255924e5a9ea1d777932b0808f6d46b
Migrated supported scanner determination to MainModel.
diff --git a/controllers/main.py b/controllers/main.py index db9e39e..ede0ae0 100644 --- a/controllers/main.py +++ b/controllers/main.py @@ -57,759 +57,693 @@ class MainController(Controller): status_controller.get_context_id(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ self.adapt('show_toolbar', 'show_toolbar_menu_item') self.adapt('show_statusbar', 'show_statusbar_menu_item') self.adapt('show_thumbnails', 'show_thumbnails_menu_item') self.adapt('show_adjustments', 'show_adjustments_menu_item') self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS # Menu Items def on_scan_window_destroy(self, window): """Exits the application.""" self.quit() def on_scan_menu_item_activate(self, menu_item): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_menu_item_activate(self, menu_item): """Refresh the list of connected scanners from SANE.""" self._update_available_scanners() def on_save_as_menu_item_activate(self, menu_item): """Saves the current document to a file.""" self.application.show_save_dialog() def on_delete_menu_item_activate(self, menu_item): self.application.get_document_controller().delete_selected() def on_preferences_menu_item_activate(self, menu_item): """Creates and displays a preferences dialog.""" self.application.show_preferences_dialog() def on_quit_menu_item_activate(self, menu_item): """Exits the application.""" self.quit() def on_zoom_in_menu_item_activate(self, menu_item): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_menu_item_activate(self, menu_item): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_menu_item_activate(self, menu_item): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_menu_item_activate(self, menu_item): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_available_scanner_menu_item_toggled(self, menu_item): """ Set the active scanner. TODO: Need a second scanner to properly test this... """ main_model = self.application.get_main_model() if menu_item.get_active(): for scanner in main_model.available_scanners: if scanner.display_name == menu_item.get_children()[0].get_text(): main_model.active_scanner = scanner return def on_valid_mode_menu_item_toggled(self, menu_item): """Sets the active scan mode.""" if menu_item.get_active(): self.application.get_main_model().active_mode = \ menu_item.get_children()[0].get_text() def on_valid_resolution_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_resolution = \ menu_item.get_children()[0].get_text() def on_go_first_menu_item_activate(self, menu_item): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_menu_item_activate(self, menu_item): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_menu_item_activate(self, menu_item): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_menu_item_activate(self, menu_item): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() def on_contents_menu_item_clicked(self, menu_item): """TODO""" pass def on_about_menu_item_activate(self, menu_item): """Show the about dialog.""" self.application.show_about_dialog() # Toolbar Buttons def on_scan_button_clicked(self, button): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_button_clicked(self, button): self._update_available_scanners() def on_save_as_button_clicked(self, button): """Saves the current document to a file.""" self.application.show_save_dialog() def on_zoom_in_button_clicked(self, button): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_button_clicked(self, button): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_button_clicked(self, button): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_button_clicked(self, button): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_go_first_button_clicked(self, button): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_button_clicked(self, button): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_button_clicked(self, button): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_button_clicked(self, button): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() # Progress Window INTERFACE CALLBACKS def on_progress_window_delete_event(self, window, event): """ Emulate clicking of the cancel/close button and then hide the window. """ main_view = self.application.get_main_view() self.on_scan_cancel_button_clicked(None) main_view['progress_window'].hide() return True def on_scan_cancel_button_clicked(self, button): """ Cancel the current scan or, if the scan is finished, close the progress window. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress: assert self.cancel_event self.cancel_event.set() else: main_view['progress_window'].hide() def on_scan_again_button_clicked(self, button): """Initiate a new scan from the progress window.""" self._scan() def on_quick_save_button_clicked(self, button): """ Show the save dialog. If the user completes a save then disable the quick save button until another page is scanned. """ main_view = self.application.get_main_view() document_model = self.application.get_document_model() self.application.show_save_dialog() if document_model.count == 0: main_view['quick_save_button'].set_sensitive(False) # MainModel PROPERTY CALLBACKS def property_show_toolbar_value_change(self, model, old_value, new_value): """Update the visibility of the toolbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_toolbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['main_toolbar'].show() else: main_view['main_toolbar'].hide() def property_show_statusbar_value_change(self, model, old_value, new_value): """Update the visibility of the statusbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_statusbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['status_view_docking_viewport'].show() else: main_view['status_view_docking_viewport'].hide() def property_show_thumbnails_value_change(self, model, old_value, new_value): """Update the visibility of the thumbnails.""" main_view = self.application.get_main_view() menu_item = main_view['show_thumbnails_menu_item'] menu_item.set_active(new_value) self.application.get_document_controller().toggle_thumbnails_visible(new_value) def property_show_adjustments_value_change(self, model, old_value, new_value): """Update the visibility of the adjustments controls.""" document_controller = self.application.get_document_controller() main_view = self.application.get_main_view() menu_item = main_view['show_adjustments_menu_item'] menu_item.set_active(new_value) document_controller.toggle_adjustments_visible(new_value) def property_active_scanner_value_change(self, model, old_value, new_value): """ Update the menu and valid scanner options to match the new device. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() if new_value == None: return for menu_item in main_view['scanner_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value.display_name: menu_item.set_active(True) break def property_active_mode_value_change(self, model, old_value, new_value): """Select the active mode from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_mode_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_resolution_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_resolution_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_available_scanners_value_change(self, model, old_value, new_value): """ Update the menu of available scanners. """ main_view = self.application.get_main_view() self._clear_available_scanners_sub_menu() # Generate the new menu if len(new_value) == 0: menu_item = gtk.MenuItem('No Scanners Connected') menu_item.set_sensitive(False) main_view['scanner_sub_menu'].append(menu_item) else: first_item = None for i in range(len(new_value)): # The first menu item defines the group if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i].display_name) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i].display_name) main_view['scanner_sub_menu'].append(menu_item) main_view['scanner_sub_menu'].show_all() def property_valid_modes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan modes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_modes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Modes") menu_item.set_sensitive(False) main_view['scan_mode_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled) main_view['scan_mode_sub_menu'].append(menu_item) main_view['scan_mode_sub_menu'].show_all() def property_valid_resolutions_value_change(self, model, old_value, new_value): """ Updates the list of valid scan resolutions for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_resolutions_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Resolutions") menu_item.set_sensitive(False) main_view['scan_resolution_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled) main_view['scan_resolution_sub_menu'].append(menu_item) main_view['scan_resolution_sub_menu'].show_all() def property_scan_in_progress_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() def property_updating_available_scanners_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() # DocumentModel PROPERTY CALLBACKS def property_count_value_change(self, model, old_value, new_value): """Toggle available controls.""" self._toggle_document_controls() # PreferencesModel PROPERTY CALLBACKS def property_toolbar_style_value_change(self, model, old_value, new_value): """Toggle available controls.""" main_view = self.application.get_main_view() if new_value == 'System Default': # TODO - reset style to system default pass else: main_view['main_toolbar'].set_style(constants.TOOLBAR_STYLES[new_value]) # THREAD CALLBACKS def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned): main_view = self.application.get_main_view() short_bytes_scanned = float(bytes_scanned) / 1000 short_total_bytes = float(scan_info.total_bytes) / 1000 main_view['scan_progressbar'].set_fraction( float(bytes_scanned) / scan_info.total_bytes) main_view['scan_progressbar'].set_text( 'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes)) # TODO: multi page scans main_view['progress_secondary_label'].set_markup( '<i>Scanning page.</i>') def on_scan_succeeded(self, scanning_thread, pil_image): """ Append the new page to the current document. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['scan_progressbar'].set_fraction(1) main_view['scan_progressbar'].set_text('Scan complete') main_view['progress_secondary_label'].set_markup( '<i>Adding page to document.</i>') gtk.gdk.flush() new_page = PageModel(self.application, pil_image, int(main_model.active_resolution)) self.application.get_document_model().append(new_page) main_view['progress_secondary_label'].set_markup( '<i>Page added.</i>') main_view['scan_again_button'].set_sensitive(True) main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_failed(self, scanning_thread, reason): """ Set that scan is complete. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['progress_secondary_label'].set_markup( '<i>%s</i>' % reason) main_view['scan_again_button'].set_sensitive(True) if self.application.get_document_model().count > 0: main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_aborted(self, scanning_thread, exc_info): """ Change display to indicate that scanning failed and convey the to the user the reason why the thread aborted. If the failure was from a SANE exception then give the user the option to blacklist the device. If not, then reraise the error and let the sys.excepthook deal with it. """ self.on_scan_failed(scanning_thread, 'An error occurred.') if isinstance(exc_info[1], saneme.SaneError): self.run_device_exception_dialog(exc_info) else: raise exc_info[0], exc_info[1], exc_info[2] def on_update_available_scanners_thread_finished(self, update_thread, scanner_list): """Set the new list of available scanners.""" main_model = self.application.get_main_model() - preferences_model = self.application.get_preferences_model() - status_controller = self.application.get_status_controller() - - # Remove blacklisted scanners - scanner_list = \ - [scanner for scanner in scanner_list if not \ - scanner.display_name in preferences_model.blacklisted_scanners] - - # Remove scanners that do not support necessary options or fail to - # open entirely - preferences_model.unavailable_scanners = [] - - def is_supported_option(option): - """Verify an option supports necessary capabilities to be useful.""" - return option.is_active() and \ - option.is_soft_gettable() and \ - option.is_soft_settable() - - def is_supported_mode(option): - """Verify that the mode conforms to type expectations.""" - if not is_supported_option(option): - return False - - if not option.constraint_type == \ - saneme.OPTION_CONSTRAINT_STRING_LIST: - return False - - return True - - def is_supported_resolution(option): - """ - Verify that the resolution conforms to type expectations. - - Where noted these stem from the SANE API standards. Others are - simply limitations on what has currently been implemented in - NoStaples. - """ - if not is_supported_option(option): - return False - - # See SANE API 4.5.2 - if option.type != saneme.OPTION_TYPE_INT and \ - option.type != saneme.OPTION_TYPE_FIXED: - return False - - # See SANE API 4.5.2 - if not option.unit == saneme.OPTION_UNIT_DPI: - return False - - return True - - for scanner in scanner_list: - try: - scanner.open() - - if not scanner.has_option('mode') or \ - not is_supported_mode(scanner.options['mode']) or \ - not scanner.has_option('resolution') or \ - not is_supported_resolution(scanner.options['resolution']): - preferences_model.unavailable_scanners.append(scanner.display_name) - scanner_list.remove(scanner) - - scanner.close() - except saneme.SaneError: - preferences_model.unavailable_scanners.append(scanner.display_name) - scanner_list.remove(scanner) main_model.available_scanners = scanner_list main_model.updating_available_scanners = False def on_update_available_scanners_thread_aborted(self, update_thread, exc_info): """ Change the display to indicate that no scanners are available and reraise the exception so that it can be caught by the sys.excepthook. There is no reason to handle these cases with a special dialog, if the application failed to even enumerate the available devices then no other action will be possible. This should be fantastically rare. """ self.on_update_available_scanners_thread_finished(update_thread, []) raise exc_info[0], exc_info[1], exc_info[2] # PUBLIC METHODS def quit(self): """Exits the application.""" self.log.debug('Quit.') gtk.main_quit() def run_device_exception_dialog(self, exc_info): """ Display an error dialog that provides the user with the option of blacklisting the device which caused the error. TODO: Move into MainView. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() preferences_model = self.application.get_preferences_model() response = main_view.run_device_exception_dialog(exc_info) if response == constants.RESPONSE_BLACKLIST_DEVICE: temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(exc_info[1].device.display_name) temp_blacklist.sort() preferences_model.blacklisted_scanners = temp_blacklist # PRIVATE METHODS def _clear_available_scanners_sub_menu(self): """Clear the menu of available scanners.""" main_view = self.application.get_main_view() for child in main_view['scanner_sub_menu'].get_children(): main_view['scanner_sub_menu'].remove(child) def _clear_scan_modes_sub_menu(self): """Clear the menu of valid scan modes.""" main_view = self.application.get_main_view() for child in main_view['scan_mode_sub_menu'].get_children(): main_view['scan_mode_sub_menu'].remove(child) def _clear_scan_resolutions_sub_menu(self): """Clear the menu of valid scan resolutions.""" main_view = self.application.get_main_view() for child in main_view['scan_resolution_sub_menu'].get_children(): main_view['scan_resolution_sub_menu'].remove(child) def _toggle_scan_controls(self): """Toggle whether or not the scan controls or accessible.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_scan_controls_sensitive(False) main_view.set_refresh_scanner_controls_sensitive(False) else: if main_model.active_scanner != None: main_view.set_scan_controls_sensitive(True) main_view.set_refresh_scanner_controls_sensitive(True) def _toggle_document_controls(self): """ Toggle available document controls based on the current scanner status and the number of scanned pages. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() # Disable all controls when the scanner is in use if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: count = self.application.get_document_model().count # Disable all controls if no pages are scanned if count == 0: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: # Enable most controls if any pages scanned main_view.set_file_controls_sensitive(True) main_view.set_delete_controls_sensitive(True) main_view.set_zoom_controls_sensitive(True) main_view.set_adjustment_controls_sensitive(True) # Only enable navigation if more than one page scanned if count > 1: main_view.set_navigation_controls_sensitive(True) else: main_view.set_navigation_controls_sensitive(False) def _update_status(self): """ Update the text of the statusbar based on the current state of the application. """ main_model = self.application.get_main_model() status_controller = self.application.get_status_controller() status_controller.pop(self.status_context) if main_model.scan_in_progress: status_controller.push(self.status_context, 'Scanning...') elif main_model.updating_available_scanners: status_controller.push(self.status_context, 'Querying hardware...') else: if main_model.active_scanner: status_controller.push(self.status_context, 'Ready with %s.' % main_model.active_scanner.display_name) else: status_controller.push(self.status_context, 'No scanner available.') def _scan(self): """Begin a scan.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() main_model.scan_in_progress = True scanning_thread = ScanningThread(main_model.active_scanner) scanning_thread.connect("progress", self.on_scan_progress) scanning_thread.connect("succeeded", self.on_scan_succeeded) scanning_thread.connect("failed", self.on_scan_failed) scanning_thread.connect("aborted", self.on_scan_aborted) self.cancel_event = scanning_thread.cancel_event main_view['progress_primary_label'].set_markup( '<big><b>%s</b></big>' % main_model.active_scanner.display_name) main_view['scan_progressbar'].set_fraction(0) main_view['scan_progressbar'].set_text('Waiting for data') main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>') mode = main_model.active_mode if main_model.active_mode else 'Not set' main_view['progress_mode_label'].set_markup(mode) dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set' main_view['progress_resolution_label'].set_markup(dpi) main_view['scan_again_button'].set_sensitive(False) main_view['quick_save_button'].set_sensitive(False) main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL) main_view['progress_window'].show_all() scanning_thread.start() def _update_available_scanners(self): """ Start a new update thread to query for available scanners. """ sane = self.application.get_sane() main_model = self.application.get_main_model() main_model.updating_available_scanners = True update_thread = UpdateAvailableScannersThread(sane) update_thread.connect("finished", self.on_update_available_scanners_thread_finished) update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted) update_thread.start() \ No newline at end of file diff --git a/controllers/preferences.py b/controllers/preferences.py index 81437bb..e57458a 100644 --- a/controllers/preferences.py +++ b/controllers/preferences.py @@ -1,284 +1,286 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{PreferencesController}, which manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ import logging import gtk from gtkmvc.controller import Controller from nostaples import constants from nostaples.utils.gui import read_combobox class PreferencesController(Controller): """ Manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the PreferencesController. """ self.application = application Controller.__init__(self, application.get_preferences_model()) application.get_main_model().register_observer(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ pass # USER INTERFACE CALLBACKS def on_preview_mode_combobox_changed(self, combobox): """Update the preview mode in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.preview_mode = \ read_combobox(preferences_view['preview_mode_combobox']) def on_thumbnail_size_combobox_changed(self, combobox): """Update the thumbnail size in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.thumbnail_size = \ int(read_combobox(preferences_view['thumbnail_size_combobox'])) def on_toolbar_style_combobox_changed(self, combobox): """Update the toolbar style in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.toolbar_style = \ read_combobox(preferences_view['toolbar_style_combobox']) def on_remove_from_blacklist_button_clicked(self, button): """ Remove the currently selected blacklist device from the list. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['blacklist_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.remove(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_add_to_blacklist_button_clicked(self, button): """ Move the currently selected available scanner to the blacklist. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['available_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_remove_from_keywords_button_clicked(self, button): """ Remove the currently selected keyword from the list. """ preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['keywords_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_keywords = list(preferences_model.saved_keywords) temp_keywords.remove(selection_text) preferences_model.saved_keywords = temp_keywords def on_blacklist_tree_view_selection_changed(self, selection): """Update the available device controls.""" self._toggle_device_controls() def on_available_tree_view_selection_changed(self, selection): """Update the available device controls.""" self._toggle_device_controls() def on_preferences_dialog_response(self, dialog, response): """Close the preferences dialog.""" preferences_view = self.application.get_preferences_view() preferences_view['preferences_dialog'].hide() # PROPERTY CALLBACKS def property_preview_mode_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_thumbnail_size_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_toolbar_style_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass - def property_unavailable_scanners_value_change(self, model, old_value, new_value): - """Update unavailable scanners liststore.""" - preferences_view = self.application.get_preferences_view() - - unavailable_liststore = preferences_view['unavailable_tree_view'].get_model() - unavailable_liststore.clear() - - for unavailable_item in new_value: - unavailable_liststore.append([unavailable_item]) - def property_blacklisted_scanners_value_change(self, model, old_value, new_value): """Update blacklisted scanners liststore.""" preferences_view = self.application.get_preferences_view() blacklist_liststore = preferences_view['blacklist_tree_view'].get_model() blacklist_liststore.clear() for blacklist_item in new_value: blacklist_liststore.append([blacklist_item]) - self._toggle_device_controls() + self._toggle_device_controls() + + def property_saved_keywords_value_change(self, model, old_value, new_value): + """Update keywords liststore.""" + preferences_view = self.application.get_preferences_view() + + keywords_liststore = preferences_view['keywords_tree_view'].get_model() + keywords_liststore.clear() + + for keyword in new_value: + keywords_liststore.append([keyword]) + + # MainModel PROPERTY CALLBACKS def property_available_scanners_value_change(self, model, old_value, new_value): """Update available scanners liststore.""" preferences_view = self.application.get_preferences_view() available_liststore = preferences_view['available_tree_view'].get_model() available_liststore.clear() for available_item in new_value: available_liststore.append([available_item.display_name]) self._toggle_device_controls() + + def property_unavailable_scanners_value_change(self, model, old_value, new_value): + """Update unavailable scanners liststore.""" + preferences_view = self.application.get_preferences_view() + + unavailable_liststore = preferences_view['unavailable_tree_view'].get_model() + unavailable_liststore.clear() + + for unavailable_item in new_value: + unavailable_liststore.append([unavailable_item]) def property_updating_available_scanners_value_change(self, model, old_value, new_value): """ Disable device management controls while devices are being updated. """ - self._toggle_device_controls() - - def property_saved_keywords_value_change(self, model, old_value, new_value): - """Update keywords liststore.""" - preferences_view = self.application.get_preferences_view() - - keywords_liststore = preferences_view['keywords_tree_view'].get_model() - keywords_liststore.clear() - - for keyword in new_value: - keywords_liststore.append([keyword]) + self._toggle_device_controls() # PUBLIC METHODS def run(self): """Run the preferences dialog.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() # Force property updates when dialog is run: this handles the case # where the PreferencesController has not been created until now # so it has not been receiving property notifications. - self.property_unavailable_scanners_value_change( - preferences_model, None, preferences_model.unavailable_scanners) self.property_blacklisted_scanners_value_change( preferences_model, None, preferences_model.blacklisted_scanners) - self.property_available_scanners_value_change( - main_model, None, main_model.available_scanners) self.property_saved_keywords_value_change( preferences_model, None, preferences_model.saved_keywords) + self.property_available_scanners_value_change( + main_model, None, main_model.available_scanners) + self.property_unavailable_scanners_value_change( + preferences_model, None, main_model.unavailable_scanners) preferences_view.run() # PRIVATE METHODS def _toggle_device_controls(self): """ Toggle the availability of the scanner management controls based on the state of the application. """ main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() if main_model.updating_available_scanners: preferences_view['remove_from_blacklist_button'].set_sensitive(False) preferences_view['add_to_blacklist_button'].set_sensitive(False) else: if preferences_view['blacklist_tree_view'].get_selection().count_selected_rows() > 0: #if len(preferences_model.blacklisted_scanners) > 0: preferences_view['remove_from_blacklist_button'].set_sensitive(True) else: preferences_view['remove_from_blacklist_button'].set_sensitive(False) if preferences_view['available_tree_view'].get_selection().count_selected_rows() > 0: #if len(main_model.available_scanners) > 0: preferences_view['add_to_blacklist_button'].set_sensitive(True) else: preferences_view['add_to_blacklist_button'].set_sensitive(False) \ No newline at end of file diff --git a/models/main.py b/models/main.py index 11a6f75..65ce77e 100644 --- a/models/main.py +++ b/models/main.py @@ -1,461 +1,539 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme import nostaples.utils.properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device + 'unavailable_scanners' : [], # [] of saneme.Device.display_name's 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it's option constraints can be queried without error. if value is not None: # Verify that the proper type is being set assert isinstance(value, saneme.Device) # Open the new scanner try: value.open() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Load the option constraints (valid_modes, etc.) for the new device self._load_scanner_option_constraints(value) # Manually constrain option values if self._prop_active_mode not in self._prop_valid_modes: self._prop_active_mode = self._prop_valid_modes[0] if self._prop_active_resolution not in self._prop_valid_resolutions: self._prop_active_resolution = self._prop_valid_resolutions[0] # Manually push option values to new device try: try: value.options['mode'].value = self._prop_active_mode except saneme.SaneReloadOptionsError: pass try: value.options['resolution'].value = \ int(self._prop_active_resolution) except saneme.SaneReloadOptionsError: pass except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Emit change notifications for manually updated properties self.notify_property_value_change( 'valid_modes', None, self.valid_modes) self.notify_property_value_change( 'valid_resolutions', None, self.valid_resolutions) self.notify_property_value_change( 'active_mode', None, self.active_mode) self.notify_property_value_change( 'active_resolution', None, self.active_resolution) # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notifications self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_mode = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value self.active_scanner.options['mode'].value = value except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_mode'] = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_resolution = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value self.active_scanner.options['resolution'].value = int(value) except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_resolution'] = value # Emit change notification self.notify_property_value_change( 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ - Set the list of available scanners and update the active_scanner. + Takes a new list of scanners, removes any which are blacklisted or + unsupported, sets the new list, updates the active_scanner, and emits + appropriate property callbacks. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() + preferences_model = self.application.get_preferences_model() + + # Remove blacklisted scanners + value = \ + [scanner for scanner in value if not \ + scanner.display_name in preferences_model.blacklisted_scanners] + + # Remove scanners that do not support necessary options or fail to + # open entirely + new_unavailable_scanners = [] + + for scanner in value: + try: + scanner.open() + + if not scanner.has_option('mode') or \ + not self.is_supported_mode_option(scanner.options['mode']) or \ + not scanner.has_option('resolution') or \ + not self.is_supported_resolution_option(scanner.options['resolution']): + new_unavailable_scanners.append(scanner.display_name) + value.remove(scanner) + + scanner.close() + except saneme.SaneError: + new_unavailable_scanners.append(scanner.display_name) + value.remove(scanner) + self._prop_unavailable_scanners = new_unavailable_scanners self._prop_available_scanners = value + self.notify_property_value_change( + 'unavailable_scanners', None, new_unavailable_scanners) self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None elif self._prop_active_scanner not in value: self.active_scanner = value[0] def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) if len(value) == 0: self.active_mode = None elif self.active_mode not in value: self.active_mode = value[0] def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) if len(value) == 0: self.active_resolution = None elif self.active_resolution not in value: self.active_resolution = value[0] # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution # INTERNAL METHODS + + def is_supported_option(self, option): + """ + Verify an option supports minimum capabilities needed to be used by + NoStaples. + """ + return option.is_active() and \ + option.is_soft_gettable() and \ + option.is_soft_settable() + + def is_supported_mode_option(self, option): + """ + Verify that the mode option supports minimum capabilities needed to be + used by NoStaples. + """ + if not self.is_supported_option(option): + return False + + if not option.constraint_type == \ + saneme.OPTION_CONSTRAINT_STRING_LIST: + return False + + return True + + def is_supported_resolution_option(self, option): + """ + Verify that the resolution option supports minimum capabilities needed + to be used by NoStaples. + + Where noted these stem from the SANE API standards. Others are + simply limitations on what has currently been implemented in + NoStaples. + """ + if not self.is_supported_option(option): + return False + + # See SANE API 4.5.2 + if option.type != saneme.OPTION_TYPE_INT and \ + option.type != saneme.OPTION_TYPE_FLOAT: + return False + + # See SANE API 4.5.2 + if not option.unit == saneme.OPTION_UNIT_DPI: + return False + + return True def _load_scanner_option_constraints(self, sane_device): """ Load the option constraints from a specified scanner. """ main_controller = self.application.get_main_controller() try: assert sane_device.options['mode'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST self._prop_valid_modes = sane_device.options['mode'].constraint if sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_RANGE: min, max, step = sane_device.options['resolution'].constraint # Fix for ticket #34. if step is None or step == 0: step = 1 resolutions = [] # If there are not an excessive number, include every possible # resolution if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: i = min while i <= max: resolutions.append(str(i)) i = i + step # Otherwise, take a crack at building a sensible set of options # that mean that constraint criteria else: i = 1 increment = (max - min) / (constants.MAX_VALID_OPTION_VALUES - 1) while (i <= constants.MAX_VALID_OPTION_VALUES - 2): unrounded = min + (i * increment) rounded = int(round(unrounded / step) * step) resolutions.append(str(rounded)) i = i + 1 resolutions.insert(0, str(min)) resolutions.append(str(max)) self._prop_valid_resolutions = resolutions elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_VALUE_LIST: # Convert values to strings for display self._prop_valid_resolutions = \ [str(i) for i in sane_device.options['resolution'].constraint] elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST: self._prop_valid_resolutions = \ sane_device.options['resolution'].constraint else: raise AssertionError('Unsupported constraint type.') except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) def _load_scanner_option_values(self): """ Get current scanner options from the active_scanner. Useful for reloading any option that may have changed in response to a SaneReloadOptionsError. """ main_controller = self.application.get_main_controller() try: # TODO: ReloadOptions should reload constraints as well as values! self.active_mode = self.active_scanner.options['mode'].value self.active_resolution = str(self.active_scanner.options['resolution'].value) except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) \ No newline at end of file diff --git a/models/preferences.py b/models/preferences.py index f9ea253..146d412 100644 --- a/models/preferences.py +++ b/models/preferences.py @@ -1,93 +1,92 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the PreferencesModel, which manages user settings. """ import logging from gtkmvc.model import Model from nostaples import constants import nostaples.utils.properties class PreferencesModel(Model): """ Manages user settings. """ __properties__ = \ { 'preview_mode' : constants.DEFAULT_PREVIEW_MODE, 'thumbnail_size' : constants.DEFAULT_THUMBNAIL_SIZE, 'toolbar_style' : constants.DEFAULT_TOOLBAR_STYLE, - 'unavailable_scanners' : [], # Not persisted 'blacklisted_scanners' : [], # List of scanner display names 'saved_keywords' : '', } def __init__(self, application): """ Constructs the PreferencesModel. """ Model.__init__(self) self.application = application self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() self.preview_mode = state_manager.init_state( 'preview_mode', constants.DEFAULT_PREVIEW_MODE, nostaples.utils.properties.PropertyStateCallback(self, 'preview_mode')) self.thumbnail_size = state_manager.init_state( 'thumbnail_size', constants.DEFAULT_THUMBNAIL_SIZE, nostaples.utils.properties.PropertyStateCallback(self, 'thumbnail_size')) self.toolbar_style = state_manager.init_state( 'toolbar_style', constants.DEFAULT_TOOLBAR_STYLE, nostaples.utils.properties.PropertyStateCallback(self, 'toolbar_style')) self.blacklisted_scanners = state_manager.init_state( 'blacklisted_scanners', constants.DEFAULT_BLACKLISTED_SCANNERS, nostaples.utils.properties.PropertyStateCallback(self, 'blacklisted_scanners')) self.saved_keywords = state_manager.init_state( 'saved_keywords', constants.DEFAULT_SAVED_KEYWORDS, nostaples.utils.properties.PropertyStateCallback(self, 'saved_keywords')) # PROPERTY SETTERS set_prop_preview_mode = nostaples.utils.properties.StatefulPropertySetter( 'preview_mode') set_prop_thumbnail_size = nostaples.utils.properties.StatefulPropertySetter( 'thumbnail_size') set_prop_toolbar_style = nostaples.utils.properties.StatefulPropertySetter( 'toolbar_style') set_prop_blacklisted_scanners = nostaples.utils.properties.StatefulPropertySetter( 'blacklisted_scanners') set_prop_saved_keywords = nostaples.utils.properties.StatefulPropertySetter( 'saved_keywords') \ No newline at end of file
onyxfish/nostaples
88e1cb6990e6d78f9cb3e1a8cab5e02d1ed93926
Pushed fixed-point/float conversion down into SaneMe.
diff --git a/models/main.py b/models/main.py index 23dad8d..11a6f75 100644 --- a/models/main.py +++ b/models/main.py @@ -1,488 +1,461 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme import nostaples.utils.properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it's option constraints can be queried without error. if value is not None: # Verify that the proper type is being set assert isinstance(value, saneme.Device) # Open the new scanner try: value.open() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Load the option constraints (valid_modes, etc.) for the new device self._load_scanner_option_constraints(value) # Manually constrain option values if self._prop_active_mode not in self._prop_valid_modes: self._prop_active_mode = self._prop_valid_modes[0] if self._prop_active_resolution not in self._prop_valid_resolutions: self._prop_active_resolution = self._prop_valid_resolutions[0] # Manually push option values to new device try: try: value.options['mode'].value = self._prop_active_mode except saneme.SaneReloadOptionsError: pass try: value.options['resolution'].value = \ int(self._prop_active_resolution) except saneme.SaneReloadOptionsError: pass except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Emit change notifications for manually updated properties self.notify_property_value_change( 'valid_modes', None, self.valid_modes) self.notify_property_value_change( 'valid_resolutions', None, self.valid_resolutions) self.notify_property_value_change( 'active_mode', None, self.active_mode) self.notify_property_value_change( 'active_resolution', None, self.active_resolution) # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notifications self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_mode = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value self.active_scanner.options['mode'].value = value except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_mode'] = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_resolution = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value - if self.active_scanner.options['resolution'].type == saneme.OPTION_TYPE_FIXED: - self.active_scanner.options['resolution'].value = saneme.SANE_FIX(int(value)) - else: - self.active_scanner.options['resolution'].value = int(value) + self.active_scanner.options['resolution'].value = int(value) except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_resolution'] = value # Emit change notification self.notify_property_value_change( 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ Set the list of available scanners and update the active_scanner. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() self._prop_available_scanners = value self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None elif self._prop_active_scanner not in value: self.active_scanner = value[0] def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) if len(value) == 0: self.active_mode = None elif self.active_mode not in value: self.active_mode = value[0] def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) if len(value) == 0: self.active_resolution = None elif self.active_resolution not in value: self.active_resolution = value[0] # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution # INTERNAL METHODS def _load_scanner_option_constraints(self, sane_device): """ Load the option constraints from a specified scanner. """ main_controller = self.application.get_main_controller() try: assert sane_device.options['mode'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST self._prop_valid_modes = sane_device.options['mode'].constraint if sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_RANGE: min, max, step = sane_device.options['resolution'].constraint - # Convert fixed point values - if sane_device.options['resolution'].type == saneme.OPTION_TYPE_FIXED: - min = saneme.SANE_UNFIX(min) - max = saneme.SANE_UNFIX(max) - step = saneme.SANE_UNFIX(step) - # Fix for ticket #34. if step is None or step == 0: step = 1 resolutions = [] # If there are not an excessive number, include every possible # resolution if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: i = min while i <= max: resolutions.append(str(i)) i = i + step # Otherwise, take a crack at building a sensible set of options # that mean that constraint criteria else: i = 1 increment = (max - min) / (constants.MAX_VALID_OPTION_VALUES - 1) while (i <= constants.MAX_VALID_OPTION_VALUES - 2): unrounded = min + (i * increment) rounded = int(round(unrounded / step) * step) resolutions.append(str(rounded)) i = i + 1 resolutions.insert(0, str(min)) resolutions.append(str(max)) self._prop_valid_resolutions = resolutions elif sane_device.options['resolution'].constraint_type == \ - saneme.OPTION_CONSTRAINT_INTEGER_LIST: - # Convert fixed point values to floats - if sane_device.options['resolution'].type == saneme.OPTION_TYPE_FIXED: - temp_value_resolutions = [saneme.SANE_UNFIX(i) for i in sane_device.options['resolution'].constraint] - else: - temp_value_resolutions = sane_device.options['resolution'].constraint - + saneme.OPTION_CONSTRAINT_VALUE_LIST: # Convert values to strings for display self._prop_valid_resolutions = \ - [str(i) for i in temp_value_resolutions] + [str(i) for i in sane_device.options['resolution'].constraint] elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST: - # Convert fixed point values to floats - # (keeping in mind these are strings representing fixed points) - if sane_device.options['resolution'].type == saneme.OPTION_TYPE_FIXED: - temp_value_resolutions = [int(i) for i in sane_device.options['resolution'].constraint] - temp_value_resolutions = [saneme.SANE_UNFIX(i) for i in temp_value_resolutions] - temp_value_resolutions = [str(i) for i in temp_value_resolutions] - else: - temp_value_resolutions = sane_device.options['resolution'].constraint - - self._prop_valid_resolutions = temp_value_resolutions + self._prop_valid_resolutions = \ + sane_device.options['resolution'].constraint else: raise AssertionError('Unsupported constraint type.') except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) def _load_scanner_option_values(self): """ Get current scanner options from the active_scanner. Useful for reloading any option that may have changed in response to a SaneReloadOptionsError. """ main_controller = self.application.get_main_controller() try: # TODO: ReloadOptions should reload constraints as well as values! self.active_mode = self.active_scanner.options['mode'].value - - if self.active_scanner.options['resolution'].type == saneme.OPTION_TYPE_FIXED: - str(saneme.SANE_UNFIX(self.active_scanner.options['resolution'].value)) - else: - str(self.active_scanner.options['resolution'].value) + self.active_resolution = str(self.active_scanner.options['resolution'].value) except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) \ No newline at end of file diff --git a/sane/saneme.py b/sane/saneme.py index 8dce78b..2e693f1 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -1,997 +1,1012 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module contains the Pythonic implementation of the SANE API. The flat C functions have been wrapped in a set of objects and all ctypes of the underlying implmentation have been hidden from the user's view. This enumerations and definiations which are absolutely necessary to the end user have been redeclared. """ # TODO: document what exceptions can be thrown by each method, # including those that could bubble up from array import * import atexit import ctypes from types import * from PIL import Image from errors import * from saneh import * # Redeclare saneh enumerations which are visible to the application (OPTION_TYPE_BOOL, OPTION_TYPE_INT, - OPTION_TYPE_FIXED, + # Automatically converted from SANE_TYPE_FIXED + OPTION_TYPE_FLOAT, OPTION_TYPE_STRING, OPTION_TYPE_BUTTON, OPTION_TYPE_GROUP) = xrange(6) (OPTION_UNIT_NONE, OPTION_UNIT_PIXEL, OPTION_UNIT_BIT, OPTION_UNIT_MM, OPTION_UNIT_DPI, OPTION_UNIT_PERCENT, OPTION_UNIT_MICROSECOND) = xrange(7) (OPTION_CONSTRAINT_NONE, OPTION_CONSTRAINT_RANGE, - OPTION_CONSTRAINT_INTEGER_LIST, + OPTION_CONSTRAINT_VALUE_LIST, OPTION_CONSTRAINT_STRING_LIST) = xrange(4) class SaneMe(object): """ The top-level object for interacting with the SANE API. Handles polling for devices. This object should only be instantiated once. """ _log = None _version = None # (major, minor, build) _devices = [] def __init__(self, log=None): """ Create the SANE object, perform setup, and register the cleanup function. @param log: an optional Python logging object to log to. """ self._log = log self._setup() atexit.register(self._shutdown) # Read only properties def __get_version(self): """Get the current installed version of SANE.""" return self._version version = property(__get_version) def _setup(self): """ Iniitalize SANE and retrieve the current installed version. """ version_code = SANE_Int() auth_callback = SANE_Auth_Callback(self._sane_auth_callback) status = sane_init(byref(version_code), auth_callback) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_init returned an invalid status: %i.' % status) self._version = (SANE_VERSION_MAJOR(version_code), SANE_VERSION_MINOR(version_code), SANE_VERSION_BUILD(version_code)) if self._log: self._log.info('SANE version %s initalized.', self._version) def _sane_auth_callback(self, resource, username, password): """ TODO """ raise NotImplementedError( 'sane_auth_callback requested, but not yet implemented.') def _shutdown(self): """ Deinitialize SANE. This code would go in __del__, but it is not guaranteed that method will be called and sane_exit must be called to release resources. To ensure this method is called it is registered with atexit. """ for device in self._devices: if device.is_open(): device.close() sane_exit() self._version = None if self._log: self._log.info('SANE deinitialized.') # Public Methods def get_device_list(self): """ Poll for connected devices. This method may take several seconds to return. Note that SANE is exited and re-inited before querying for devices to workaround a limitation in SANE's USB driver which causes the device list to only be updated on init. This means that all settings applied to all devices will be B{lost} and must be restored by the calling application. This was found documented here: U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html} """ if not self._version: raise AssertionError('version was None') # See docstring for details on this voodoo self._shutdown() self._setup() cdevices = POINTER(POINTER(SANE_Device))() status = sane_get_devices(byref(cdevices), SANE_Bool(0)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_get_devices ran out of memory.') else: raise SaneUnknownError( 'sane_get_devices returned an invalid status: %i.' % status) device_count = 0 self._devices = [] while cdevices[device_count]: self._devices.append( Device(cdevices[device_count].contents, self._log)) device_count += 1 if self._log: self._log.info('SANE queried, %i device(s) found.', device_count) return self._devices def get_device_by_name(self, name): """ Retrieve a L{Device} by name. Must be preceded by a call to L{get_device_list}. """ for device in self._devices: if device.name == name: return device raise SaneNoSuchDeviceError( 'The requested device does not exist.') class Device(object): """ This is the primary object for interacting with SANE. It represents a single device and handles enumeration of options, getting and setting of options, and starting and stopping of scanning jobs. """ _log = None _handle = None _name = '' _vendor = '' _model = '' _type = '' _display_name = '' _options = {} def __init__(self, ctypes_device, log=None): """ Sets the Devices properties from a ctypes SANE_Device and queries for its available options. """ self._log = log # String attributes should never be None self._name = ctypes_device.name if ctypes_device.name else '' self._vendor = ctypes_device.vendor if ctypes_device.vendor else '' self._model = ctypes_device.model if ctypes_device.model else '' self._type = ctypes_device.type if ctypes_device.type else '' self._display_name = ' '.join([self._vendor, self._model]) # Read only properties def __get_name(self): """ Get the complete SANE identifier for this device, e.g. 'lexmark:libusb:002:006'. """ return self._name name = property(__get_name) def __get_vendor(self): """Get the manufacturer of this device, e.g. 'Lexmark'.""" return self._vendor vendor = property(__get_vendor) def __get_model(self): """Get the specific model of this device, e.g. 'X1100/rev. B2'.""" return self._model model = property(__get_model) def __get_type(self): """Get the type of this device, e.g. 'flatbed scanner'.""" return self._type type = property(__get_type) def __get_display_name(self): """ Get an appropriate name to use for displaying this device to a user, e.g. 'Lexmark X1100/rev. B2'.""" return self._display_name display_name = property(__get_display_name) def __get_options(self): """Get the dictionary of options that this device has.""" return self._options options = property(__get_options) # Internal methods def _update_options(self): """ Update the list of available options for this device. As these are immutable, this should only need to be called when the Device is first instantiated. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') option_value = pointer(c_int()) status = sane_control_option( self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: raise SaneUnsupportedOperationError( 'sane_control_option reported that a value was outside the option\'s constraint.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) option_count = option_value.contents.value if self._log: self._log.debug('Device queried, %i option(s) found.', option_count) self._options.clear() i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) self._options[coption.contents.name] = Option( self, i, coption.contents, self._log) i = i + 1 # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Public methods def open(self): """ Open a new handle to this device. Must be called before any operations (including getting or setting options) are performed on this device. """ if self._handle: raise AssertionError('device handle already exists.') self._handle = SANE_Handle() status = sane_open(self.name, byref(self._handle)) # If and exception will be thrown, nullify device handle # so is_open() will return false for the device. if status != SANE_STATUS_GOOD.value: self._handle = None if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_open reported that the device was busy.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) self._update_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) def has_option(self, option_name): """Return true if option_name is available for this scanner.""" return (option_name in self.options.keys()) def scan(self, progress_callback=None): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: # Lineart if sane_parameters.depth == 1: pil_image = Image.frombuffer( '1', (scan_info.width, scan_info.height), data_array, 'raw', '1', 0, 1) # Grayscale elif sane_parameters.depth == 8: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) else: raise AssertionError( 'Unexpected bit depth for monochrome scan format: %i' % sane_parameters.depth) elif sane_parameters.format == SANE_FRAME_RGB.value: # Color pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capability = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number # String attributes should never be None self._name = ctypes_option.name if ctypes_option.name else '' self._title = ctypes_option.title if ctypes_option.title else '' self._description = ctypes_option.desc if ctypes_option.desc else '' self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: - self._constraint = ( - ctypes_option.constraint.range.contents.min, - ctypes_option.constraint.range.contents.max, - ctypes_option.constraint.range.contents.quant) + if self._type == SANE_TYPE_FIXED.value: + self._constraint = ( + SANE_UNFIX(ctypes_option.constraint.range.contents.min), + SANE_UNFIX(ctypes_option.constraint.range.contents.max), + SANE_UNFIX(ctypes_option.constraint.range.contents.quant)) + else: + self._constraint = ( + ctypes_option.constraint.range.contents.min, + ctypes_option.constraint.range.contents.max, + ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) - i = i + 1 + i = i + 1 + + if self._type == SANE_TYPE_FIXED.value: + self._constraint = [SANE_UNFIX(i) for i in self._constraint] elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 + + if self._type == SANE_TYPE_FIXED.value: + self._constraint = [str(SANE_UNFIX(int(i))) for i in self._constraint] else: self._constraint = None # Read only properties def __get_name(self): """ Get the short-form name of this option, e.g. 'mode'. May be an empty string, but never None. """ return self._name name = property(__get_name) def __get_title(self): """ Get the full name of this option, e.g. 'Scan mode'. May be an empty string, but never None. """ return self._title title = property(__get_title) def __get_description(self): """ Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' May be an empty string, but never None. """ return self._description description = property(__get_description) def __get_type(self): """ Get the type of this option, e.g. OPTION_TYPE_STRING. """ return self._type type = property(__get_type) def __get_unit(self): """ Get the unit of this option, e.g.OPTION_UNIT_DPI. """ return self._unit unit = property(__get_unit) def __get_constraint_type(self): """ Get the type of constraint on this option, e.g. OPTION_CONSTRAINT_RANGE. """ return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. - If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then - this is a list of integers which are valid values. + If constraint_type is OPTION_CONSTRAINT_VALUE_LIST then + this is a list of ints/floats which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """value Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option( handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i.' % status, device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value + elif self._type == SANE_TYPE_FIXED.value: + option_value = SANE_UNFIX(option_value.value) else: option_value = option_value.contents.value if self._log: self._log.debug( 'Option %s queried, its current value is %s.', self._name, option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: raise TypeError( 'option set with %s, expected BooleanType' % type(value)) - c_value = pointer(c_int(value)) + c_value = pointer(SANE_Bool(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) - c_value = pointer(c_int(value)) + c_value = pointer(SANE_Int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 - if type(value) is not IntType: + if type(value) is not IntType and type(value) is not FloatType: raise TypeError( - 'option set with %s, expected IntType' % type(value)) - c_value = pointer(c_int(value)) + 'option set with %s, expected IntType or FloatType' % type(value)) + c_value = pointer(SANE_Fixed(SANE_FIX(value))) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: raise TypeError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: raise ValueError( 'value for option is longer than max string size') - c_value = c_char_p(value) + c_value = SANE_String(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: min, max, step = self._constraint if value < min: raise ValueError('value for option is less than min.') if value > max: raise ValueError('value for option is greater than max.') if step is not None and step > 0: if value % step != 0: raise ValueError( 'value for option is not evenly divisible by step.') elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i .' % status, device=self._device) if self._log: self._log.debug('Option %s set to value %s.', self._name, value) # See SANE API 4.3.7 if info_flags.value & SANE_INFO_RELOAD_OPTIONS: raise SaneReloadOptionsError() # Catching this can not be avoided by constraint checking, as some # devices restrict option values without setting a constraint range # step. if info_flags.value & SANE_INFO_INEXACT: raise SaneInexactValueError() # TODO? if info_flags.value & SANE_INFO_RELOAD_PARAMS: pass value = property(__get_value, __set_value) # PUBLIC METHODS def is_soft_settable(self): """ Returns True if the option can be set by software. """ return self._capability & SANE_CAP_SOFT_SELECT def is_hard_settable(self): """ Returns True if the option can be set by hardware. """ return self._capability & SANE_CAP_HARD_SELECT def is_soft_gettable(self): """ Returns True if the option can be read by software. """ return self._capability & SANE_CAP_SOFT_DETECT def is_emulated(self): """ Returns True if the option is emulated by the backend driver. """ return self._capability & SANE_CAP_EMULATED # def is_automatic(self): # return self._capability & SANE_CAP_AUTOMATIC def is_active(self): """ Returns False if this device is unavailable because of the value of some other option. """ return not self._capability & SANE_CAP_INACTIVE # def is_advanced(self): # return self._capability & SANE_CAP_ADVANCED class ScanInfo(object): """ Contains the parameters and progress of a scan in progress. """ _width = 0 _height = 0 _depth = 0 _total_bytes = 0 def __init__(self, sane_parameters): """ Initialize the ScanInfo object from the sane_parameters. """ self._width = sane_parameters.pixels_per_line self._height = sane_parameters.lines self._depth = sane_parameters.depth self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines # Read only properties def __get_width(self): """Get the width of the current scan, in pixels.""" return self._width width = property(__get_width) def __get_height(self): """Get the height of the current scan, in pixels.""" return self._height height = property(__get_height) def __get_depth(self): """Get the depth of the current scan, in bits.""" return self._depth depth = property(__get_depth) def __get_total_bytes(self): """Get the total number of bytes comprising this scan.""" return self._total_bytes total_bytes = property(__get_total_bytes) \ No newline at end of file
onyxfish/nostaples
a4c00743eccb3e80c868bd0c1b2acb2f162f2ff3
Fix copy/paste error caught in read through of previous commit.
diff --git a/models/main.py b/models/main.py index 481c3a5..23dad8d 100644 --- a/models/main.py +++ b/models/main.py @@ -1,488 +1,488 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme import nostaples.utils.properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it's option constraints can be queried without error. if value is not None: # Verify that the proper type is being set assert isinstance(value, saneme.Device) # Open the new scanner try: value.open() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Load the option constraints (valid_modes, etc.) for the new device self._load_scanner_option_constraints(value) # Manually constrain option values if self._prop_active_mode not in self._prop_valid_modes: self._prop_active_mode = self._prop_valid_modes[0] if self._prop_active_resolution not in self._prop_valid_resolutions: self._prop_active_resolution = self._prop_valid_resolutions[0] # Manually push option values to new device try: try: value.options['mode'].value = self._prop_active_mode except saneme.SaneReloadOptionsError: pass try: value.options['resolution'].value = \ int(self._prop_active_resolution) except saneme.SaneReloadOptionsError: pass except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Emit change notifications for manually updated properties self.notify_property_value_change( 'valid_modes', None, self.valid_modes) self.notify_property_value_change( 'valid_resolutions', None, self.valid_resolutions) self.notify_property_value_change( 'active_mode', None, self.active_mode) self.notify_property_value_change( 'active_resolution', None, self.active_resolution) # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notifications self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_mode = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value self.active_scanner.options['mode'].value = value except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_mode'] = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_resolution = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value if self.active_scanner.options['resolution'].type == saneme.OPTION_TYPE_FIXED: self.active_scanner.options['resolution'].value = saneme.SANE_FIX(int(value)) else: self.active_scanner.options['resolution'].value = int(value) except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_resolution'] = value # Emit change notification self.notify_property_value_change( 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ Set the list of available scanners and update the active_scanner. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() self._prop_available_scanners = value self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None elif self._prop_active_scanner not in value: self.active_scanner = value[0] def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) if len(value) == 0: self.active_mode = None elif self.active_mode not in value: self.active_mode = value[0] def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) if len(value) == 0: self.active_resolution = None elif self.active_resolution not in value: self.active_resolution = value[0] # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution # INTERNAL METHODS def _load_scanner_option_constraints(self, sane_device): """ Load the option constraints from a specified scanner. """ main_controller = self.application.get_main_controller() try: assert sane_device.options['mode'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST self._prop_valid_modes = sane_device.options['mode'].constraint if sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_RANGE: min, max, step = sane_device.options['resolution'].constraint # Convert fixed point values if sane_device.options['resolution'].type == saneme.OPTION_TYPE_FIXED: min = saneme.SANE_UNFIX(min) max = saneme.SANE_UNFIX(max) step = saneme.SANE_UNFIX(step) # Fix for ticket #34. if step is None or step == 0: step = 1 resolutions = [] # If there are not an excessive number, include every possible # resolution if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: i = min while i <= max: resolutions.append(str(i)) i = i + step # Otherwise, take a crack at building a sensible set of options # that mean that constraint criteria else: i = 1 increment = (max - min) / (constants.MAX_VALID_OPTION_VALUES - 1) while (i <= constants.MAX_VALID_OPTION_VALUES - 2): unrounded = min + (i * increment) rounded = int(round(unrounded / step) * step) resolutions.append(str(rounded)) i = i + 1 resolutions.insert(0, str(min)) resolutions.append(str(max)) self._prop_valid_resolutions = resolutions elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_INTEGER_LIST: # Convert fixed point values to floats if sane_device.options['resolution'].type == saneme.OPTION_TYPE_FIXED: temp_value_resolutions = [saneme.SANE_UNFIX(i) for i in sane_device.options['resolution'].constraint] else: temp_value_resolutions = sane_device.options['resolution'].constraint # Convert values to strings for display self._prop_valid_resolutions = \ [str(i) for i in temp_value_resolutions] elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST: # Convert fixed point values to floats # (keeping in mind these are strings representing fixed points) if sane_device.options['resolution'].type == saneme.OPTION_TYPE_FIXED: temp_value_resolutions = [int(i) for i in sane_device.options['resolution'].constraint] temp_value_resolutions = [saneme.SANE_UNFIX(i) for i in temp_value_resolutions] - temp_value_resolutions = [str(i) for i in sane_device.options['resolution'].constraint] + temp_value_resolutions = [str(i) for i in temp_value_resolutions] else: temp_value_resolutions = sane_device.options['resolution'].constraint self._prop_valid_resolutions = temp_value_resolutions else: raise AssertionError('Unsupported constraint type.') except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) def _load_scanner_option_values(self): """ Get current scanner options from the active_scanner. Useful for reloading any option that may have changed in response to a SaneReloadOptionsError. """ main_controller = self.application.get_main_controller() try: # TODO: ReloadOptions should reload constraints as well as values! self.active_mode = self.active_scanner.options['mode'].value if self.active_scanner.options['resolution'].type == saneme.OPTION_TYPE_FIXED: str(saneme.SANE_UNFIX(self.active_scanner.options['resolution'].value)) else: str(self.active_scanner.options['resolution'].value) except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) \ No newline at end of file
onyxfish/nostaples
d8b751e6a9d7279a1e81206f0437edb3c54c99d7
Experimental fix for Fixed Point resolution values/constraints.
diff --git a/controllers/main.py b/controllers/main.py index fd71a3c..db9e39e 100644 --- a/controllers/main.py +++ b/controllers/main.py @@ -74,709 +74,742 @@ class MainController(Controller): """ self.adapt('show_toolbar', 'show_toolbar_menu_item') self.adapt('show_statusbar', 'show_statusbar_menu_item') self.adapt('show_thumbnails', 'show_thumbnails_menu_item') self.adapt('show_adjustments', 'show_adjustments_menu_item') self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS # Menu Items def on_scan_window_destroy(self, window): """Exits the application.""" self.quit() def on_scan_menu_item_activate(self, menu_item): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_menu_item_activate(self, menu_item): """Refresh the list of connected scanners from SANE.""" self._update_available_scanners() def on_save_as_menu_item_activate(self, menu_item): """Saves the current document to a file.""" self.application.show_save_dialog() def on_delete_menu_item_activate(self, menu_item): self.application.get_document_controller().delete_selected() def on_preferences_menu_item_activate(self, menu_item): """Creates and displays a preferences dialog.""" self.application.show_preferences_dialog() def on_quit_menu_item_activate(self, menu_item): """Exits the application.""" self.quit() def on_zoom_in_menu_item_activate(self, menu_item): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_menu_item_activate(self, menu_item): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_menu_item_activate(self, menu_item): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_menu_item_activate(self, menu_item): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_available_scanner_menu_item_toggled(self, menu_item): """ Set the active scanner. TODO: Need a second scanner to properly test this... """ main_model = self.application.get_main_model() if menu_item.get_active(): for scanner in main_model.available_scanners: if scanner.display_name == menu_item.get_children()[0].get_text(): main_model.active_scanner = scanner return def on_valid_mode_menu_item_toggled(self, menu_item): """Sets the active scan mode.""" if menu_item.get_active(): self.application.get_main_model().active_mode = \ menu_item.get_children()[0].get_text() def on_valid_resolution_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_resolution = \ menu_item.get_children()[0].get_text() def on_go_first_menu_item_activate(self, menu_item): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_menu_item_activate(self, menu_item): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_menu_item_activate(self, menu_item): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_menu_item_activate(self, menu_item): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() def on_contents_menu_item_clicked(self, menu_item): """TODO""" pass def on_about_menu_item_activate(self, menu_item): """Show the about dialog.""" self.application.show_about_dialog() # Toolbar Buttons def on_scan_button_clicked(self, button): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_button_clicked(self, button): self._update_available_scanners() def on_save_as_button_clicked(self, button): """Saves the current document to a file.""" self.application.show_save_dialog() def on_zoom_in_button_clicked(self, button): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_button_clicked(self, button): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_button_clicked(self, button): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_button_clicked(self, button): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_go_first_button_clicked(self, button): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_button_clicked(self, button): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_button_clicked(self, button): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_button_clicked(self, button): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() # Progress Window INTERFACE CALLBACKS def on_progress_window_delete_event(self, window, event): """ Emulate clicking of the cancel/close button and then hide the window. """ main_view = self.application.get_main_view() self.on_scan_cancel_button_clicked(None) main_view['progress_window'].hide() return True def on_scan_cancel_button_clicked(self, button): """ Cancel the current scan or, if the scan is finished, close the progress window. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress: assert self.cancel_event self.cancel_event.set() else: main_view['progress_window'].hide() def on_scan_again_button_clicked(self, button): """Initiate a new scan from the progress window.""" self._scan() def on_quick_save_button_clicked(self, button): """ Show the save dialog. If the user completes a save then disable the quick save button until another page is scanned. """ main_view = self.application.get_main_view() document_model = self.application.get_document_model() self.application.show_save_dialog() if document_model.count == 0: main_view['quick_save_button'].set_sensitive(False) # MainModel PROPERTY CALLBACKS def property_show_toolbar_value_change(self, model, old_value, new_value): """Update the visibility of the toolbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_toolbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['main_toolbar'].show() else: main_view['main_toolbar'].hide() def property_show_statusbar_value_change(self, model, old_value, new_value): """Update the visibility of the statusbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_statusbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['status_view_docking_viewport'].show() else: main_view['status_view_docking_viewport'].hide() def property_show_thumbnails_value_change(self, model, old_value, new_value): """Update the visibility of the thumbnails.""" main_view = self.application.get_main_view() menu_item = main_view['show_thumbnails_menu_item'] menu_item.set_active(new_value) self.application.get_document_controller().toggle_thumbnails_visible(new_value) def property_show_adjustments_value_change(self, model, old_value, new_value): """Update the visibility of the adjustments controls.""" document_controller = self.application.get_document_controller() main_view = self.application.get_main_view() menu_item = main_view['show_adjustments_menu_item'] menu_item.set_active(new_value) document_controller.toggle_adjustments_visible(new_value) def property_active_scanner_value_change(self, model, old_value, new_value): """ Update the menu and valid scanner options to match the new device. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() if new_value == None: return for menu_item in main_view['scanner_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value.display_name: menu_item.set_active(True) break def property_active_mode_value_change(self, model, old_value, new_value): """Select the active mode from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_mode_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_resolution_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_resolution_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_available_scanners_value_change(self, model, old_value, new_value): """ Update the menu of available scanners. """ main_view = self.application.get_main_view() self._clear_available_scanners_sub_menu() # Generate the new menu if len(new_value) == 0: menu_item = gtk.MenuItem('No Scanners Connected') menu_item.set_sensitive(False) main_view['scanner_sub_menu'].append(menu_item) else: first_item = None for i in range(len(new_value)): # The first menu item defines the group if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i].display_name) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i].display_name) main_view['scanner_sub_menu'].append(menu_item) main_view['scanner_sub_menu'].show_all() def property_valid_modes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan modes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_modes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Modes") menu_item.set_sensitive(False) main_view['scan_mode_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled) main_view['scan_mode_sub_menu'].append(menu_item) main_view['scan_mode_sub_menu'].show_all() def property_valid_resolutions_value_change(self, model, old_value, new_value): """ Updates the list of valid scan resolutions for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_resolutions_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Resolutions") menu_item.set_sensitive(False) main_view['scan_resolution_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled) main_view['scan_resolution_sub_menu'].append(menu_item) main_view['scan_resolution_sub_menu'].show_all() def property_scan_in_progress_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() def property_updating_available_scanners_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() # DocumentModel PROPERTY CALLBACKS def property_count_value_change(self, model, old_value, new_value): """Toggle available controls.""" self._toggle_document_controls() # PreferencesModel PROPERTY CALLBACKS def property_toolbar_style_value_change(self, model, old_value, new_value): """Toggle available controls.""" main_view = self.application.get_main_view() if new_value == 'System Default': # TODO - reset style to system default pass else: main_view['main_toolbar'].set_style(constants.TOOLBAR_STYLES[new_value]) # THREAD CALLBACKS def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned): main_view = self.application.get_main_view() short_bytes_scanned = float(bytes_scanned) / 1000 short_total_bytes = float(scan_info.total_bytes) / 1000 main_view['scan_progressbar'].set_fraction( float(bytes_scanned) / scan_info.total_bytes) main_view['scan_progressbar'].set_text( 'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes)) # TODO: multi page scans main_view['progress_secondary_label'].set_markup( '<i>Scanning page.</i>') def on_scan_succeeded(self, scanning_thread, pil_image): """ Append the new page to the current document. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['scan_progressbar'].set_fraction(1) main_view['scan_progressbar'].set_text('Scan complete') main_view['progress_secondary_label'].set_markup( '<i>Adding page to document.</i>') gtk.gdk.flush() new_page = PageModel(self.application, pil_image, int(main_model.active_resolution)) self.application.get_document_model().append(new_page) main_view['progress_secondary_label'].set_markup( '<i>Page added.</i>') main_view['scan_again_button'].set_sensitive(True) main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_failed(self, scanning_thread, reason): """ Set that scan is complete. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['progress_secondary_label'].set_markup( '<i>%s</i>' % reason) main_view['scan_again_button'].set_sensitive(True) if self.application.get_document_model().count > 0: main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_aborted(self, scanning_thread, exc_info): """ Change display to indicate that scanning failed and convey the to the user the reason why the thread aborted. If the failure was from a SANE exception then give the user the option to blacklist the device. If not, then reraise the error and let the sys.excepthook deal with it. """ self.on_scan_failed(scanning_thread, 'An error occurred.') if isinstance(exc_info[1], saneme.SaneError): self.run_device_exception_dialog(exc_info) else: raise exc_info[0], exc_info[1], exc_info[2] def on_update_available_scanners_thread_finished(self, update_thread, scanner_list): """Set the new list of available scanners.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() status_controller = self.application.get_status_controller() # Remove blacklisted scanners scanner_list = \ [scanner for scanner in scanner_list if not \ scanner.display_name in preferences_model.blacklisted_scanners] # Remove scanners that do not support necessary options or fail to # open entirely preferences_model.unavailable_scanners = [] def is_supported_option(option): """Verify an option supports necessary capabilities to be useful.""" return option.is_active() and \ option.is_soft_gettable() and \ option.is_soft_settable() + + def is_supported_mode(option): + """Verify that the mode conforms to type expectations.""" + if not is_supported_option(option): + return False + + if not option.constraint_type == \ + saneme.OPTION_CONSTRAINT_STRING_LIST: + return False + + return True + + def is_supported_resolution(option): + """ + Verify that the resolution conforms to type expectations. + + Where noted these stem from the SANE API standards. Others are + simply limitations on what has currently been implemented in + NoStaples. + """ + if not is_supported_option(option): + return False + + # See SANE API 4.5.2 + if option.type != saneme.OPTION_TYPE_INT and \ + option.type != saneme.OPTION_TYPE_FIXED: + return False + + # See SANE API 4.5.2 + if not option.unit == saneme.OPTION_UNIT_DPI: + return False + + return True for scanner in scanner_list: try: scanner.open() if not scanner.has_option('mode') or \ - not is_supported_option(scanner.options['mode']) or \ + not is_supported_mode(scanner.options['mode']) or \ not scanner.has_option('resolution') or \ - not is_supported_option(scanner.options['resolution']): + not is_supported_resolution(scanner.options['resolution']): preferences_model.unavailable_scanners.append(scanner.display_name) scanner_list.remove(scanner) scanner.close() except saneme.SaneError: preferences_model.unavailable_scanners.append(scanner.display_name) scanner_list.remove(scanner) main_model.available_scanners = scanner_list main_model.updating_available_scanners = False def on_update_available_scanners_thread_aborted(self, update_thread, exc_info): """ Change the display to indicate that no scanners are available and reraise the exception so that it can be caught by the sys.excepthook. There is no reason to handle these cases with a special dialog, if the application failed to even enumerate the available devices then no other action will be possible. This should be fantastically rare. """ self.on_update_available_scanners_thread_finished(update_thread, []) raise exc_info[0], exc_info[1], exc_info[2] # PUBLIC METHODS def quit(self): """Exits the application.""" self.log.debug('Quit.') gtk.main_quit() def run_device_exception_dialog(self, exc_info): """ Display an error dialog that provides the user with the option of blacklisting the device which caused the error. TODO: Move into MainView. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() preferences_model = self.application.get_preferences_model() response = main_view.run_device_exception_dialog(exc_info) if response == constants.RESPONSE_BLACKLIST_DEVICE: temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(exc_info[1].device.display_name) temp_blacklist.sort() preferences_model.blacklisted_scanners = temp_blacklist # PRIVATE METHODS def _clear_available_scanners_sub_menu(self): """Clear the menu of available scanners.""" main_view = self.application.get_main_view() for child in main_view['scanner_sub_menu'].get_children(): main_view['scanner_sub_menu'].remove(child) def _clear_scan_modes_sub_menu(self): """Clear the menu of valid scan modes.""" main_view = self.application.get_main_view() for child in main_view['scan_mode_sub_menu'].get_children(): main_view['scan_mode_sub_menu'].remove(child) def _clear_scan_resolutions_sub_menu(self): """Clear the menu of valid scan resolutions.""" main_view = self.application.get_main_view() for child in main_view['scan_resolution_sub_menu'].get_children(): main_view['scan_resolution_sub_menu'].remove(child) def _toggle_scan_controls(self): """Toggle whether or not the scan controls or accessible.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_scan_controls_sensitive(False) main_view.set_refresh_scanner_controls_sensitive(False) else: if main_model.active_scanner != None: main_view.set_scan_controls_sensitive(True) main_view.set_refresh_scanner_controls_sensitive(True) def _toggle_document_controls(self): """ Toggle available document controls based on the current scanner status and the number of scanned pages. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() # Disable all controls when the scanner is in use if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: count = self.application.get_document_model().count # Disable all controls if no pages are scanned if count == 0: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: # Enable most controls if any pages scanned main_view.set_file_controls_sensitive(True) main_view.set_delete_controls_sensitive(True) main_view.set_zoom_controls_sensitive(True) main_view.set_adjustment_controls_sensitive(True) # Only enable navigation if more than one page scanned if count > 1: main_view.set_navigation_controls_sensitive(True) else: main_view.set_navigation_controls_sensitive(False) def _update_status(self): """ Update the text of the statusbar based on the current state of the application. """ main_model = self.application.get_main_model() status_controller = self.application.get_status_controller() status_controller.pop(self.status_context) if main_model.scan_in_progress: status_controller.push(self.status_context, 'Scanning...') elif main_model.updating_available_scanners: status_controller.push(self.status_context, 'Querying hardware...') else: if main_model.active_scanner: status_controller.push(self.status_context, 'Ready with %s.' % main_model.active_scanner.display_name) else: status_controller.push(self.status_context, 'No scanner available.') def _scan(self): """Begin a scan.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() main_model.scan_in_progress = True scanning_thread = ScanningThread(main_model.active_scanner) scanning_thread.connect("progress", self.on_scan_progress) scanning_thread.connect("succeeded", self.on_scan_succeeded) scanning_thread.connect("failed", self.on_scan_failed) scanning_thread.connect("aborted", self.on_scan_aborted) self.cancel_event = scanning_thread.cancel_event main_view['progress_primary_label'].set_markup( '<big><b>%s</b></big>' % main_model.active_scanner.display_name) main_view['scan_progressbar'].set_fraction(0) main_view['scan_progressbar'].set_text('Waiting for data') main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>') mode = main_model.active_mode if main_model.active_mode else 'Not set' main_view['progress_mode_label'].set_markup(mode) dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set' main_view['progress_resolution_label'].set_markup(dpi) main_view['scan_again_button'].set_sensitive(False) main_view['quick_save_button'].set_sensitive(False) main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL) main_view['progress_window'].show_all() scanning_thread.start() def _update_available_scanners(self): """ Start a new update thread to query for available scanners. """ sane = self.application.get_sane() main_model = self.application.get_main_model() main_model.updating_available_scanners = True update_thread = UpdateAvailableScannersThread(sane) update_thread.connect("finished", self.on_update_available_scanners_thread_finished) update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted) update_thread.start() \ No newline at end of file diff --git a/models/main.py b/models/main.py index bc28f90..481c3a5 100644 --- a/models/main.py +++ b/models/main.py @@ -1,460 +1,488 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme import nostaples.utils.properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it's option constraints can be queried without error. if value is not None: # Verify that the proper type is being set assert isinstance(value, saneme.Device) # Open the new scanner try: value.open() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Load the option constraints (valid_modes, etc.) for the new device self._load_scanner_option_constraints(value) # Manually constrain option values if self._prop_active_mode not in self._prop_valid_modes: self._prop_active_mode = self._prop_valid_modes[0] if self._prop_active_resolution not in self._prop_valid_resolutions: self._prop_active_resolution = self._prop_valid_resolutions[0] # Manually push option values to new device try: try: value.options['mode'].value = self._prop_active_mode except saneme.SaneReloadOptionsError: pass try: value.options['resolution'].value = \ int(self._prop_active_resolution) except saneme.SaneReloadOptionsError: pass except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Emit change notifications for manually updated properties self.notify_property_value_change( 'valid_modes', None, self.valid_modes) self.notify_property_value_change( 'valid_resolutions', None, self.valid_resolutions) self.notify_property_value_change( 'active_mode', None, self.active_mode) self.notify_property_value_change( 'active_resolution', None, self.active_resolution) # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notifications self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_mode = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value self.active_scanner.options['mode'].value = value except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_mode'] = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_resolution = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value - self.active_scanner.options['resolution'].value = int(value) + if self.active_scanner.options['resolution'].type == saneme.OPTION_TYPE_FIXED: + self.active_scanner.options['resolution'].value = saneme.SANE_FIX(int(value)) + else: + self.active_scanner.options['resolution'].value = int(value) except saneme.SaneInexactValueError: # TODO - what if "exact" value isn't in the list? pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_resolution'] = value # Emit change notification self.notify_property_value_change( 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ Set the list of available scanners and update the active_scanner. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() self._prop_available_scanners = value self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None elif self._prop_active_scanner not in value: self.active_scanner = value[0] def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) if len(value) == 0: self.active_mode = None elif self.active_mode not in value: self.active_mode = value[0] def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) if len(value) == 0: self.active_resolution = None elif self.active_resolution not in value: self.active_resolution = value[0] # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution # INTERNAL METHODS def _load_scanner_option_constraints(self, sane_device): """ Load the option constraints from a specified scanner. """ main_controller = self.application.get_main_controller() try: assert sane_device.options['mode'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST self._prop_valid_modes = sane_device.options['mode'].constraint if sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_RANGE: min, max, step = sane_device.options['resolution'].constraint + # Convert fixed point values + if sane_device.options['resolution'].type == saneme.OPTION_TYPE_FIXED: + min = saneme.SANE_UNFIX(min) + max = saneme.SANE_UNFIX(max) + step = saneme.SANE_UNFIX(step) + # Fix for ticket #34. if step is None or step == 0: step = 1 resolutions = [] # If there are not an excessive number, include every possible # resolution if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: i = min while i <= max: resolutions.append(str(i)) i = i + step # Otherwise, take a crack at building a sensible set of options # that mean that constraint criteria else: i = 1 increment = (max - min) / (constants.MAX_VALID_OPTION_VALUES - 1) while (i <= constants.MAX_VALID_OPTION_VALUES - 2): unrounded = min + (i * increment) rounded = int(round(unrounded / step) * step) resolutions.append(str(rounded)) i = i + 1 resolutions.insert(0, str(min)) resolutions.append(str(max)) self._prop_valid_resolutions = resolutions elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_INTEGER_LIST: + # Convert fixed point values to floats + if sane_device.options['resolution'].type == saneme.OPTION_TYPE_FIXED: + temp_value_resolutions = [saneme.SANE_UNFIX(i) for i in sane_device.options['resolution'].constraint] + else: + temp_value_resolutions = sane_device.options['resolution'].constraint + + # Convert values to strings for display self._prop_valid_resolutions = \ - [str(i) for i in sane_device.options['resolution'].constraint] + [str(i) for i in temp_value_resolutions] elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST: - sane_device.options['resolution'].constraint + # Convert fixed point values to floats + # (keeping in mind these are strings representing fixed points) + if sane_device.options['resolution'].type == saneme.OPTION_TYPE_FIXED: + temp_value_resolutions = [int(i) for i in sane_device.options['resolution'].constraint] + temp_value_resolutions = [saneme.SANE_UNFIX(i) for i in temp_value_resolutions] + temp_value_resolutions = [str(i) for i in sane_device.options['resolution'].constraint] + else: + temp_value_resolutions = sane_device.options['resolution'].constraint + + self._prop_valid_resolutions = temp_value_resolutions else: raise AssertionError('Unsupported constraint type.') except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) def _load_scanner_option_values(self): """ Get current scanner options from the active_scanner. Useful for reloading any option that may have changed in response to a SaneReloadOptionsError. """ main_controller = self.application.get_main_controller() try: # TODO: ReloadOptions should reload constraints as well as values! self.active_mode = self.active_scanner.options['mode'].value - self.active_resolution = \ + + if self.active_scanner.options['resolution'].type == saneme.OPTION_TYPE_FIXED: + str(saneme.SANE_UNFIX(self.active_scanner.options['resolution'].value)) + else: str(self.active_scanner.options['resolution'].value) except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) \ No newline at end of file
onyxfish/nostaples
8268a836c33d9bbe1315d3575542b6ef479ba3f2
Scanner management buttons can no longer be selected if no device is selected.
diff --git a/controllers/preferences.py b/controllers/preferences.py index 2cfb931..81437bb 100644 --- a/controllers/preferences.py +++ b/controllers/preferences.py @@ -1,274 +1,284 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{PreferencesController}, which manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ import logging import gtk from gtkmvc.controller import Controller from nostaples import constants from nostaples.utils.gui import read_combobox class PreferencesController(Controller): """ Manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the PreferencesController. """ self.application = application Controller.__init__(self, application.get_preferences_model()) application.get_main_model().register_observer(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ pass # USER INTERFACE CALLBACKS def on_preview_mode_combobox_changed(self, combobox): """Update the preview mode in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.preview_mode = \ read_combobox(preferences_view['preview_mode_combobox']) def on_thumbnail_size_combobox_changed(self, combobox): """Update the thumbnail size in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.thumbnail_size = \ int(read_combobox(preferences_view['thumbnail_size_combobox'])) def on_toolbar_style_combobox_changed(self, combobox): """Update the toolbar style in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.toolbar_style = \ read_combobox(preferences_view['toolbar_style_combobox']) def on_remove_from_blacklist_button_clicked(self, button): """ Remove the currently selected blacklist device from the list. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['blacklist_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.remove(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_add_to_blacklist_button_clicked(self, button): """ Move the currently selected available scanner to the blacklist. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['available_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_remove_from_keywords_button_clicked(self, button): """ Remove the currently selected keyword from the list. """ preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['keywords_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_keywords = list(preferences_model.saved_keywords) temp_keywords.remove(selection_text) preferences_model.saved_keywords = temp_keywords + + def on_blacklist_tree_view_selection_changed(self, selection): + """Update the available device controls.""" + self._toggle_device_controls() + + def on_available_tree_view_selection_changed(self, selection): + """Update the available device controls.""" + self._toggle_device_controls() def on_preferences_dialog_response(self, dialog, response): """Close the preferences dialog.""" preferences_view = self.application.get_preferences_view() preferences_view['preferences_dialog'].hide() # PROPERTY CALLBACKS def property_preview_mode_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_thumbnail_size_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_toolbar_style_value_change(self, model, old_value, new_value): # TODO - set the combobox (in case the change came form state) pass def property_unavailable_scanners_value_change(self, model, old_value, new_value): """Update unavailable scanners liststore.""" preferences_view = self.application.get_preferences_view() unavailable_liststore = preferences_view['unavailable_tree_view'].get_model() unavailable_liststore.clear() for unavailable_item in new_value: unavailable_liststore.append([unavailable_item]) def property_blacklisted_scanners_value_change(self, model, old_value, new_value): """Update blacklisted scanners liststore.""" preferences_view = self.application.get_preferences_view() blacklist_liststore = preferences_view['blacklist_tree_view'].get_model() blacklist_liststore.clear() for blacklist_item in new_value: blacklist_liststore.append([blacklist_item]) self._toggle_device_controls() def property_available_scanners_value_change(self, model, old_value, new_value): """Update available scanners liststore.""" preferences_view = self.application.get_preferences_view() available_liststore = preferences_view['available_tree_view'].get_model() available_liststore.clear() for available_item in new_value: available_liststore.append([available_item.display_name]) self._toggle_device_controls() def property_updating_available_scanners_value_change(self, model, old_value, new_value): """ Disable device management controls while devices are being updated. """ self._toggle_device_controls() def property_saved_keywords_value_change(self, model, old_value, new_value): """Update keywords liststore.""" preferences_view = self.application.get_preferences_view() keywords_liststore = preferences_view['keywords_tree_view'].get_model() keywords_liststore.clear() for keyword in new_value: keywords_liststore.append([keyword]) # PUBLIC METHODS def run(self): """Run the preferences dialog.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() # Force property updates when dialog is run: this handles the case # where the PreferencesController has not been created until now # so it has not been receiving property notifications. self.property_unavailable_scanners_value_change( preferences_model, None, preferences_model.unavailable_scanners) self.property_blacklisted_scanners_value_change( preferences_model, None, preferences_model.blacklisted_scanners) self.property_available_scanners_value_change( main_model, None, main_model.available_scanners) self.property_saved_keywords_value_change( preferences_model, None, preferences_model.saved_keywords) preferences_view.run() # PRIVATE METHODS def _toggle_device_controls(self): """ Toggle the availability of the scanner management controls based on the state of the application. """ main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() if main_model.updating_available_scanners: preferences_view['remove_from_blacklist_button'].set_sensitive(False) preferences_view['add_to_blacklist_button'].set_sensitive(False) else: - if len(preferences_model.blacklisted_scanners) > 0: + if preferences_view['blacklist_tree_view'].get_selection().count_selected_rows() > 0: + #if len(preferences_model.blacklisted_scanners) > 0: preferences_view['remove_from_blacklist_button'].set_sensitive(True) else: preferences_view['remove_from_blacklist_button'].set_sensitive(False) - if len(main_model.available_scanners) > 0: + if preferences_view['available_tree_view'].get_selection().count_selected_rows() > 0: + #if len(main_model.available_scanners) > 0: preferences_view['add_to_blacklist_button'].set_sensitive(True) else: preferences_view['add_to_blacklist_button'].set_sensitive(False) \ No newline at end of file diff --git a/views/preferences.py b/views/preferences.py index 3986b6f..a1a8c3e 100644 --- a/views/preferences.py +++ b/views/preferences.py @@ -1,164 +1,172 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the PreferencesView which exposes user settings through a dialog seperate from the main application window. """ import logging import os import gtk from gtkmvc.view import View from nostaples import constants from nostaples.utils.gui import read_combobox, setup_combobox class PreferencesView(View): """ Exposes user settings through a dialog seperate from the main application window. """ def __init__(self, application): """ Constructs the PreferencesView, including setting up controls that could not be configured in Glade. """ self.application = application preferences_controller = application.get_preferences_controller() preferences_dialog_glade = os.path.join( constants.GUI_DIRECTORY, 'preferences_dialog.glade') View.__init__( self, preferences_controller, preferences_dialog_glade, 'preferences_dialog', None, False) self.log = logging.getLogger(self.__class__.__name__) # Can not configure this via constructor do to the multiple # root windows in the Main View. self['preferences_dialog'].set_transient_for( application.get_main_view()['scan_window']) # These two combobox's are setup dynamically. Because of this they # must have their signal handlers connected manually. Otherwise # their signals will fire before the view creation is finished. setup_combobox( self['preview_mode_combobox'], constants.PREVIEW_MODES_LIST, application.get_preferences_model().preview_mode) self['preview_mode_combobox'].connect( 'changed', preferences_controller.on_preview_mode_combobox_changed) setup_combobox( self['thumbnail_size_combobox'], constants.THUMBNAIL_SIZE_LIST, application.get_preferences_model().thumbnail_size) self['thumbnail_size_combobox'].connect( 'changed', preferences_controller.on_thumbnail_size_combobox_changed) setup_combobox( self['toolbar_style_combobox'], constants.TOOLBAR_STYLES_LIST, application.get_preferences_model().toolbar_style) self['toolbar_style_combobox'].connect( 'changed', preferences_controller.on_toolbar_style_combobox_changed) # Setup the unavailable scanners tree view unavailable_liststore = gtk.ListStore(str) self['unavailable_tree_view'] = gtk.TreeView() self['unavailable_tree_view'].set_model(unavailable_liststore) self['unavailable_column'] = gtk.TreeViewColumn(None) self['unavailable_cell'] = gtk.CellRendererText() self['unavailable_tree_view'].append_column(self['unavailable_column']) self['unavailable_column'].pack_start(self['unavailable_cell'], True) self['unavailable_column'].add_attribute( self['unavailable_cell'], 'text', 0) self['unavailable_tree_view'].get_selection().set_mode( gtk.SELECTION_NONE) self['unavailable_tree_view'].set_headers_visible(False) self['unavailable_tree_view'].set_property('can-focus', False) self['unavailable_scrolled_window'].add(self['unavailable_tree_view']) self['unavailable_scrolled_window'].show_all() # Setup the blacklist tree view blacklist_liststore = gtk.ListStore(str) self['blacklist_tree_view'] = gtk.TreeView() self['blacklist_tree_view'].set_model(blacklist_liststore) self['blacklist_column'] = gtk.TreeViewColumn(None) self['blacklist_cell'] = gtk.CellRendererText() self['blacklist_tree_view'].append_column(self['blacklist_column']) self['blacklist_column'].pack_start(self['blacklist_cell'], True) self['blacklist_column'].add_attribute(self['blacklist_cell'], 'text', 0) self['blacklist_tree_view'].get_selection().set_mode( gtk.SELECTION_SINGLE) self['blacklist_tree_view'].set_headers_visible(False) self['blacklist_tree_view'].set_property('can-focus', False) self['blacklist_scrolled_window'].add(self['blacklist_tree_view']) self['blacklist_scrolled_window'].show_all() - # Setup the keywords tree view - keywords_liststore = gtk.ListStore(str) - self['keywords_tree_view'] = gtk.TreeView() - self['keywords_tree_view'].set_model(keywords_liststore) - self['keywords_column'] = gtk.TreeViewColumn(None) - self['keywords_cell'] = gtk.CellRendererText() - self['keywords_tree_view'].append_column(self['keywords_column']) - self['keywords_column'].pack_start(self['keywords_cell'], True) - self['keywords_column'].add_attribute(self['keywords_cell'], 'text', 0) - self['keywords_tree_view'].get_selection().set_mode( - gtk.SELECTION_SINGLE) - self['keywords_tree_view'].set_headers_visible(False) - self['keywords_tree_view'].set_property('can-focus', False) - - self['keywords_scrolled_window'].add(self['keywords_tree_view']) - self['keywords_scrolled_window'].show_all() + self['blacklist_tree_view'].get_selection().connect( + 'changed', + preferences_controller.on_blacklist_tree_view_selection_changed) # Setup the available devices tree view available_liststore = gtk.ListStore(str) self['available_tree_view'] = gtk.TreeView() self['available_tree_view'].set_model(available_liststore) self['available_column'] = gtk.TreeViewColumn(None) self['available_cell'] = gtk.CellRendererText() self['available_tree_view'].append_column(self['available_column']) self['available_column'].pack_start(self['available_cell'], True) self['available_column'].add_attribute(self['available_cell'], 'text', 0) self['available_tree_view'].get_selection().set_mode( gtk.SELECTION_SINGLE) self['available_tree_view'].set_headers_visible(False) self['available_tree_view'].set_property('can-focus', False) self['available_scrolled_window'].add(self['available_tree_view']) self['available_scrolled_window'].show_all() + self['available_tree_view'].get_selection().connect( + 'changed', + preferences_controller.on_available_tree_view_selection_changed) + + # Setup the keywords tree view + keywords_liststore = gtk.ListStore(str) + self['keywords_tree_view'] = gtk.TreeView() + self['keywords_tree_view'].set_model(keywords_liststore) + self['keywords_column'] = gtk.TreeViewColumn(None) + self['keywords_cell'] = gtk.CellRendererText() + self['keywords_tree_view'].append_column(self['keywords_column']) + self['keywords_column'].pack_start(self['keywords_cell'], True) + self['keywords_column'].add_attribute(self['keywords_cell'], 'text', 0) + self['keywords_tree_view'].get_selection().set_mode( + gtk.SELECTION_SINGLE) + self['keywords_tree_view'].set_headers_visible(False) + self['keywords_tree_view'].set_property('can-focus', False) + + self['keywords_scrolled_window'].add(self['keywords_tree_view']) + self['keywords_scrolled_window'].show_all() + application.get_preferences_controller().register_view(self) self.log.debug('Created.') def run(self): """Run the modal preferences dialog.""" self['preferences_dialog'].run() \ No newline at end of file
onyxfish/nostaples
8d2637ea8152d131d1cd493be451390a9af2ed17
Fixed Lineart mode scanning.
diff --git a/nostaples b/nostaples index dfc8089..01e503e 100755 --- a/nostaples +++ b/nostaples @@ -1,172 +1,174 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. ''' This module parses command line options, checks that imports are available, and bootstraps the NoStaples application. ''' import optparse import sys import pygtk pygtk.require('2.0') import gtk # COMMAND LINE PARSING # Functions to pretty-print debugging info def print_device_debug(i, device): """Pretty-print device information.""" print 'Device %i' % i print '' print 'Name:\t%s' % device.name print 'Vendor:\t%s' % device.vendor print 'Model:\t%s' % device.model print 'Type:\t%s' % device.type print '' try: device.open() j = 1 for option in device.options.values(): print_option_debug(j, option) print '' j = j + 1 device.close() except Exception: print '\t**Failed to open device.**' def print_option_debug(j, option): """Pretty-print device option information.""" print '\tOption %i' % j print '' print '\tName:\t%s' % option._name print '\tTitle:\t%s' % option._title print '\tDesc:\t%s' % option._description print '\tType:\t%s' % option._type print '\tUnit:\t%s' % option._unit print '\tSize:\t%s' % option._size print '\tCap:\t%s' % option._capability print '\tConstraint Type:\t%s' % option._constraint_type print '\tConstraint:\t', option._constraint - if option.is_soft_gettable(): + if not option.is_active(): + print '\tValue:\tNot active.' + elif not option.is_soft_gettable(): + print '\tValue:\tNot soft-gettable.' + else: try: print '\tValue:\t%s' % str(option.value) except Exception: print '\t**Failed to get current value for option.**' - else: - print '\tValue:\tNot soft-gettable.' # Parse command line options parser = optparse.OptionParser() parser.add_option("--debugdevices", action="store_true", dest="debug_devices", help="print debugging information for all connected devices") (options, args) = parser.parse_args() if options.debug_devices: import nostaples.sane as saneme sane_manager = saneme.SaneMe() devices = sane_manager.get_device_list() if len(devices) == 0: print 'No devices found.' i = 1 for device in devices: print_device_debug(i, device) print '' i = i + 1 sys.exit() # CHECK IMPORT VERSIONS def display_import_error(message): """ Displays a GTK message dialog containing the import error and then exits the application. """ dialog = gtk.MessageDialog( parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_NONE) dialog.set_title('') primary = "<big><b>A required package is not installed.</b></big>" secondary = '%s' % message dialog.set_markup(primary) dialog.format_secondary_markup(secondary) dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) response = dialog.run() dialog.destroy() sys.exit() # Python if sys.version_info < (2, 5) or sys.version_info >= (3, 0): display_import_error( 'NoStaples requires Python version 2.5 or later (but not version 3.0 or later).') # GTK if gtk.gtk_version < (2, 6, 0): display_import_error( 'NoStaples requires GTK+ version 2.6 or later.') if gtk.pygtk_version < (2, 8, 0): display_import_error( 'NoStaples requires PyGTK version 2.8 or later.') # PIL try: import Image except ImportError: display_import_error( 'NoStaples requires the Python Imaging Library (PIL) 1.1.6 or later.') pil_version = tuple([int(i) for i in Image.VERSION.split('.')]) if pil_version < (1, 1, 6): display_import_error( 'NoStaples requires the Python Imaging Library (PIL) version 1.1.6 or later.') # ReportLab try: import reportlab except ImportError: display_import_error( 'NoStaples requires ReportLab version 2.1 or later.') reportlab_version = tuple([int(i) for i in reportlab.Version.split('.')]) if reportlab_version < (2, 1): display_import_error( 'NoStaples requires ReportLab version 2.1 or later.') # BOOTSTRAP from nostaples.application import Application nostaples = Application() nostaples.run() diff --git a/sane/saneme.py b/sane/saneme.py index a85e4e8..8dce78b 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -54,971 +54,944 @@ from saneh import * (OPTION_CONSTRAINT_NONE, OPTION_CONSTRAINT_RANGE, OPTION_CONSTRAINT_INTEGER_LIST, OPTION_CONSTRAINT_STRING_LIST) = xrange(4) class SaneMe(object): """ The top-level object for interacting with the SANE API. Handles polling for devices. This object should only be instantiated once. """ _log = None _version = None # (major, minor, build) _devices = [] def __init__(self, log=None): """ Create the SANE object, perform setup, and register the cleanup function. @param log: an optional Python logging object to log to. """ self._log = log self._setup() atexit.register(self._shutdown) # Read only properties def __get_version(self): """Get the current installed version of SANE.""" return self._version version = property(__get_version) def _setup(self): """ Iniitalize SANE and retrieve the current installed version. """ version_code = SANE_Int() auth_callback = SANE_Auth_Callback(self._sane_auth_callback) status = sane_init(byref(version_code), auth_callback) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_init returned an invalid status: %i.' % status) self._version = (SANE_VERSION_MAJOR(version_code), SANE_VERSION_MINOR(version_code), SANE_VERSION_BUILD(version_code)) if self._log: self._log.info('SANE version %s initalized.', self._version) def _sane_auth_callback(self, resource, username, password): """ TODO """ raise NotImplementedError( 'sane_auth_callback requested, but not yet implemented.') def _shutdown(self): """ Deinitialize SANE. This code would go in __del__, but it is not guaranteed that method will be called and sane_exit must be called to release resources. To ensure this method is called it is registered with atexit. """ for device in self._devices: if device.is_open(): device.close() sane_exit() self._version = None if self._log: self._log.info('SANE deinitialized.') # Public Methods def get_device_list(self): """ Poll for connected devices. This method may take several seconds to return. Note that SANE is exited and re-inited before querying for devices to workaround a limitation in SANE's USB driver which causes the device list to only be updated on init. This means that all settings applied to all devices will be B{lost} and must be restored by the calling application. This was found documented here: U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html} """ if not self._version: raise AssertionError('version was None') # See docstring for details on this voodoo self._shutdown() self._setup() cdevices = POINTER(POINTER(SANE_Device))() status = sane_get_devices(byref(cdevices), SANE_Bool(0)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_get_devices ran out of memory.') else: raise SaneUnknownError( 'sane_get_devices returned an invalid status: %i.' % status) device_count = 0 self._devices = [] while cdevices[device_count]: self._devices.append( Device(cdevices[device_count].contents, self._log)) device_count += 1 if self._log: self._log.info('SANE queried, %i device(s) found.', device_count) return self._devices def get_device_by_name(self, name): """ Retrieve a L{Device} by name. Must be preceded by a call to L{get_device_list}. """ for device in self._devices: if device.name == name: return device raise SaneNoSuchDeviceError( 'The requested device does not exist.') class Device(object): """ This is the primary object for interacting with SANE. It represents a single device and handles enumeration of options, getting and setting of options, and starting and stopping of scanning jobs. """ _log = None _handle = None _name = '' _vendor = '' _model = '' _type = '' _display_name = '' _options = {} def __init__(self, ctypes_device, log=None): """ Sets the Devices properties from a ctypes SANE_Device and queries for its available options. """ self._log = log # String attributes should never be None self._name = ctypes_device.name if ctypes_device.name else '' self._vendor = ctypes_device.vendor if ctypes_device.vendor else '' self._model = ctypes_device.model if ctypes_device.model else '' self._type = ctypes_device.type if ctypes_device.type else '' self._display_name = ' '.join([self._vendor, self._model]) # Read only properties def __get_name(self): """ Get the complete SANE identifier for this device, e.g. 'lexmark:libusb:002:006'. """ return self._name name = property(__get_name) def __get_vendor(self): """Get the manufacturer of this device, e.g. 'Lexmark'.""" return self._vendor vendor = property(__get_vendor) def __get_model(self): """Get the specific model of this device, e.g. 'X1100/rev. B2'.""" return self._model model = property(__get_model) def __get_type(self): """Get the type of this device, e.g. 'flatbed scanner'.""" return self._type type = property(__get_type) def __get_display_name(self): """ Get an appropriate name to use for displaying this device to a user, e.g. 'Lexmark X1100/rev. B2'.""" return self._display_name display_name = property(__get_display_name) def __get_options(self): """Get the dictionary of options that this device has.""" return self._options options = property(__get_options) # Internal methods def _update_options(self): """ Update the list of available options for this device. As these are immutable, this should only need to be called when the Device is first instantiated. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') option_value = pointer(c_int()) status = sane_control_option( self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: raise SaneUnsupportedOperationError( 'sane_control_option reported that a value was outside the option\'s constraint.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) option_count = option_value.contents.value if self._log: self._log.debug('Device queried, %i option(s) found.', option_count) self._options.clear() i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) self._options[coption.contents.name] = Option( self, i, coption.contents, self._log) i = i + 1 # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Public methods def open(self): """ Open a new handle to this device. Must be called before any operations (including getting or setting options) are performed on this device. """ if self._handle: raise AssertionError('device handle already exists.') self._handle = SANE_Handle() status = sane_open(self.name, byref(self._handle)) # If and exception will be thrown, nullify device handle # so is_open() will return false for the device. if status != SANE_STATUS_GOOD.value: self._handle = None if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_open reported that the device was busy.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) self._update_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) def has_option(self, option_name): """Return true if option_name is available for this scanner.""" return (option_name in self.options.keys()) def scan(self, progress_callback=None): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') - + if sane_parameters.format == SANE_FRAME_GRAY.value: - pil_image = Image.frombuffer( - 'L', (scan_info.width, scan_info.height), - data_array, 'raw', 'L', 0, 1) + # Lineart + if sane_parameters.depth == 1: + pil_image = Image.frombuffer( + '1', (scan_info.width, scan_info.height), + data_array, 'raw', '1', 0, 1) + # Grayscale + elif sane_parameters.depth == 8: + pil_image = Image.frombuffer( + 'L', (scan_info.width, scan_info.height), + data_array, 'raw', 'L', 0, 1) + else: + raise AssertionError( + 'Unexpected bit depth for monochrome scan format: %i' % sane_parameters.depth) elif sane_parameters.format == SANE_FRAME_RGB.value: + # Color pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capability = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number # String attributes should never be None self._name = ctypes_option.name if ctypes_option.name else '' self._title = ctypes_option.title if ctypes_option.title else '' self._description = ctypes_option.desc if ctypes_option.desc else '' self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 else: self._constraint = None # Read only properties def __get_name(self): """ Get the short-form name of this option, e.g. 'mode'. May be an empty string, but never None. """ return self._name name = property(__get_name) def __get_title(self): """ Get the full name of this option, e.g. 'Scan mode'. May be an empty string, but never None. """ return self._title title = property(__get_title) def __get_description(self): """ Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' May be an empty string, but never None. """ return self._description description = property(__get_description) def __get_type(self): """ Get the type of this option, e.g. OPTION_TYPE_STRING. """ return self._type type = property(__get_type) def __get_unit(self): """ Get the unit of this option, e.g.OPTION_UNIT_DPI. """ return self._unit unit = property(__get_unit) def __get_constraint_type(self): """ Get the type of constraint on this option, e.g. OPTION_CONSTRAINT_RANGE. """ return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then this is a list of integers which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """value Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option( handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i.' % status, device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value else: option_value = option_value.contents.value if self._log: self._log.debug( 'Option %s queried, its current value is %s.', self._name, option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: raise TypeError( 'option set with %s, expected BooleanType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: raise TypeError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: raise ValueError( 'value for option is longer than max string size') c_value = c_char_p(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: min, max, step = self._constraint if value < min: raise ValueError('value for option is less than min.') if value > max: raise ValueError('value for option is greater than max.') if step is not None and step > 0: if value % step != 0: raise ValueError( 'value for option is not evenly divisible by step.') elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i .' % status, device=self._device) if self._log: self._log.debug('Option %s set to value %s.', self._name, value) # See SANE API 4.3.7 if info_flags.value & SANE_INFO_RELOAD_OPTIONS: raise SaneReloadOptionsError() # Catching this can not be avoided by constraint checking, as some # devices restrict option values without setting a constraint range # step. if info_flags.value & SANE_INFO_INEXACT: raise SaneInexactValueError() # TODO? if info_flags.value & SANE_INFO_RELOAD_PARAMS: pass value = property(__get_value, __set_value) # PUBLIC METHODS def is_soft_settable(self): """ Returns True if the option can be set by software. """ return self._capability & SANE_CAP_SOFT_SELECT def is_hard_settable(self): """ Returns True if the option can be set by hardware. """ return self._capability & SANE_CAP_HARD_SELECT def is_soft_gettable(self): """ Returns True if the option can be read by software. """ return self._capability & SANE_CAP_SOFT_DETECT def is_emulated(self): """ Returns True if the option is emulated by the backend driver. """ return self._capability & SANE_CAP_EMULATED # def is_automatic(self): # return self._capability & SANE_CAP_AUTOMATIC def is_active(self): """ Returns False if this device is unavailable because of the value of some other option. """ return not self._capability & SANE_CAP_INACTIVE # def is_advanced(self): # return self._capability & SANE_CAP_ADVANCED class ScanInfo(object): """ Contains the parameters and progress of a scan in progress. """ _width = 0 _height = 0 _depth = 0 _total_bytes = 0 def __init__(self, sane_parameters): """ Initialize the ScanInfo object from the sane_parameters. """ self._width = sane_parameters.pixels_per_line self._height = sane_parameters.lines self._depth = sane_parameters.depth self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines # Read only properties def __get_width(self): """Get the width of the current scan, in pixels.""" return self._width width = property(__get_width) def __get_height(self): """Get the height of the current scan, in pixels.""" return self._height height = property(__get_height) def __get_depth(self): """Get the depth of the current scan, in bits.""" return self._depth depth = property(__get_depth) def __get_total_bytes(self): """Get the total number of bytes comprising this scan.""" return self._total_bytes - total_bytes = property(__get_total_bytes) - -if __name__ == '__main__': - def progress_callback(sane_info, bytes_read): - #print float(bytes_read) / sane_info.total_bytes - pass - - import logging - log_format = FORMAT = "%(message)s" - logging.basicConfig(level=logging.DEBUG, format=log_format) - - sane = SaneMe(logging.getLogger()) - devices = sane.get_device_list() - - for dev in devices: - print dev.name - - devices[0].open() - - print devices[0].options.keys() - - try: - devices[0].options['mode'].value = 'Gray' - except SaneReloadOptionsError: - pass - - try: - devices[0].options['resolution'].value = 75 - except SaneReloadOptionsError: - pass - - try: - devices[0].options['preview'].value = False - except SaneReloadOptionsError: - pass - - devices[0].scan(progress_callback).save('out.bmp') - - devices[0].close() \ No newline at end of file + total_bytes = property(__get_total_bytes) \ No newline at end of file diff --git a/utils/graphics.py b/utils/graphics.py index 8573cb9..34d66b5 100644 --- a/utils/graphics.py +++ b/utils/graphics.py @@ -1,52 +1,52 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds utility functions for converting between GTK and PIL graphics formats. """ import gtk import Image def convert_pil_image_to_pixbuf(image): """ Utility function to quickly convert a PIL Image to a GTK Pixbuf. Adapted from Comix by Pontus Ekberg. (http://comix.sourceforge.net/) """ - if image.mode == 'L': + if image.mode != 'RGB': image = image.convert('RGB') image_string = image.tostring() pixbuf = gtk.gdk.pixbuf_new_from_data( image_string, gtk.gdk.COLORSPACE_RGB, False, 8, image.size[0], image.size[1], 3 * image.size[0]) return pixbuf def convert_pixbuf_to_pil_image(pixbuf): """ Utility function to quickly convert a GTK Pixbuf to a PIL Image. Adapted from Comix by Pontus Ekberg. (http://comix.sourceforge.net/) """ dimensions = pixbuf.get_width(), pixbuf.get_height() stride = pixbuf.get_rowstride() pixels = pixbuf.get_pixels() image = Image.frombuffer( 'RGB', dimensions, pixels, 'raw', 'RGB', stride, 1) return image \ No newline at end of file
onyxfish/nostaples
df8e5de5f63fc2e18d70febbedeeafcfe5104f04
A variety of minor (mostly cosmetic) fixes.
diff --git a/constants.py b/constants.py index 89bed8e..a835790 100644 --- a/constants.py +++ b/constants.py @@ -1,105 +1,124 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. ''' This module contains global configuration constants that are not likely to change often as well as enumeration-like state constants. ''' import os import gtk import Image from reportlab.lib.pagesizes import A0, A1, A2, A3, A4, A5, A6, \ B0, B1, B2, B3, B4, B5, B6, LETTER, LEGAL, ELEVENSEVENTEEN PAGESIZES = {'A0' : A0, 'A1' : A1, 'A2' : A2, 'A3' : A3, 'A4' : A4, 'A5' : A5, 'A6' : A6, 'B0' : B0, 'B1' : B1, 'B2' : B2, 'B3' : B3, 'B4' : B4, 'B5' : B5, 'B6' : B6, 'LETTER' : LETTER, 'LEGAL' : LEGAL, 'ELEVENSEVENTEEN' : ELEVENSEVENTEEN} DEFAULT_SHOW_TOOLBAR = True DEFAULT_SHOW_STATUSBAR = True DEFAULT_SHOW_THUMBNAILS = True DEFAULT_SHOW_ADJUSTMENTS = False DEFAULT_ROTATE_ALL_PAGES = False DEFAULT_ACTIVE_SCANNER = '' DEFAULT_SCAN_MODE = 'Color' DEFAULT_SCAN_RESOLUTION = '75' DEFAULT_SAVE_PATH = '' DEFAULT_AUTHOR = os.getenv('LOGNAME') DEFAULT_SAVED_KEYWORDS = [] DEFAULT_PREVIEW_MODE = 'Bilinear (Default)' DEFAULT_THUMBNAIL_SIZE = 128 DEFAULT_SHOW_DOCUMENT_METADATA = True DEFAULT_BLACKLISTED_SCANNERS = [] +DEFAULT_TOOLBAR_STYLE = 'System Default' THUMBNAILS_SCALING_MODE = Image.ANTIALIAS MAX_VALID_OPTION_VALUES = 11 SCAN_CANCELLED = -1 SCAN_FAILURE = 0 SCAN_SUCCESS = 1 RESPONSE_BLACKLIST_DEVICE = 1 GCONF_DIRECTORY = '/apps/nostaples' GCONF_TUPLE_SEPARATOR = '|' GCONF_LIST_SEPARATOR = '^' # TODO: rename to CONFIG_DIRECTORY APP_DIRECTORY = os.path.expanduser('~/.nostaples') LOGGING_CONFIG = os.path.join(os.path.dirname(__file__), 'logging.config') GUI_DIRECTORY = os.path.join(os.path.dirname(__file__), 'gui') PREVIEW_MODES = \ { 'Nearest (Fastest)': gtk.gdk.INTERP_NEAREST, 'Tiles': gtk.gdk.INTERP_TILES, 'Bilinear (Default)': gtk.gdk.INTERP_BILINEAR, 'Antialias (Smoothest)': gtk.gdk.INTERP_HYPER } PREVIEW_MODES_LIST = \ [ 'Nearest (Fastest)', 'Tiles', 'Bilinear (Default)', 'Antialias (Smoothest)' ] THUMBNAIL_SIZE_LIST = \ [ 32, 64, 128, 256 +] + +TOOLBAR_STYLES = \ +{ + 'System Default': None, + 'Icons Only': gtk.TOOLBAR_ICONS, + 'Text Only': gtk.TOOLBAR_TEXT, + 'Icons and Text (Stacked)': gtk.TOOLBAR_BOTH, + 'Icons and Text (Side by side)': gtk.TOOLBAR_BOTH_HORIZ +} + +TOOLBAR_STYLES_LIST = \ +[ + 'System Default', + 'Icons Only', + 'Text Only', + 'Icons and Text (Stacked)', + 'Icons and Text (Side by side)' ] \ No newline at end of file diff --git a/controllers/main.py b/controllers/main.py index ffc02df..fd71a3c 100644 --- a/controllers/main.py +++ b/controllers/main.py @@ -1,769 +1,782 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{MainController}, which manages interaction between the L{MainModel} and L{MainView}. """ import commands import logging import os import re import threading import gobject import gtk from gtkmvc.controller import Controller from nostaples.models.page import PageModel import nostaples.sane as saneme from nostaples.utils.scanning import * class MainController(Controller): """ Manages interaction between the L{MainModel} and L{MainView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the MainController, as well as necessary sub-controllers and services. """ self.application = application Controller.__init__(self, application.get_main_model()) application.get_document_model().register_observer(self) + application.get_preferences_model().register_observer(self) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ self.adapt('show_toolbar', 'show_toolbar_menu_item') self.adapt('show_statusbar', 'show_statusbar_menu_item') self.adapt('show_thumbnails', 'show_thumbnails_menu_item') self.adapt('show_adjustments', 'show_adjustments_menu_item') self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS # Menu Items def on_scan_window_destroy(self, window): """Exits the application.""" self.quit() def on_scan_menu_item_activate(self, menu_item): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_menu_item_activate(self, menu_item): """Refresh the list of connected scanners from SANE.""" self._update_available_scanners() def on_save_as_menu_item_activate(self, menu_item): """Saves the current document to a file.""" self.application.show_save_dialog() def on_delete_menu_item_activate(self, menu_item): self.application.get_document_controller().delete_selected() def on_preferences_menu_item_activate(self, menu_item): """Creates and displays a preferences dialog.""" self.application.show_preferences_dialog() def on_quit_menu_item_activate(self, menu_item): """Exits the application.""" self.quit() def on_zoom_in_menu_item_activate(self, menu_item): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_menu_item_activate(self, menu_item): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_menu_item_activate(self, menu_item): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_menu_item_activate(self, menu_item): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_available_scanner_menu_item_toggled(self, menu_item): """ Set the active scanner. TODO: Need a second scanner to properly test this... """ main_model = self.application.get_main_model() if menu_item.get_active(): for scanner in main_model.available_scanners: if scanner.display_name == menu_item.get_children()[0].get_text(): main_model.active_scanner = scanner return def on_valid_mode_menu_item_toggled(self, menu_item): """Sets the active scan mode.""" if menu_item.get_active(): self.application.get_main_model().active_mode = \ menu_item.get_children()[0].get_text() def on_valid_resolution_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_resolution = \ menu_item.get_children()[0].get_text() def on_go_first_menu_item_activate(self, menu_item): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_menu_item_activate(self, menu_item): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_menu_item_activate(self, menu_item): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_menu_item_activate(self, menu_item): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() def on_contents_menu_item_clicked(self, menu_item): """TODO""" pass def on_about_menu_item_activate(self, menu_item): """Show the about dialog.""" self.application.show_about_dialog() # Toolbar Buttons def on_scan_button_clicked(self, button): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_button_clicked(self, button): self._update_available_scanners() def on_save_as_button_clicked(self, button): """Saves the current document to a file.""" self.application.show_save_dialog() def on_zoom_in_button_clicked(self, button): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_button_clicked(self, button): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_button_clicked(self, button): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_button_clicked(self, button): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_go_first_button_clicked(self, button): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_button_clicked(self, button): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_button_clicked(self, button): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_button_clicked(self, button): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() # Progress Window INTERFACE CALLBACKS def on_progress_window_delete_event(self, window, event): """ Emulate clicking of the cancel/close button and then hide the window. """ main_view = self.application.get_main_view() self.on_scan_cancel_button_clicked(None) main_view['progress_window'].hide() return True def on_scan_cancel_button_clicked(self, button): """ Cancel the current scan or, if the scan is finished, close the progress window. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress: assert self.cancel_event self.cancel_event.set() else: main_view['progress_window'].hide() def on_scan_again_button_clicked(self, button): """Initiate a new scan from the progress window.""" self._scan() def on_quick_save_button_clicked(self, button): """ Show the save dialog. If the user completes a save then disable the quick save button until another page is scanned. """ main_view = self.application.get_main_view() document_model = self.application.get_document_model() self.application.show_save_dialog() if document_model.count == 0: main_view['quick_save_button'].set_sensitive(False) # MainModel PROPERTY CALLBACKS def property_show_toolbar_value_change(self, model, old_value, new_value): """Update the visibility of the toolbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_toolbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['main_toolbar'].show() else: main_view['main_toolbar'].hide() def property_show_statusbar_value_change(self, model, old_value, new_value): """Update the visibility of the statusbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_statusbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['status_view_docking_viewport'].show() else: main_view['status_view_docking_viewport'].hide() def property_show_thumbnails_value_change(self, model, old_value, new_value): """Update the visibility of the thumbnails.""" main_view = self.application.get_main_view() menu_item = main_view['show_thumbnails_menu_item'] menu_item.set_active(new_value) self.application.get_document_controller().toggle_thumbnails_visible(new_value) def property_show_adjustments_value_change(self, model, old_value, new_value): """Update the visibility of the adjustments controls.""" document_controller = self.application.get_document_controller() main_view = self.application.get_main_view() menu_item = main_view['show_adjustments_menu_item'] menu_item.set_active(new_value) document_controller.toggle_adjustments_visible(new_value) def property_active_scanner_value_change(self, model, old_value, new_value): """ Update the menu and valid scanner options to match the new device. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() if new_value == None: return for menu_item in main_view['scanner_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value.display_name: menu_item.set_active(True) break def property_active_mode_value_change(self, model, old_value, new_value): """Select the active mode from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_mode_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_resolution_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_resolution_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_available_scanners_value_change(self, model, old_value, new_value): """ Update the menu of available scanners. """ main_view = self.application.get_main_view() self._clear_available_scanners_sub_menu() # Generate the new menu if len(new_value) == 0: menu_item = gtk.MenuItem('No Scanners Connected') menu_item.set_sensitive(False) main_view['scanner_sub_menu'].append(menu_item) else: first_item = None for i in range(len(new_value)): # The first menu item defines the group if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i].display_name) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i].display_name) main_view['scanner_sub_menu'].append(menu_item) main_view['scanner_sub_menu'].show_all() def property_valid_modes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan modes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_modes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Modes") menu_item.set_sensitive(False) main_view['scan_mode_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled) main_view['scan_mode_sub_menu'].append(menu_item) main_view['scan_mode_sub_menu'].show_all() def property_valid_resolutions_value_change(self, model, old_value, new_value): """ Updates the list of valid scan resolutions for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_resolutions_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Resolutions") menu_item.set_sensitive(False) main_view['scan_resolution_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled) main_view['scan_resolution_sub_menu'].append(menu_item) main_view['scan_resolution_sub_menu'].show_all() def property_scan_in_progress_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() def property_updating_available_scanners_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() # DocumentModel PROPERTY CALLBACKS def property_count_value_change(self, model, old_value, new_value): """Toggle available controls.""" self._toggle_document_controls() + + # PreferencesModel PROPERTY CALLBACKS + + def property_toolbar_style_value_change(self, model, old_value, new_value): + """Toggle available controls.""" + main_view = self.application.get_main_view() + + if new_value == 'System Default': + # TODO - reset style to system default + pass + else: + main_view['main_toolbar'].set_style(constants.TOOLBAR_STYLES[new_value]) # THREAD CALLBACKS def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned): main_view = self.application.get_main_view() short_bytes_scanned = float(bytes_scanned) / 1000 short_total_bytes = float(scan_info.total_bytes) / 1000 main_view['scan_progressbar'].set_fraction( float(bytes_scanned) / scan_info.total_bytes) main_view['scan_progressbar'].set_text( 'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes)) # TODO: multi page scans main_view['progress_secondary_label'].set_markup( '<i>Scanning page.</i>') def on_scan_succeeded(self, scanning_thread, pil_image): """ Append the new page to the current document. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['scan_progressbar'].set_fraction(1) main_view['scan_progressbar'].set_text('Scan complete') main_view['progress_secondary_label'].set_markup( '<i>Adding page to document.</i>') gtk.gdk.flush() new_page = PageModel(self.application, pil_image, int(main_model.active_resolution)) self.application.get_document_model().append(new_page) main_view['progress_secondary_label'].set_markup( '<i>Page added.</i>') main_view['scan_again_button'].set_sensitive(True) main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_failed(self, scanning_thread, reason): """ Set that scan is complete. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['progress_secondary_label'].set_markup( '<i>%s</i>' % reason) main_view['scan_again_button'].set_sensitive(True) if self.application.get_document_model().count > 0: main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_aborted(self, scanning_thread, exc_info): """ Change display to indicate that scanning failed and convey the to the user the reason why the thread aborted. If the failure was from a SANE exception then give the user the option to blacklist the device. If not, then reraise the error and let the sys.excepthook deal with it. """ self.on_scan_failed(scanning_thread, 'An error occurred.') if isinstance(exc_info[1], saneme.SaneError): self.run_device_exception_dialog(exc_info) else: raise exc_info[0], exc_info[1], exc_info[2] def on_update_available_scanners_thread_finished(self, update_thread, scanner_list): """Set the new list of available scanners.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() status_controller = self.application.get_status_controller() # Remove blacklisted scanners scanner_list = \ [scanner for scanner in scanner_list if not \ scanner.display_name in preferences_model.blacklisted_scanners] # Remove scanners that do not support necessary options or fail to # open entirely preferences_model.unavailable_scanners = [] def is_supported_option(option): """Verify an option supports necessary capabilities to be useful.""" return option.is_active() and \ option.is_soft_gettable() and \ option.is_soft_settable() for scanner in scanner_list: try: scanner.open() if not scanner.has_option('mode') or \ not is_supported_option(scanner.options['mode']) or \ not scanner.has_option('resolution') or \ not is_supported_option(scanner.options['resolution']): preferences_model.unavailable_scanners.append(scanner.display_name) scanner_list.remove(scanner) scanner.close() except saneme.SaneError: preferences_model.unavailable_scanners.append(scanner.display_name) scanner_list.remove(scanner) main_model.available_scanners = scanner_list main_model.updating_available_scanners = False def on_update_available_scanners_thread_aborted(self, update_thread, exc_info): """ Change the display to indicate that no scanners are available and reraise the exception so that it can be caught by the sys.excepthook. There is no reason to handle these cases with a special dialog, if the application failed to even enumerate the available devices then no other action will be possible. This should be fantastically rare. """ self.on_update_available_scanners_thread_finished(update_thread, []) raise exc_info[0], exc_info[1], exc_info[2] # PUBLIC METHODS def quit(self): """Exits the application.""" self.log.debug('Quit.') gtk.main_quit() def run_device_exception_dialog(self, exc_info): """ Display an error dialog that provides the user with the option of blacklisting the device which caused the error. TODO: Move into MainView. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() preferences_model = self.application.get_preferences_model() response = main_view.run_device_exception_dialog(exc_info) if response == constants.RESPONSE_BLACKLIST_DEVICE: temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(exc_info[1].device.display_name) temp_blacklist.sort() preferences_model.blacklisted_scanners = temp_blacklist # PRIVATE METHODS def _clear_available_scanners_sub_menu(self): """Clear the menu of available scanners.""" main_view = self.application.get_main_view() for child in main_view['scanner_sub_menu'].get_children(): main_view['scanner_sub_menu'].remove(child) def _clear_scan_modes_sub_menu(self): """Clear the menu of valid scan modes.""" main_view = self.application.get_main_view() for child in main_view['scan_mode_sub_menu'].get_children(): main_view['scan_mode_sub_menu'].remove(child) def _clear_scan_resolutions_sub_menu(self): """Clear the menu of valid scan resolutions.""" main_view = self.application.get_main_view() for child in main_view['scan_resolution_sub_menu'].get_children(): main_view['scan_resolution_sub_menu'].remove(child) def _toggle_scan_controls(self): """Toggle whether or not the scan controls or accessible.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_scan_controls_sensitive(False) main_view.set_refresh_scanner_controls_sensitive(False) else: if main_model.active_scanner != None: main_view.set_scan_controls_sensitive(True) main_view.set_refresh_scanner_controls_sensitive(True) def _toggle_document_controls(self): """ Toggle available document controls based on the current scanner status and the number of scanned pages. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() # Disable all controls when the scanner is in use if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: count = self.application.get_document_model().count # Disable all controls if no pages are scanned if count == 0: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: # Enable most controls if any pages scanned main_view.set_file_controls_sensitive(True) main_view.set_delete_controls_sensitive(True) main_view.set_zoom_controls_sensitive(True) main_view.set_adjustment_controls_sensitive(True) # Only enable navigation if more than one page scanned if count > 1: main_view.set_navigation_controls_sensitive(True) else: main_view.set_navigation_controls_sensitive(False) def _update_status(self): """ Update the text of the statusbar based on the current state of the application. """ main_model = self.application.get_main_model() status_controller = self.application.get_status_controller() status_controller.pop(self.status_context) if main_model.scan_in_progress: status_controller.push(self.status_context, 'Scanning...') elif main_model.updating_available_scanners: status_controller.push(self.status_context, 'Querying hardware...') else: if main_model.active_scanner: status_controller.push(self.status_context, 'Ready with %s.' % main_model.active_scanner.display_name) else: status_controller.push(self.status_context, 'No scanner available.') def _scan(self): """Begin a scan.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() main_model.scan_in_progress = True scanning_thread = ScanningThread(main_model.active_scanner) scanning_thread.connect("progress", self.on_scan_progress) scanning_thread.connect("succeeded", self.on_scan_succeeded) scanning_thread.connect("failed", self.on_scan_failed) scanning_thread.connect("aborted", self.on_scan_aborted) self.cancel_event = scanning_thread.cancel_event main_view['progress_primary_label'].set_markup( '<big><b>%s</b></big>' % main_model.active_scanner.display_name) main_view['scan_progressbar'].set_fraction(0) main_view['scan_progressbar'].set_text('Waiting for data') main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>') mode = main_model.active_mode if main_model.active_mode else 'Not set' main_view['progress_mode_label'].set_markup(mode) dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set' main_view['progress_resolution_label'].set_markup(dpi) main_view['scan_again_button'].set_sensitive(False) main_view['quick_save_button'].set_sensitive(False) main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL) main_view['progress_window'].show_all() scanning_thread.start() def _update_available_scanners(self): """ Start a new update thread to query for available scanners. """ sane = self.application.get_sane() main_model = self.application.get_main_model() main_model.updating_available_scanners = True update_thread = UpdateAvailableScannersThread(sane) update_thread.connect("finished", self.on_update_available_scanners_thread_finished) update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted) update_thread.start() \ No newline at end of file diff --git a/controllers/preferences.py b/controllers/preferences.py index 91eb89a..2cfb931 100644 --- a/controllers/preferences.py +++ b/controllers/preferences.py @@ -1,218 +1,274 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{PreferencesController}, which manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ import logging import gtk from gtkmvc.controller import Controller from nostaples import constants from nostaples.utils.gui import read_combobox class PreferencesController(Controller): """ Manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the PreferencesController. """ self.application = application Controller.__init__(self, application.get_preferences_model()) application.get_main_model().register_observer(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ pass # USER INTERFACE CALLBACKS def on_preview_mode_combobox_changed(self, combobox): """Update the preview mode in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.preview_mode = \ read_combobox(preferences_view['preview_mode_combobox']) def on_thumbnail_size_combobox_changed(self, combobox): """Update the thumbnail size in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.thumbnail_size = \ int(read_combobox(preferences_view['thumbnail_size_combobox'])) + def on_toolbar_style_combobox_changed(self, combobox): + """Update the toolbar style in the PreferencesModel.""" + preferences_model = self.application.get_preferences_model() + preferences_view = self.application.get_preferences_view() + + preferences_model.toolbar_style = \ + read_combobox(preferences_view['toolbar_style_combobox']) + def on_remove_from_blacklist_button_clicked(self, button): """ Remove the currently selected blacklist device from the list. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['blacklist_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.remove(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_add_to_blacklist_button_clicked(self, button): """ Move the currently selected available scanner to the blacklist. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['available_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_remove_from_keywords_button_clicked(self, button): """ Remove the currently selected keyword from the list. """ preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['keywords_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_keywords = list(preferences_model.saved_keywords) temp_keywords.remove(selection_text) preferences_model.saved_keywords = temp_keywords def on_preferences_dialog_response(self, dialog, response): """Close the preferences dialog.""" preferences_view = self.application.get_preferences_view() preferences_view['preferences_dialog'].hide() # PROPERTY CALLBACKS + def property_preview_mode_value_change(self, model, old_value, new_value): + # TODO - set the combobox (in case the change came form state) + pass + + def property_thumbnail_size_value_change(self, model, old_value, new_value): + # TODO - set the combobox (in case the change came form state) + pass + + def property_toolbar_style_value_change(self, model, old_value, new_value): + # TODO - set the combobox (in case the change came form state) + pass + def property_unavailable_scanners_value_change(self, model, old_value, new_value): """Update unavailable scanners liststore.""" preferences_view = self.application.get_preferences_view() unavailable_liststore = preferences_view['unavailable_tree_view'].get_model() unavailable_liststore.clear() for unavailable_item in new_value: unavailable_liststore.append([unavailable_item]) def property_blacklisted_scanners_value_change(self, model, old_value, new_value): """Update blacklisted scanners liststore.""" preferences_view = self.application.get_preferences_view() blacklist_liststore = preferences_view['blacklist_tree_view'].get_model() blacklist_liststore.clear() for blacklist_item in new_value: blacklist_liststore.append([blacklist_item]) + + self._toggle_device_controls() def property_available_scanners_value_change(self, model, old_value, new_value): """Update available scanners liststore.""" preferences_view = self.application.get_preferences_view() available_liststore = preferences_view['available_tree_view'].get_model() available_liststore.clear() for available_item in new_value: available_liststore.append([available_item.display_name]) + self._toggle_device_controls() + + def property_updating_available_scanners_value_change(self, model, old_value, new_value): + """ + Disable device management controls while devices are being updated. + """ + self._toggle_device_controls() + def property_saved_keywords_value_change(self, model, old_value, new_value): """Update keywords liststore.""" preferences_view = self.application.get_preferences_view() keywords_liststore = preferences_view['keywords_tree_view'].get_model() keywords_liststore.clear() for keyword in new_value: keywords_liststore.append([keyword]) # PUBLIC METHODS def run(self): """Run the preferences dialog.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() # Force property updates when dialog is run: this handles the case # where the PreferencesController has not been created until now # so it has not been receiving property notifications. self.property_unavailable_scanners_value_change( preferences_model, None, preferences_model.unavailable_scanners) self.property_blacklisted_scanners_value_change( preferences_model, None, preferences_model.blacklisted_scanners) self.property_available_scanners_value_change( main_model, None, main_model.available_scanners) self.property_saved_keywords_value_change( preferences_model, None, preferences_model.saved_keywords) - preferences_view.run() \ No newline at end of file + preferences_view.run() + + # PRIVATE METHODS + + def _toggle_device_controls(self): + """ + Toggle the availability of the scanner management controls based on + the state of the application. + """ + main_model = self.application.get_main_model() + preferences_model = self.application.get_preferences_model() + preferences_view = self.application.get_preferences_view() + + if main_model.updating_available_scanners: + preferences_view['remove_from_blacklist_button'].set_sensitive(False) + preferences_view['add_to_blacklist_button'].set_sensitive(False) + else: + if len(preferences_model.blacklisted_scanners) > 0: + preferences_view['remove_from_blacklist_button'].set_sensitive(True) + else: + preferences_view['remove_from_blacklist_button'].set_sensitive(False) + + if len(main_model.available_scanners) > 0: + preferences_view['add_to_blacklist_button'].set_sensitive(True) + else: + preferences_view['add_to_blacklist_button'].set_sensitive(False) + \ No newline at end of file diff --git a/gui/preferences_dialog.glade b/gui/preferences_dialog.glade index 8f2f9a3..58c44aa 100644 --- a/gui/preferences_dialog.glade +++ b/gui/preferences_dialog.glade @@ -1,350 +1,371 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> -<!--Generated with glade3 3.4.5 on Fri Feb 27 20:10:04 2009 --> +<!--Generated with glade3 3.4.5 on Sun Mar 8 11:55:15 2009 --> <glade-interface> <widget class="GtkDialog" id="preferences_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">NoStaples Preferences</property> <property name="resizable">False</property> <property name="modal">True</property> <property name="window_position">GTK_WIN_POS_CENTER_ON_PARENT</property> <property name="destroy_with_parent">True</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property> <property name="skip_taskbar_hint">True</property> <property name="skip_pager_hint">True</property> <property name="has_separator">False</property> <signal name="response" handler="on_preferences_dialog_response"/> <child internal-child="vbox"> <widget class="GtkVBox" id="dialog-vbox5"> <property name="visible">True</property> <property name="spacing">12</property> <signal name="add" handler="on_preferences_dialog_close"/> <child> <widget class="GtkNotebook" id="notebook1"> <property name="visible">True</property> <property name="can_focus">True</property> <child> <widget class="GtkAlignment" id="alignment6"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> - <widget class="GtkVBox" id="vbox3"> + <widget class="GtkTable" id="table1"> <property name="visible">True</property> - <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> - <property name="spacing">6</property> + <property name="n_rows">3</property> + <property name="n_columns">2</property> + <property name="column_spacing">12</property> <child> - <widget class="GtkHBox" id="hbox2"> + <widget class="GtkComboBox" id="toolbar_style_combobox"> <property name="visible">True</property> - <property name="spacing">12</property> - <child> - <widget class="GtkLabel" id="label4"> - <property name="visible">True</property> - <property name="label" translatable="yes">Preview Scaling Mode:</property> - </widget> - <packing> - <property name="expand">False</property> - </packing> - </child> - <child> - <widget class="GtkComboBox" id="preview_mode_combobox"> - <property name="visible">True</property> - <property name="items" translatable="yes"></property> - </widget> - <packing> - <property name="position">1</property> - </packing> - </child> </widget> <packing> - <property name="expand">False</property> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + <property name="top_attach">2</property> + <property name="bottom_attach">3</property> + <property name="y_options"></property> </packing> </child> <child> - <widget class="GtkHBox" id="hbox1"> + <widget class="GtkLabel" id="label10"> <property name="visible">True</property> - <property name="spacing">12</property> - <child> - <widget class="GtkLabel" id="label5"> - <property name="visible">True</property> - <property name="label" translatable="yes">Thumbnail Size:</property> - </widget> - <packing> - <property name="expand">False</property> - </packing> - </child> - <child> - <widget class="GtkComboBox" id="thumbnail_size_combobox"> - <property name="visible">True</property> - </widget> - <packing> - <property name="position">1</property> - </packing> - </child> + <property name="xalign">0</property> + <property name="label" translatable="yes">Toolbar Style:</property> </widget> <packing> - <property name="expand">False</property> - <property name="position">1</property> + <property name="top_attach">2</property> + <property name="bottom_attach">3</property> + <property name="x_options">GTK_FILL</property> + <property name="y_options"></property> + </packing> + </child> + <child> + <widget class="GtkLabel" id="label4"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="label" translatable="yes">Preview Scaling Mode:</property> + </widget> + <packing> + <property name="x_options">GTK_FILL</property> + <property name="y_options"></property> + </packing> + </child> + <child> + <widget class="GtkLabel" id="label5"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="label" translatable="yes">Thumbnail Size:</property> + </widget> + <packing> + <property name="top_attach">1</property> + <property name="bottom_attach">2</property> + <property name="x_options">GTK_FILL</property> + <property name="y_options"></property> + </packing> + </child> + <child> + <widget class="GtkComboBox" id="preview_mode_combobox"> + <property name="visible">True</property> + <property name="items" translatable="yes"></property> + </widget> + <packing> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + <property name="y_options"></property> + </packing> + </child> + <child> + <widget class="GtkComboBox" id="thumbnail_size_combobox"> + <property name="visible">True</property> + </widget> + <packing> + <property name="left_attach">1</property> + <property name="right_attach">2</property> + <property name="top_attach">1</property> + <property name="bottom_attach">2</property> + <property name="y_options"></property> </packing> </child> </widget> </child> </widget> </child> <child> <widget class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">View</property> </widget> <packing> <property name="type">tab</property> <property name="tab_fill">False</property> </packing> </child> <child> <widget class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="label8"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Unsupported or unavailable devices:</property> <property name="wrap_mode">PANGO_WRAP_WORD_CHAR</property> </widget> </child> <child> <widget class="GtkScrolledWindow" id="unavailable_scrolled_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="shadow_type">GTK_SHADOW_IN</property> <child> <placeholder/> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkLabel" id="label7"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Blacklisted devices:</property> <property name="wrap_mode">PANGO_WRAP_WORD_CHAR</property> </widget> <packing> <property name="position">2</property> </packing> </child> <child> <widget class="GtkScrolledWindow" id="blacklist_scrolled_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="shadow_type">GTK_SHADOW_IN</property> <child> <placeholder/> </child> </widget> <packing> <property name="position">3</property> </packing> </child> <child> <widget class="GtkButton" id="remove_from_blacklist_button"> <property name="visible">True</property> + <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="label" translatable="yes">Remove from Blacklist</property> <property name="response_id">0</property> <signal name="clicked" handler="on_remove_from_blacklist_button_clicked"/> </widget> <packing> <property name="position">4</property> </packing> </child> <child> <widget class="GtkLabel" id="label9"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Available devices:</property> <property name="wrap_mode">PANGO_WRAP_WORD_CHAR</property> </widget> <packing> <property name="position">5</property> </packing> </child> <child> <widget class="GtkScrolledWindow" id="available_scrolled_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="shadow_type">GTK_SHADOW_IN</property> <child> <placeholder/> </child> </widget> <packing> <property name="position">6</property> </packing> </child> <child> <widget class="GtkButton" id="add_to_blacklist_button"> <property name="visible">True</property> + <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="label" translatable="yes">Add to Blacklist</property> <property name="response_id">0</property> <signal name="clicked" handler="on_add_to_blacklist_button_clicked"/> </widget> <packing> <property name="position">7</property> </packing> </child> </widget> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkLabel" id="label3"> <property name="visible">True</property> <property name="label" translatable="yes">Devices</property> </widget> <packing> <property name="type">tab</property> <property name="position">1</property> <property name="tab_fill">False</property> </packing> </child> <child> <widget class="GtkAlignment" id="alignment2"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="label6"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Keywords for autocompletion:</property> <property name="use_markup">True</property> <property name="wrap">True</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkScrolledWindow" id="keywords_scrolled_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="shadow_type">GTK_SHADOW_IN</property> <child> <placeholder/> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkAlignment" id="alignment3"> <property name="visible">True</property> <child> <widget class="GtkButton" id="remove_from_keywords_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="label" translatable="yes">Remove</property> <property name="response_id">0</property> <signal name="clicked" handler="on_remove_from_keywords_button_clicked"/> </widget> </child> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> </widget> </child> </widget> <packing> <property name="position">2</property> </packing> </child> <child> <widget class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">Documents</property> </widget> <packing> <property name="type">tab</property> <property name="position">2</property> <property name="tab_fill">False</property> </packing> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <widget class="GtkHButtonBox" id="dialog-action_area5"> <property name="visible">True</property> <property name="layout_style">GTK_BUTTONBOX_END</property> <child> <placeholder/> </child> <child> <widget class="GtkButton" id="preferences_close_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">gtk-close</property> <property name="use_stock">True</property> <property name="response_id">0</property> <signal name="clicked" handler="on_preferences_close_button_clicked"/> </widget> <packing> <property name="expand">False</property> <property name="pack_type">GTK_PACK_END</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="expand">False</property> <property name="pack_type">GTK_PACK_END</property> </packing> </child> </widget> </child> </widget> </glade-interface> diff --git a/gui/scan_window.glade b/gui/scan_window.glade index ea9aa3a..b76303e 100644 --- a/gui/scan_window.glade +++ b/gui/scan_window.glade @@ -1,913 +1,925 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> -<!--Generated with glade3 3.4.5 on Mon Feb 16 21:36:10 2009 --> +<!--Generated with glade3 3.4.5 on Sun Mar 8 12:20:09 2009 --> <glade-interface> <widget class="GtkWindow" id="progress_window"> <property name="width_request">400</property> <property name="height_request">200</property> <property name="title" translatable="yes">Scan in progress...</property> <property name="resizable">False</property> <property name="modal">True</property> <property name="window_position">GTK_WIN_POS_CENTER</property> <property name="destroy_with_parent">True</property> <property name="icon_name">scanner</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property> <property name="skip_taskbar_hint">True</property> <property name="skip_pager_hint">True</property> <property name="transient_for">scan_window</property> <signal name="delete_event" handler="on_progress_window_delete_event"/> <child> <widget class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkLabel" id="progress_primary_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">&lt;big&gt;&lt;b&gt;Scan in progress...&lt;/b&gt;&lt;/big&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <widget class="GtkVBox" id="vbox4"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkVBox" id="vbox3"> <property name="visible">True</property> <child> <widget class="GtkHBox" id="hbox2"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="static_mode_label"> <property name="width_request">90</property> <property name="visible">True</property> <property name="xalign">1</property> <property name="label" translatable="yes">&lt;b&gt;Mode:&lt;/b&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkLabel" id="progress_mode_label"> <property name="visible">True</property> <property name="label" translatable="yes">Color</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </widget> </child> <child> <widget class="GtkHBox" id="hbox5"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="static_page_size_label"> <property name="width_request">90</property> <property name="visible">True</property> <property name="xalign">1</property> <property name="label" translatable="yes">&lt;b&gt;Page Size:&lt;/b&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkLabel" id="progress_page_size_label"> <property name="visible">True</property> <property name="label" translatable="yes">Letter (TODO)</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkHBox" id="hbox3"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="static_resolution_label"> <property name="width_request">90</property> <property name="visible">True</property> <property name="xalign">1</property> <property name="label" translatable="yes">&lt;b&gt;Resolution:&lt;/b&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkLabel" id="progress_resolution_label"> <property name="visible">True</property> <property name="label" translatable="yes">150 DPI</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="position">2</property> </packing> </child> </widget> </child> <child> <widget class="GtkVBox" id="vbox4"> <property name="visible">True</property> <child> <widget class="GtkProgressBar" id="scan_progressbar"> <property name="visible">True</property> <property name="show_text">True</property> <property name="text" translatable="yes">X of Y bytes receieved.</property> </widget> <packing> <property name="fill">False</property> </packing> </child> <child> <widget class="GtkLabel" id="progress_secondary_label"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">&lt;i&gt;Scanning page 1 of Z.&lt;/i&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </widget> </child> <child> <widget class="GtkHBox" id="hbox1"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkButton" id="scan_cancel_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="label" translatable="yes">gtk-cancel</property> <property name="use_stock">True</property> <property name="response_id">0</property> <signal name="clicked" handler="on_scan_cancel_button_clicked"/> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="pack_type">GTK_PACK_END</property> <property name="position">2</property> </packing> </child> <child> <widget class="GtkButton" id="scan_again_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="response_id">0</property> <signal name="clicked" handler="on_scan_again_button_clicked"/> <child> <widget class="GtkHBox" id="hbox4"> <property name="visible">True</property> <child> <widget class="GtkImage" id="image1"> <property name="visible">True</property> <property name="icon_name">scanner</property> </widget> </child> <child> <widget class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">Scan Again</property> <property name="use_markup">True</property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> </child> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="pack_type">GTK_PACK_END</property> <property name="position">1</property> </packing> </child> <child> <widget class="GtkButton" id="quick_save_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="response_id">0</property> <signal name="clicked" handler="on_quick_save_button_clicked"/> <child> <widget class="GtkHBox" id="hbox6"> <property name="visible">True</property> <child> <widget class="GtkImage" id="image2"> <property name="visible">True</property> <property name="stock">gtk-save-as</property> </widget> </child> <child> <widget class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">Quick Save</property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> </child> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="pack_type">GTK_PACK_END</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="fill">False</property> <property name="position">1</property> </packing> </child> </widget> </child> </widget> </child> </widget> <widget class="GtkWindow" id="scan_window"> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="title" translatable="yes">NoStaples</property> <property name="window_position">GTK_WIN_POS_CENTER</property> <property name="default_width">600</property> <property name="default_height">400</property> <signal name="destroy" handler="on_scan_window_destroy"/> <signal name="size_allocate" handler="on_scan_window_size_allocate"/> <child> <widget class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <child> <widget class="GtkMenuBar" id="menubar1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <child> <widget class="GtkMenuItem" id="menuitem1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">_File</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <child> <widget class="GtkImageMenuItem" id="scan_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">S_can</property> <property name="use_underline">True</property> <signal name="activate" handler="on_scan_menu_item_activate"/> <child internal-child="image"> <widget class="GtkImage" id="menu-item-image2"> <property name="visible">True</property> <property name="icon_name">scanner</property> </widget> </child> </widget> </child> <child> <widget class="GtkImageMenuItem" id="refresh_available_scanners_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">Refresh Available Scanners</property> <property name="use_underline">True</property> <signal name="activate" handler="on_refresh_available_scanners_menu_item_activate"/> <child internal-child="image"> <widget class="GtkImage" id="menu-item-image4"> <property name="stock">gtk-refresh</property> </widget> </child> </widget> </child> <child> <widget class="GtkSeparatorMenuItem" id="separatormenuitem7"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> </widget> </child> <child> <widget class="GtkImageMenuItem" id="save_as_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">Save _As...</property> <property name="use_underline">True</property> <signal name="activate" handler="on_save_as_menu_item_activate"/> <accelerator key="S" modifiers="GDK_CONTROL_MASK" signal="activate"/> <child internal-child="image"> <widget class="GtkImage" id="menu-item-image1"> <property name="stock">gtk-save-as</property> </widget> </child> </widget> </child> <child> <widget class="GtkSeparatorMenuItem" id="separatormenuitem1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> </widget> </child> <child> <widget class="GtkImageMenuItem" id="quit_menu_item"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">gtk-quit</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_quit_menu_item_activate"/> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="menuitem2"> <property name="visible">True</property> <property name="label" translatable="yes">_Edit</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu4"> <property name="visible">True</property> <child> <widget class="GtkImageMenuItem" id="delete_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-delete</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_delete_menu_item_activate"/> <accelerator key="Delete" modifiers="" signal="activate"/> </widget> </child> <child> <widget class="GtkSeparatorMenuItem" id="separatormenuitem4"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> </widget> </child> <child> <widget class="GtkImageMenuItem" id="preferences_menu_item"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">gtk-preferences</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_preferences_menu_item_activate"/> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="view_menu"> <property name="visible">True</property> <property name="label" translatable="yes">_View</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu2"> <property name="visible">True</property> <child> <widget class="GtkCheckMenuItem" id="show_toolbar_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Toolbar</property> <property name="use_underline">True</property> <property name="active">True</property> <signal name="toggled" handler="on_show_toolbar_menu_item_toggled"/> </widget> </child> <child> <widget class="GtkCheckMenuItem" id="show_statusbar_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Statusbar</property> <property name="use_underline">True</property> <property name="active">True</property> <signal name="toggled" handler="on_show_statusbar_menu_item_toggled"/> </widget> </child> <child> <widget class="GtkCheckMenuItem" id="show_thumbnails_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">Thumb_nails</property> <property name="use_underline">True</property> <property name="active">True</property> <signal name="toggled" handler="on_show_thumbnails_menu_item_toggled"/> </widget> </child> <child> <widget class="GtkCheckMenuItem" id="show_adjustments_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Adjustments</property> <property name="use_underline">True</property> <signal name="toggled" handler="on_show_adjustments_menu_item_toggled"/> </widget> </child> <child> <widget class="GtkSeparatorMenuItem" id="separatormenuitem5"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> </widget> </child> <child> <widget class="GtkImageMenuItem" id="zoom_in_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-zoom-in</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_zoom_in_menu_item_activate"/> <accelerator key="plus" modifiers="GDK_CONTROL_MASK" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="zoom_out_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-zoom-out</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_zoom_out_menu_item_activate"/> <accelerator key="minus" modifiers="GDK_CONTROL_MASK" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="zoom_one_to_one_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-zoom-100</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_zoom_one_to_one_menu_item_activate"/> <accelerator key="1" modifiers="GDK_CONTROL_MASK" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="zoom_best_fit_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-zoom-fit</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_zoom_best_fit_menu_item_activate"/> <accelerator key="F" modifiers="GDK_CONTROL_MASK" signal="activate"/> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="menuitem9"> <property name="visible">True</property> <property name="label" translatable="yes">_Tools</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu6"> <property name="visible">True</property> <child> <widget class="GtkMenuItem" id="rotate_clockwise_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Rotate Clockwise</property> <property name="use_underline">True</property> <signal name="activate" handler="on_rotate_clockwise_menu_item_activate"/> </widget> </child> <child> <widget class="GtkMenuItem" id="rotate_counter_clockwise_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">Rotate _Counterclockwise</property> <property name="use_underline">True</property> <signal name="activate" handler="on_rotate_counter_clockwise_menu_item_activate"/> </widget> </child> <child> <widget class="GtkCheckMenuItem" id="rotate_all_pages_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">Apply rotation to all _pages?</property> <property name="use_underline">True</property> <signal name="toggled" handler="on_rotate_all_pages_menu_item_toggled"/> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="options_menu"> <property name="visible">True</property> <property name="label" translatable="yes">_Options</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu7"> <property name="visible">True</property> <child> <widget class="GtkMenuItem" id="scanner_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Scanner</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="scanner_sub_menu"> <property name="visible">True</property> <child> <widget class="GtkMenuItem" id="menuitem5"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="label" translatable="yes">None</property> <property name="use_underline">True</property> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="scan_mode_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Mode</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="scan_mode_sub_menu"> <property name="visible">True</property> <child> <widget class="GtkMenuItem" id="menuitem8"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="label" translatable="yes">None</property> <property name="use_underline">True</property> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="scan_resolution_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Resolution</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="scan_resolution_sub_menu"> <property name="visible">True</property> <child> <widget class="GtkMenuItem" id="menuitem10"> <property name="visible">True</property> <property name="sensitive">False</property> <property name="label" translatable="yes">None</property> <property name="use_underline">True</property> </widget> </child> </widget> </child> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="menuitem3"> <property name="visible">True</property> <property name="label" translatable="yes">_Go</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu5"> <property name="visible">True</property> <child> <widget class="GtkImageMenuItem" id="go_first_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-goto-first</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_go_first_menu_item_activate"/> <accelerator key="Home" modifiers="" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="go_previous_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-go-back</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_go_previous_menu_item_activate"/> <accelerator key="Left" modifiers="GDK_MOD1_MASK" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="go_next_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-go-forward</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_go_next_menu_item_activate"/> <accelerator key="Right" modifiers="GDK_MOD1_MASK" signal="activate"/> </widget> </child> <child> <widget class="GtkImageMenuItem" id="go_last_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">gtk-goto-last</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_go_last_menu_item_activate"/> <accelerator key="End" modifiers="" signal="activate"/> </widget> </child> </widget> </child> </widget> </child> <child> <widget class="GtkMenuItem" id="menuitem4"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">_Help</property> <property name="use_underline">True</property> <child> <widget class="GtkMenu" id="menu3"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <child> <widget class="GtkImageMenuItem" id="contents_menu_item"> <property name="visible">True</property> <property name="label" translatable="yes">_Contents</property> <property name="use_underline">True</property> <accelerator key="F1" modifiers="" signal="activate"/> <child internal-child="image"> <widget class="GtkImage" id="menu-item-image3"> <property name="visible">True</property> <property name="stock">gtk-help</property> </widget> </child> </widget> </child> <child> <widget class="GtkImageMenuItem" id="about_menu_item"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">gtk-about</property> <property name="use_underline">True</property> <property name="use_stock">True</property> <signal name="activate" handler="on_about_menu_item_activate"/> </widget> </child> </widget> </child> </widget> </child> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkToolbar" id="main_toolbar"> <property name="visible">True</property> - <property name="toolbar_style">GTK_TOOLBAR_BOTH_HORIZ</property> <property name="icon_size">GTK_ICON_SIZE_SMALL_TOOLBAR</property> <child> <widget class="GtkToolButton" id="scan_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Scan</property> + <property name="label" translatable="yes">Scan</property> <property name="icon_name">scanner</property> <signal name="clicked" handler="on_scan_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="refresh_available_scanners_button"> <property name="visible">True</property> + <property name="label" translatable="yes">Refresh Available Scanners</property> <property name="stock_id">gtk-refresh</property> <signal name="clicked" handler="on_refresh_available_scanners_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="save_as_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Save As...</property> + <property name="label" translatable="yes">Save As</property> <property name="icon_name">document-save-as</property> <signal name="clicked" handler="on_save_as_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkSeparatorToolItem" id="toolbutton1"> <property name="visible">True</property> </widget> </child> <child> <widget class="GtkToolButton" id="zoom_in_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Zoom In</property> + <property name="label" translatable="yes">Zoom In</property> <property name="icon_name">zoom-in</property> <signal name="clicked" handler="on_zoom_in_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="zoom_out_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Zoom Out</property> + <property name="label" translatable="yes">Zoom Out</property> <property name="icon_name">zoom-out</property> <signal name="clicked" handler="on_zoom_out_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="zoom_one_to_one_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Normal Size</property> + <property name="label" translatable="yes">Normal Size</property> <property name="icon_name">zoom-original</property> <signal name="clicked" handler="on_zoom_one_to_one_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="zoom_best_fit_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Best Fit</property> + <property name="label" translatable="yes">Best Fit</property> <property name="icon_name">zoom-fit-best</property> <signal name="clicked" handler="on_zoom_best_fit_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkSeparatorToolItem" id="toolbutton2"> <property name="visible">True</property> </widget> </child> <child> <widget class="GtkToolButton" id="rotate_counter_clockwise_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Rotate Counterclockwise</property> + <property name="label" translatable="yes">Rotate Counterclockwise</property> <property name="icon_name">object-rotate-left</property> <signal name="clicked" handler="on_rotate_counter_clockwise_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="rotate_clockwise_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Rotate Clockwise</property> + <property name="label" translatable="yes">Rotate Clockwise</property> <property name="icon_name">object-rotate-right</property> <signal name="clicked" handler="on_rotate_clockwise_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkSeparatorToolItem" id="toolbutton4"> <property name="visible">True</property> </widget> </child> <child> <widget class="GtkToolButton" id="go_first_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">First</property> + <property name="label" translatable="yes">First</property> <property name="stock_id">gtk-goto-first</property> <signal name="clicked" handler="on_go_first_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="go_previous_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Back</property> + <property name="label" translatable="yes">Back</property> <property name="stock_id">gtk-go-back</property> <signal name="clicked" handler="on_go_previous_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="go_next_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Forward</property> + <property name="label" translatable="yes">Forward</property> <property name="stock_id">gtk-go-forward</property> <signal name="clicked" handler="on_go_next_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> <child> <widget class="GtkToolButton" id="go_last_button"> <property name="visible">True</property> <property name="tooltip" translatable="yes">Last</property> + <property name="label" translatable="yes">Last</property> <property name="stock_id">gtk-goto-last</property> <signal name="clicked" handler="on_go_last_button_clicked"/> </widget> <packing> <property name="homogeneous">True</property> </packing> </child> </widget> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> <child> <widget class="GtkViewport" id="document_view_docking_viewport"> <property name="visible">True</property> <property name="resize_mode">GTK_RESIZE_QUEUE</property> <child> <placeholder/> </child> </widget> <packing> <property name="position">2</property> </packing> </child> <child> <widget class="GtkViewport" id="status_view_docking_viewport"> <property name="visible">True</property> <property name="resize_mode">GTK_RESIZE_QUEUE</property> <property name="shadow_type">GTK_SHADOW_NONE</property> <child> <placeholder/> </child> </widget> <packing> <property name="expand">False</property> <property name="position">3</property> </packing> </child> </widget> </child> </widget> </glade-interface> diff --git a/models/main.py b/models/main.py index 9cdc8e8..bc28f90 100644 --- a/models/main.py +++ b/models/main.py @@ -1,454 +1,460 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme import nostaples.utils.properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it's option constraints can be queried without error. if value is not None: # Verify that the proper type is being set assert isinstance(value, saneme.Device) # Open the new scanner try: value.open() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Load the option constraints (valid_modes, etc.) for the new device self._load_scanner_option_constraints(value) # Manually constrain option values if self._prop_active_mode not in self._prop_valid_modes: self._prop_active_mode = self._prop_valid_modes[0] if self._prop_active_resolution not in self._prop_valid_resolutions: self._prop_active_resolution = self._prop_valid_resolutions[0] # Manually push option values to new device try: try: value.options['mode'].value = self._prop_active_mode except saneme.SaneReloadOptionsError: pass try: value.options['resolution'].value = \ int(self._prop_active_resolution) except saneme.SaneReloadOptionsError: pass except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Emit change notifications for manually updated properties self.notify_property_value_change( 'valid_modes', None, self.valid_modes) self.notify_property_value_change( 'valid_resolutions', None, self.valid_resolutions) self.notify_property_value_change( 'active_mode', None, self.active_mode) self.notify_property_value_change( 'active_resolution', None, self.active_resolution) # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notifications self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_mode = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value self.active_scanner.options['mode'].value = value + except saneme.SaneInexactValueError: + # TODO - what if "exact" value isn't in the list? + pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_mode'] = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_resolution = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value self.active_scanner.options['resolution'].value = int(value) + except saneme.SaneInexactValueError: + # TODO - what if "exact" value isn't in the list? + pass except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_resolution'] = value # Emit change notification self.notify_property_value_change( 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ Set the list of available scanners and update the active_scanner. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() self._prop_available_scanners = value self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None elif self._prop_active_scanner not in value: self.active_scanner = value[0] def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) if len(value) == 0: self.active_mode = None elif self.active_mode not in value: self.active_mode = value[0] def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) if len(value) == 0: self.active_resolution = None elif self.active_resolution not in value: self.active_resolution = value[0] # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution # INTERNAL METHODS def _load_scanner_option_constraints(self, sane_device): """ Load the option constraints from a specified scanner. """ main_controller = self.application.get_main_controller() try: assert sane_device.options['mode'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST self._prop_valid_modes = sane_device.options['mode'].constraint if sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_RANGE: min, max, step = sane_device.options['resolution'].constraint # Fix for ticket #34. if step is None or step == 0: step = 1 resolutions = [] # If there are not an excessive number, include every possible # resolution if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: i = min while i <= max: resolutions.append(str(i)) i = i + step # Otherwise, take a crack at building a sensible set of options # that mean that constraint criteria else: i = 1 increment = (max - min) / (constants.MAX_VALID_OPTION_VALUES - 1) while (i <= constants.MAX_VALID_OPTION_VALUES - 2): unrounded = min + (i * increment) rounded = int(round(unrounded / step) * step) resolutions.append(str(rounded)) i = i + 1 resolutions.insert(0, str(min)) resolutions.append(str(max)) self._prop_valid_resolutions = resolutions elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_INTEGER_LIST: self._prop_valid_resolutions = \ [str(i) for i in sane_device.options['resolution'].constraint] elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST: sane_device.options['resolution'].constraint else: raise AssertionError('Unsupported constraint type.') except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) def _load_scanner_option_values(self): """ Get current scanner options from the active_scanner. Useful for reloading any option that may have changed in response to a SaneReloadOptionsError. """ main_controller = self.application.get_main_controller() try: # TODO: ReloadOptions should reload constraints as well as values! self.active_mode = self.active_scanner.options['mode'].value self.active_resolution = \ str(self.active_scanner.options['resolution'].value) except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) \ No newline at end of file diff --git a/models/preferences.py b/models/preferences.py index 9270cb4..f9ea253 100644 --- a/models/preferences.py +++ b/models/preferences.py @@ -1,86 +1,93 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the PreferencesModel, which manages user settings. """ import logging from gtkmvc.model import Model from nostaples import constants import nostaples.utils.properties class PreferencesModel(Model): """ Manages user settings. """ __properties__ = \ { 'preview_mode' : constants.DEFAULT_PREVIEW_MODE, 'thumbnail_size' : constants.DEFAULT_THUMBNAIL_SIZE, + 'toolbar_style' : constants.DEFAULT_TOOLBAR_STYLE, 'unavailable_scanners' : [], # Not persisted 'blacklisted_scanners' : [], # List of scanner display names 'saved_keywords' : '', } def __init__(self, application): """ Constructs the PreferencesModel. """ Model.__init__(self) self.application = application self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() self.preview_mode = state_manager.init_state( 'preview_mode', constants.DEFAULT_PREVIEW_MODE, nostaples.utils.properties.PropertyStateCallback(self, 'preview_mode')) self.thumbnail_size = state_manager.init_state( 'thumbnail_size', constants.DEFAULT_THUMBNAIL_SIZE, nostaples.utils.properties.PropertyStateCallback(self, 'thumbnail_size')) + self.toolbar_style = state_manager.init_state( + 'toolbar_style', constants.DEFAULT_TOOLBAR_STYLE, + nostaples.utils.properties.PropertyStateCallback(self, 'toolbar_style')) + self.blacklisted_scanners = state_manager.init_state( 'blacklisted_scanners', constants.DEFAULT_BLACKLISTED_SCANNERS, nostaples.utils.properties.PropertyStateCallback(self, 'blacklisted_scanners')) self.saved_keywords = state_manager.init_state( 'saved_keywords', constants.DEFAULT_SAVED_KEYWORDS, nostaples.utils.properties.PropertyStateCallback(self, 'saved_keywords')) # PROPERTY SETTERS set_prop_preview_mode = nostaples.utils.properties.StatefulPropertySetter( 'preview_mode') set_prop_thumbnail_size = nostaples.utils.properties.StatefulPropertySetter( 'thumbnail_size') + set_prop_toolbar_style = nostaples.utils.properties.StatefulPropertySetter( + 'toolbar_style') set_prop_blacklisted_scanners = nostaples.utils.properties.StatefulPropertySetter( 'blacklisted_scanners') set_prop_saved_keywords = nostaples.utils.properties.StatefulPropertySetter( 'saved_keywords') \ No newline at end of file diff --git a/sane/errors.py b/sane/errors.py index 05abe38..81610b4 100644 --- a/sane/errors.py +++ b/sane/errors.py @@ -1,146 +1,153 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module contains the Python exceptions which take the place of SANE's status codes in the Pythonic reimplementation of the API. These are the errors that users will need to handle. """ class SaneError(Exception): """ Base class for all SANE Errors. """ def __init__(self, message='', device=None): self.message = message self.device = device class SaneUnknownError(SaneError): """ Exception denoting an error within the SANE library that could not be categorized. """ pass class SaneNoSuchDeviceError(SaneError): """ Exception denoting that a device requested by name did not exist. """ pass class SaneUnsupportedOperationError(SaneError): """ Exception denoting an unsupported operation was requested. Corresponds to SANE status code SANE_STATUS_UNSUPPORTED. """ pass class SaneDeviceBusyError(SaneError): """ Exception denoting that the requested device is being accessed by another process. Corresponds to SANE status code SANE_STATUS_DEVICE_BUSY. """ pass class SaneInvalidParameterError(SaneError): """ Exception denoting that SANE received an invalid parameter to a function call. Corresponds to SANE status code SANE_STATUS_INVAL. """ pass class SaneInvalidDataError(SaneError): """ Exception denoting that some data or argument was not valid. Corresponds to SANE status code SANE_STATUS_INVAL. """ pass class SaneEndOfFileError(SaneError): """ TODO: Should the user ever see this? probably handled internally Corresponds to SANE status code SANE_STATUS_EOF. """ pass class SaneDeviceJammedError(SaneError): """ Exception denoting that the device is jammed. Corresponds to SANE status code SANE_STATUS_JAMMED. """ pass class SaneNoDocumentsError(SaneError): """ Exception denoting that there are pages in the document feeder of the device. Corresponds to SANE status code SANE_STATUS_NO_DOCS. """ pass class SaneCoverOpenError(SaneError): """ Exception denoting that the cover of the device is open. Corresponds to SANE status code SANE_STATUS_COVER_OPEN. """ pass class SaneIOError(SaneError): """ Exception denoting that an IO error occurred while communicating wtih the device. Corresponds to the SANE status code SANE_STATUS_IO_ERROR. """ pass class SaneOutOfMemoryError(SaneError): """ Exception denoting that SANE ran out of memory during an operation. Corresponds to the SANE status code SANE_STATUS_NO_MEM. """ pass class SaneAccessDeniedError(SaneError): """ TODO: should this be handled in a special way? Corresponds to the SANE status code SANE_STATUS_ACCESS_DENIED. """ pass class SaneReloadOptionsError(SaneError): """ Exception denoting that a change to a SANE option has had a cascade effect on other options and thus that they should be read again to get the most up to date values. """ + pass + +class SaneInexactValueError(SaneError): + """ + Exception denoting that a change to a SANE option has caused the backend + to round its value. The frontend should read its new value for display. + """ pass \ No newline at end of file diff --git a/sane/saneme.py b/sane/saneme.py index 6df7f23..a85e4e8 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -377,647 +377,648 @@ class Device(object): elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) self._update_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) def has_option(self, option_name): """Return true if option_name is available for this scanner.""" return (option_name in self.options.keys()) def scan(self, progress_callback=None): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) elif sane_parameters.format == SANE_FRAME_RGB.value: pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capability = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number # String attributes should never be None self._name = ctypes_option.name if ctypes_option.name else '' self._title = ctypes_option.title if ctypes_option.title else '' self._description = ctypes_option.desc if ctypes_option.desc else '' self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 else: self._constraint = None # Read only properties def __get_name(self): """ Get the short-form name of this option, e.g. 'mode'. May be an empty string, but never None. """ return self._name name = property(__get_name) def __get_title(self): """ Get the full name of this option, e.g. 'Scan mode'. May be an empty string, but never None. """ return self._title title = property(__get_title) def __get_description(self): """ Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' May be an empty string, but never None. """ return self._description description = property(__get_description) def __get_type(self): """ Get the type of this option, e.g. OPTION_TYPE_STRING. """ return self._type type = property(__get_type) def __get_unit(self): """ Get the unit of this option, e.g.OPTION_UNIT_DPI. """ return self._unit unit = property(__get_unit) def __get_constraint_type(self): """ Get the type of constraint on this option, e.g. OPTION_CONSTRAINT_RANGE. """ return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then this is a list of integers which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """value Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option( handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i.' % status, device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value else: option_value = option_value.contents.value if self._log: self._log.debug( 'Option %s queried, its current value is %s.', self._name, option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: raise TypeError( 'option set with %s, expected BooleanType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: raise TypeError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: raise ValueError( 'value for option is longer than max string size') c_value = c_char_p(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: min, max, step = self._constraint if value < min: raise ValueError('value for option is less than min.') if value > max: raise ValueError('value for option is greater than max.') if step is not None and step > 0: if value % step != 0: raise ValueError( 'value for option is not evenly divisible by step.') elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i .' % status, device=self._device) if self._log: self._log.debug('Option %s set to value %s.', self._name, value) - # Constraint checking ensures this should never happen + # See SANE API 4.3.7 + if info_flags.value & SANE_INFO_RELOAD_OPTIONS: + raise SaneReloadOptionsError() + + # Catching this can not be avoided by constraint checking, as some + # devices restrict option values without setting a constraint range + # step. if info_flags.value & SANE_INFO_INEXACT: - raise AssertionError( - 'sane_control_option reported that set value was inexact.') + raise SaneInexactValueError() # TODO? if info_flags.value & SANE_INFO_RELOAD_PARAMS: pass - # See SANE API 4.3.7 - if info_flags.value & SANE_INFO_RELOAD_OPTIONS: - raise SaneReloadOptionsError() - value = property(__get_value, __set_value) # PUBLIC METHODS def is_soft_settable(self): """ Returns True if the option can be set by software. """ return self._capability & SANE_CAP_SOFT_SELECT def is_hard_settable(self): """ Returns True if the option can be set by hardware. """ return self._capability & SANE_CAP_HARD_SELECT def is_soft_gettable(self): """ Returns True if the option can be read by software. """ return self._capability & SANE_CAP_SOFT_DETECT def is_emulated(self): """ Returns True if the option is emulated by the backend driver. """ return self._capability & SANE_CAP_EMULATED # def is_automatic(self): # return self._capability & SANE_CAP_AUTOMATIC def is_active(self): """ Returns False if this device is unavailable because of the value of some other option. """ return not self._capability & SANE_CAP_INACTIVE # def is_advanced(self): # return self._capability & SANE_CAP_ADVANCED class ScanInfo(object): """ Contains the parameters and progress of a scan in progress. """ _width = 0 _height = 0 _depth = 0 _total_bytes = 0 def __init__(self, sane_parameters): """ Initialize the ScanInfo object from the sane_parameters. """ self._width = sane_parameters.pixels_per_line self._height = sane_parameters.lines self._depth = sane_parameters.depth self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines # Read only properties def __get_width(self): """Get the width of the current scan, in pixels.""" return self._width width = property(__get_width) def __get_height(self): """Get the height of the current scan, in pixels.""" return self._height height = property(__get_height) def __get_depth(self): """Get the depth of the current scan, in bits.""" return self._depth depth = property(__get_depth) def __get_total_bytes(self): """Get the total number of bytes comprising this scan.""" return self._total_bytes total_bytes = property(__get_total_bytes) if __name__ == '__main__': def progress_callback(sane_info, bytes_read): #print float(bytes_read) / sane_info.total_bytes pass import logging log_format = FORMAT = "%(message)s" logging.basicConfig(level=logging.DEBUG, format=log_format) sane = SaneMe(logging.getLogger()) devices = sane.get_device_list() for dev in devices: print dev.name devices[0].open() print devices[0].options.keys() try: devices[0].options['mode'].value = 'Gray' except SaneReloadOptionsError: pass try: devices[0].options['resolution'].value = 75 except SaneReloadOptionsError: pass try: devices[0].options['preview'].value = False except SaneReloadOptionsError: pass devices[0].scan(progress_callback).save('out.bmp') devices[0].close() \ No newline at end of file diff --git a/views/preferences.py b/views/preferences.py index e34894e..3986b6f 100644 --- a/views/preferences.py +++ b/views/preferences.py @@ -1,155 +1,164 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the PreferencesView which exposes user settings through a dialog seperate from the main application window. """ import logging import os import gtk from gtkmvc.view import View from nostaples import constants from nostaples.utils.gui import read_combobox, setup_combobox class PreferencesView(View): """ Exposes user settings through a dialog seperate from the main application window. """ def __init__(self, application): """ Constructs the PreferencesView, including setting up controls that could not be configured in Glade. """ self.application = application preferences_controller = application.get_preferences_controller() preferences_dialog_glade = os.path.join( constants.GUI_DIRECTORY, 'preferences_dialog.glade') View.__init__( self, preferences_controller, preferences_dialog_glade, 'preferences_dialog', None, False) self.log = logging.getLogger(self.__class__.__name__) # Can not configure this via constructor do to the multiple # root windows in the Main View. self['preferences_dialog'].set_transient_for( application.get_main_view()['scan_window']) # These two combobox's are setup dynamically. Because of this they # must have their signal handlers connected manually. Otherwise # their signals will fire before the view creation is finished. setup_combobox( self['preview_mode_combobox'], constants.PREVIEW_MODES_LIST, application.get_preferences_model().preview_mode) self['preview_mode_combobox'].connect( 'changed', preferences_controller.on_preview_mode_combobox_changed) setup_combobox( self['thumbnail_size_combobox'], constants.THUMBNAIL_SIZE_LIST, application.get_preferences_model().thumbnail_size) self['thumbnail_size_combobox'].connect( 'changed', preferences_controller.on_thumbnail_size_combobox_changed) + setup_combobox( + self['toolbar_style_combobox'], + constants.TOOLBAR_STYLES_LIST, + application.get_preferences_model().toolbar_style) + + self['toolbar_style_combobox'].connect( + 'changed', + preferences_controller.on_toolbar_style_combobox_changed) + # Setup the unavailable scanners tree view unavailable_liststore = gtk.ListStore(str) self['unavailable_tree_view'] = gtk.TreeView() self['unavailable_tree_view'].set_model(unavailable_liststore) self['unavailable_column'] = gtk.TreeViewColumn(None) self['unavailable_cell'] = gtk.CellRendererText() self['unavailable_tree_view'].append_column(self['unavailable_column']) self['unavailable_column'].pack_start(self['unavailable_cell'], True) self['unavailable_column'].add_attribute( self['unavailable_cell'], 'text', 0) self['unavailable_tree_view'].get_selection().set_mode( gtk.SELECTION_NONE) self['unavailable_tree_view'].set_headers_visible(False) self['unavailable_tree_view'].set_property('can-focus', False) self['unavailable_scrolled_window'].add(self['unavailable_tree_view']) self['unavailable_scrolled_window'].show_all() # Setup the blacklist tree view blacklist_liststore = gtk.ListStore(str) self['blacklist_tree_view'] = gtk.TreeView() self['blacklist_tree_view'].set_model(blacklist_liststore) self['blacklist_column'] = gtk.TreeViewColumn(None) self['blacklist_cell'] = gtk.CellRendererText() self['blacklist_tree_view'].append_column(self['blacklist_column']) self['blacklist_column'].pack_start(self['blacklist_cell'], True) self['blacklist_column'].add_attribute(self['blacklist_cell'], 'text', 0) self['blacklist_tree_view'].get_selection().set_mode( gtk.SELECTION_SINGLE) self['blacklist_tree_view'].set_headers_visible(False) self['blacklist_tree_view'].set_property('can-focus', False) self['blacklist_scrolled_window'].add(self['blacklist_tree_view']) self['blacklist_scrolled_window'].show_all() # Setup the keywords tree view keywords_liststore = gtk.ListStore(str) self['keywords_tree_view'] = gtk.TreeView() self['keywords_tree_view'].set_model(keywords_liststore) self['keywords_column'] = gtk.TreeViewColumn(None) self['keywords_cell'] = gtk.CellRendererText() self['keywords_tree_view'].append_column(self['keywords_column']) self['keywords_column'].pack_start(self['keywords_cell'], True) self['keywords_column'].add_attribute(self['keywords_cell'], 'text', 0) self['keywords_tree_view'].get_selection().set_mode( gtk.SELECTION_SINGLE) self['keywords_tree_view'].set_headers_visible(False) self['keywords_tree_view'].set_property('can-focus', False) self['keywords_scrolled_window'].add(self['keywords_tree_view']) self['keywords_scrolled_window'].show_all() # Setup the available devices tree view available_liststore = gtk.ListStore(str) self['available_tree_view'] = gtk.TreeView() self['available_tree_view'].set_model(available_liststore) self['available_column'] = gtk.TreeViewColumn(None) self['available_cell'] = gtk.CellRendererText() self['available_tree_view'].append_column(self['available_column']) self['available_column'].pack_start(self['available_cell'], True) self['available_column'].add_attribute(self['available_cell'], 'text', 0) self['available_tree_view'].get_selection().set_mode( gtk.SELECTION_SINGLE) self['available_tree_view'].set_headers_visible(False) self['available_tree_view'].set_property('can-focus', False) self['available_scrolled_window'].add(self['available_tree_view']) self['available_scrolled_window'].show_all() application.get_preferences_controller().register_view(self) self.log.debug('Created.') def run(self): """Run the modal preferences dialog.""" self['preferences_dialog'].run() \ No newline at end of file
onyxfish/nostaples
2ba11aa9b415466d6cd6845372fdf99f584f128c
Guard against second possible ZeroDivisionError involving option constraint step.
diff --git a/sane/saneme.py b/sane/saneme.py index cba37ae..6df7f23 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -325,697 +325,699 @@ class Device(object): i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) self._options[coption.contents.name] = Option( self, i, coption.contents, self._log) i = i + 1 # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Public methods def open(self): """ Open a new handle to this device. Must be called before any operations (including getting or setting options) are performed on this device. """ if self._handle: raise AssertionError('device handle already exists.') self._handle = SANE_Handle() status = sane_open(self.name, byref(self._handle)) # If and exception will be thrown, nullify device handle # so is_open() will return false for the device. if status != SANE_STATUS_GOOD.value: self._handle = None if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_open reported that the device was busy.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) self._update_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) def has_option(self, option_name): """Return true if option_name is available for this scanner.""" return (option_name in self.options.keys()) def scan(self, progress_callback=None): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) elif sane_parameters.format == SANE_FRAME_RGB.value: pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capability = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number # String attributes should never be None self._name = ctypes_option.name if ctypes_option.name else '' self._title = ctypes_option.title if ctypes_option.title else '' self._description = ctypes_option.desc if ctypes_option.desc else '' self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 else: self._constraint = None # Read only properties def __get_name(self): """ Get the short-form name of this option, e.g. 'mode'. May be an empty string, but never None. """ return self._name name = property(__get_name) def __get_title(self): """ Get the full name of this option, e.g. 'Scan mode'. May be an empty string, but never None. """ return self._title title = property(__get_title) def __get_description(self): """ Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' May be an empty string, but never None. """ return self._description description = property(__get_description) def __get_type(self): """ Get the type of this option, e.g. OPTION_TYPE_STRING. """ return self._type type = property(__get_type) def __get_unit(self): """ Get the unit of this option, e.g.OPTION_UNIT_DPI. """ return self._unit unit = property(__get_unit) def __get_constraint_type(self): """ Get the type of constraint on this option, e.g. OPTION_CONSTRAINT_RANGE. """ return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then this is a list of integers which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """value Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option( handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i.' % status, device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value else: option_value = option_value.contents.value if self._log: self._log.debug( 'Option %s queried, its current value is %s.', self._name, option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: raise TypeError( 'option set with %s, expected BooleanType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: raise TypeError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: raise ValueError( 'value for option is longer than max string size') c_value = c_char_p(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: - if value < self._constraint[0]: + min, max, step = self._constraint + if value < min: raise ValueError('value for option is less than min.') - if value > self._constraint[1]: + if value > max: raise ValueError('value for option is greater than max.') - if value % self._constraint[2] != 0: - raise ValueError( - 'value for option is not divisible by step.') + if step is not None and step > 0: + if value % step != 0: + raise ValueError( + 'value for option is not evenly divisible by step.') elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i .' % status, device=self._device) if self._log: self._log.debug('Option %s set to value %s.', self._name, value) # Constraint checking ensures this should never happen if info_flags.value & SANE_INFO_INEXACT: raise AssertionError( 'sane_control_option reported that set value was inexact.') # TODO? if info_flags.value & SANE_INFO_RELOAD_PARAMS: pass # See SANE API 4.3.7 if info_flags.value & SANE_INFO_RELOAD_OPTIONS: raise SaneReloadOptionsError() value = property(__get_value, __set_value) # PUBLIC METHODS def is_soft_settable(self): """ Returns True if the option can be set by software. """ return self._capability & SANE_CAP_SOFT_SELECT def is_hard_settable(self): """ Returns True if the option can be set by hardware. """ return self._capability & SANE_CAP_HARD_SELECT def is_soft_gettable(self): """ Returns True if the option can be read by software. """ return self._capability & SANE_CAP_SOFT_DETECT def is_emulated(self): """ Returns True if the option is emulated by the backend driver. """ return self._capability & SANE_CAP_EMULATED # def is_automatic(self): # return self._capability & SANE_CAP_AUTOMATIC def is_active(self): """ Returns False if this device is unavailable because of the value of some other option. """ return not self._capability & SANE_CAP_INACTIVE # def is_advanced(self): # return self._capability & SANE_CAP_ADVANCED class ScanInfo(object): """ Contains the parameters and progress of a scan in progress. """ _width = 0 _height = 0 _depth = 0 _total_bytes = 0 def __init__(self, sane_parameters): """ Initialize the ScanInfo object from the sane_parameters. """ self._width = sane_parameters.pixels_per_line self._height = sane_parameters.lines self._depth = sane_parameters.depth self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines # Read only properties def __get_width(self): """Get the width of the current scan, in pixels.""" return self._width width = property(__get_width) def __get_height(self): """Get the height of the current scan, in pixels.""" return self._height height = property(__get_height) def __get_depth(self): """Get the depth of the current scan, in bits.""" return self._depth depth = property(__get_depth) def __get_total_bytes(self): """Get the total number of bytes comprising this scan.""" return self._total_bytes total_bytes = property(__get_total_bytes) if __name__ == '__main__': def progress_callback(sane_info, bytes_read): #print float(bytes_read) / sane_info.total_bytes pass import logging log_format = FORMAT = "%(message)s" logging.basicConfig(level=logging.DEBUG, format=log_format) sane = SaneMe(logging.getLogger()) devices = sane.get_device_list() for dev in devices: print dev.name devices[0].open() print devices[0].options.keys() try: devices[0].options['mode'].value = 'Gray' except SaneReloadOptionsError: pass try: devices[0].options['resolution'].value = 75 except SaneReloadOptionsError: pass try: devices[0].options['preview'].value = False except SaneReloadOptionsError: pass devices[0].scan(progress_callback).save('out.bmp') devices[0].close() \ No newline at end of file
onyxfish/nostaples
23bda7674f915ff80161bd13b18f3ded24453d42
Experimental fix for options that do not specify a range step.
diff --git a/models/main.py b/models/main.py index 63b1ae4..9cdc8e8 100644 --- a/models/main.py +++ b/models/main.py @@ -1,450 +1,454 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme import nostaples.utils.properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it's option constraints can be queried without error. if value is not None: # Verify that the proper type is being set assert isinstance(value, saneme.Device) # Open the new scanner try: value.open() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Load the option constraints (valid_modes, etc.) for the new device self._load_scanner_option_constraints(value) # Manually constrain option values if self._prop_active_mode not in self._prop_valid_modes: self._prop_active_mode = self._prop_valid_modes[0] if self._prop_active_resolution not in self._prop_valid_resolutions: self._prop_active_resolution = self._prop_valid_resolutions[0] # Manually push option values to new device try: try: value.options['mode'].value = self._prop_active_mode except saneme.SaneReloadOptionsError: pass try: value.options['resolution'].value = \ int(self._prop_active_resolution) except saneme.SaneReloadOptionsError: pass except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Emit change notifications for manually updated properties self.notify_property_value_change( 'valid_modes', None, self.valid_modes) self.notify_property_value_change( 'valid_resolutions', None, self.valid_resolutions) self.notify_property_value_change( 'active_mode', None, self.active_mode) self.notify_property_value_change( 'active_resolution', None, self.active_resolution) # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notifications self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_mode = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value self.active_scanner.options['mode'].value = value except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_mode'] = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Set new property value self._prop_active_resolution = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value self.active_scanner.options['resolution'].value = int(value) except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_resolution'] = value # Emit change notification self.notify_property_value_change( 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ Set the list of available scanners and update the active_scanner. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() self._prop_available_scanners = value self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None elif self._prop_active_scanner not in value: self.active_scanner = value[0] def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) if len(value) == 0: self.active_mode = None elif self.active_mode not in value: self.active_mode = value[0] def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) if len(value) == 0: self.active_resolution = None elif self.active_resolution not in value: self.active_resolution = value[0] # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution # INTERNAL METHODS def _load_scanner_option_constraints(self, sane_device): """ Load the option constraints from a specified scanner. """ main_controller = self.application.get_main_controller() try: assert sane_device.options['mode'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST self._prop_valid_modes = sane_device.options['mode'].constraint if sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_RANGE: min, max, step = sane_device.options['resolution'].constraint + # Fix for ticket #34. + if step is None or step == 0: + step = 1 + resolutions = [] # If there are not an excessive number, include every possible # resolution if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: i = min while i <= max: resolutions.append(str(i)) i = i + step # Otherwise, take a crack at building a sensible set of options # that mean that constraint criteria else: i = 1 increment = (max - min) / (constants.MAX_VALID_OPTION_VALUES - 1) while (i <= constants.MAX_VALID_OPTION_VALUES - 2): unrounded = min + (i * increment) rounded = int(round(unrounded / step) * step) resolutions.append(str(rounded)) i = i + 1 resolutions.insert(0, str(min)) resolutions.append(str(max)) self._prop_valid_resolutions = resolutions elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_INTEGER_LIST: self._prop_valid_resolutions = \ [str(i) for i in sane_device.options['resolution'].constraint] elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST: sane_device.options['resolution'].constraint else: raise AssertionError('Unsupported constraint type.') except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) def _load_scanner_option_values(self): """ Get current scanner options from the active_scanner. Useful for reloading any option that may have changed in response to a SaneReloadOptionsError. """ main_controller = self.application.get_main_controller() try: # TODO: ReloadOptions should reload constraints as well as values! self.active_mode = self.active_scanner.options['mode'].value self.active_resolution = \ str(self.active_scanner.options['resolution'].value) except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) \ No newline at end of file
onyxfish/nostaples
f52abc09a26329fd28f57b792892216e9c506acc
Fix misnamed variable and check that a device option is gettable before attempting to read it when using --debugdevices.
diff --git a/nostaples b/nostaples index 5d0b5f9..dfc8089 100755 --- a/nostaples +++ b/nostaples @@ -1,169 +1,172 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. ''' This module parses command line options, checks that imports are available, and bootstraps the NoStaples application. ''' import optparse import sys import pygtk pygtk.require('2.0') import gtk # COMMAND LINE PARSING # Functions to pretty-print debugging info def print_device_debug(i, device): """Pretty-print device information.""" print 'Device %i' % i print '' print 'Name:\t%s' % device.name print 'Vendor:\t%s' % device.vendor print 'Model:\t%s' % device.model print 'Type:\t%s' % device.type print '' try: device.open() j = 1 for option in device.options.values(): print_option_debug(j, option) print '' j = j + 1 device.close() except Exception: print '\t**Failed to open device.**' def print_option_debug(j, option): """Pretty-print device option information.""" print '\tOption %i' % j print '' print '\tName:\t%s' % option._name print '\tTitle:\t%s' % option._title print '\tDesc:\t%s' % option._description print '\tType:\t%s' % option._type print '\tUnit:\t%s' % option._unit print '\tSize:\t%s' % option._size - print '\tCap:\t%s' % option._capabilities + print '\tCap:\t%s' % option._capability print '\tConstraint Type:\t%s' % option._constraint_type print '\tConstraint:\t', option._constraint - try: - print '\tValue:\t%s' % str(option.value) - except Exception: - print '\t**Failed to get current value for option.**' + if option.is_soft_gettable(): + try: + print '\tValue:\t%s' % str(option.value) + except Exception: + print '\t**Failed to get current value for option.**' + else: + print '\tValue:\tNot soft-gettable.' # Parse command line options parser = optparse.OptionParser() parser.add_option("--debugdevices", action="store_true", dest="debug_devices", help="print debugging information for all connected devices") (options, args) = parser.parse_args() if options.debug_devices: import nostaples.sane as saneme sane_manager = saneme.SaneMe() devices = sane_manager.get_device_list() if len(devices) == 0: print 'No devices found.' i = 1 for device in devices: print_device_debug(i, device) print '' i = i + 1 sys.exit() # CHECK IMPORT VERSIONS def display_import_error(message): """ Displays a GTK message dialog containing the import error and then exits the application. """ dialog = gtk.MessageDialog( parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_NONE) dialog.set_title('') primary = "<big><b>A required package is not installed.</b></big>" secondary = '%s' % message dialog.set_markup(primary) dialog.format_secondary_markup(secondary) dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) response = dialog.run() dialog.destroy() sys.exit() # Python if sys.version_info < (2, 5) or sys.version_info >= (3, 0): display_import_error( 'NoStaples requires Python version 2.5 or later (but not version 3.0 or later).') # GTK if gtk.gtk_version < (2, 6, 0): display_import_error( 'NoStaples requires GTK+ version 2.6 or later.') if gtk.pygtk_version < (2, 8, 0): display_import_error( 'NoStaples requires PyGTK version 2.8 or later.') # PIL try: import Image except ImportError: display_import_error( 'NoStaples requires the Python Imaging Library (PIL) 1.1.6 or later.') pil_version = tuple([int(i) for i in Image.VERSION.split('.')]) if pil_version < (1, 1, 6): display_import_error( 'NoStaples requires the Python Imaging Library (PIL) version 1.1.6 or later.') # ReportLab try: import reportlab except ImportError: display_import_error( 'NoStaples requires ReportLab version 2.1 or later.') reportlab_version = tuple([int(i) for i in reportlab.Version.split('.')]) if reportlab_version < (2, 1): display_import_error( 'NoStaples requires ReportLab version 2.1 or later.') # BOOTSTRAP from nostaples.application import Application nostaples = Application() -nostaples.run() \ No newline at end of file +nostaples.run() diff --git a/sane/saneme.py b/sane/saneme.py index c0916f5..cba37ae 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -87,935 +87,935 @@ class SaneMe(object): version = property(__get_version) def _setup(self): """ Iniitalize SANE and retrieve the current installed version. """ version_code = SANE_Int() auth_callback = SANE_Auth_Callback(self._sane_auth_callback) status = sane_init(byref(version_code), auth_callback) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_init returned an invalid status: %i.' % status) self._version = (SANE_VERSION_MAJOR(version_code), SANE_VERSION_MINOR(version_code), SANE_VERSION_BUILD(version_code)) if self._log: self._log.info('SANE version %s initalized.', self._version) def _sane_auth_callback(self, resource, username, password): """ TODO """ raise NotImplementedError( 'sane_auth_callback requested, but not yet implemented.') def _shutdown(self): """ Deinitialize SANE. This code would go in __del__, but it is not guaranteed that method will be called and sane_exit must be called to release resources. To ensure this method is called it is registered with atexit. """ for device in self._devices: if device.is_open(): device.close() sane_exit() self._version = None if self._log: self._log.info('SANE deinitialized.') # Public Methods def get_device_list(self): """ Poll for connected devices. This method may take several seconds to return. Note that SANE is exited and re-inited before querying for devices to workaround a limitation in SANE's USB driver which causes the device list to only be updated on init. This means that all settings applied to all devices will be B{lost} and must be restored by the calling application. This was found documented here: U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html} """ if not self._version: raise AssertionError('version was None') # See docstring for details on this voodoo self._shutdown() self._setup() cdevices = POINTER(POINTER(SANE_Device))() status = sane_get_devices(byref(cdevices), SANE_Bool(0)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_get_devices ran out of memory.') else: raise SaneUnknownError( 'sane_get_devices returned an invalid status: %i.' % status) device_count = 0 self._devices = [] while cdevices[device_count]: self._devices.append( Device(cdevices[device_count].contents, self._log)) device_count += 1 if self._log: self._log.info('SANE queried, %i device(s) found.', device_count) return self._devices def get_device_by_name(self, name): """ Retrieve a L{Device} by name. Must be preceded by a call to L{get_device_list}. """ for device in self._devices: if device.name == name: return device raise SaneNoSuchDeviceError( 'The requested device does not exist.') class Device(object): """ This is the primary object for interacting with SANE. It represents a single device and handles enumeration of options, getting and setting of options, and starting and stopping of scanning jobs. """ _log = None _handle = None _name = '' _vendor = '' _model = '' _type = '' _display_name = '' _options = {} def __init__(self, ctypes_device, log=None): """ Sets the Devices properties from a ctypes SANE_Device and queries for its available options. """ self._log = log # String attributes should never be None self._name = ctypes_device.name if ctypes_device.name else '' self._vendor = ctypes_device.vendor if ctypes_device.vendor else '' self._model = ctypes_device.model if ctypes_device.model else '' self._type = ctypes_device.type if ctypes_device.type else '' self._display_name = ' '.join([self._vendor, self._model]) # Read only properties def __get_name(self): """ Get the complete SANE identifier for this device, e.g. 'lexmark:libusb:002:006'. """ return self._name name = property(__get_name) def __get_vendor(self): """Get the manufacturer of this device, e.g. 'Lexmark'.""" return self._vendor vendor = property(__get_vendor) def __get_model(self): """Get the specific model of this device, e.g. 'X1100/rev. B2'.""" return self._model model = property(__get_model) def __get_type(self): """Get the type of this device, e.g. 'flatbed scanner'.""" return self._type type = property(__get_type) def __get_display_name(self): """ Get an appropriate name to use for displaying this device to a user, e.g. 'Lexmark X1100/rev. B2'.""" return self._display_name display_name = property(__get_display_name) def __get_options(self): """Get the dictionary of options that this device has.""" return self._options options = property(__get_options) # Internal methods def _update_options(self): """ Update the list of available options for this device. As these are immutable, this should only need to be called when the Device is first instantiated. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') option_value = pointer(c_int()) status = sane_control_option( self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: raise SaneUnsupportedOperationError( 'sane_control_option reported that a value was outside the option\'s constraint.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) option_count = option_value.contents.value if self._log: self._log.debug('Device queried, %i option(s) found.', option_count) self._options.clear() i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) self._options[coption.contents.name] = Option( self, i, coption.contents, self._log) i = i + 1 # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Public methods def open(self): """ Open a new handle to this device. Must be called before any operations (including getting or setting options) are performed on this device. """ if self._handle: raise AssertionError('device handle already exists.') self._handle = SANE_Handle() status = sane_open(self.name, byref(self._handle)) # If and exception will be thrown, nullify device handle # so is_open() will return false for the device. if status != SANE_STATUS_GOOD.value: self._handle = None if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_open reported that the device was busy.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) self._update_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) def has_option(self, option_name): """Return true if option_name is available for this scanner.""" return (option_name in self.options.keys()) def scan(self, progress_callback=None): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) elif sane_parameters.format == SANE_FRAME_RGB.value: pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 - _capabilities = 0 + _capability = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number # String attributes should never be None self._name = ctypes_option.name if ctypes_option.name else '' self._title = ctypes_option.title if ctypes_option.title else '' self._description = ctypes_option.desc if ctypes_option.desc else '' self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 else: self._constraint = None # Read only properties def __get_name(self): """ Get the short-form name of this option, e.g. 'mode'. May be an empty string, but never None. """ return self._name name = property(__get_name) def __get_title(self): """ Get the full name of this option, e.g. 'Scan mode'. May be an empty string, but never None. """ return self._title title = property(__get_title) def __get_description(self): """ Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' May be an empty string, but never None. """ return self._description description = property(__get_description) def __get_type(self): """ Get the type of this option, e.g. OPTION_TYPE_STRING. """ return self._type type = property(__get_type) def __get_unit(self): """ Get the unit of this option, e.g.OPTION_UNIT_DPI. """ return self._unit unit = property(__get_unit) def __get_constraint_type(self): """ Get the type of constraint on this option, e.g. OPTION_CONSTRAINT_RANGE. """ return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then this is a list of integers which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """value Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option( handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i.' % status, device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value else: option_value = option_value.contents.value if self._log: self._log.debug( 'Option %s queried, its current value is %s.', self._name, option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: raise TypeError( 'option set with %s, expected BooleanType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: raise TypeError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: raise ValueError( 'value for option is longer than max string size') c_value = c_char_p(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: if value < self._constraint[0]: raise ValueError('value for option is less than min.') if value > self._constraint[1]: raise ValueError('value for option is greater than max.') if value % self._constraint[2] != 0: raise ValueError( 'value for option is not divisible by step.') elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i .' % status, device=self._device) if self._log: self._log.debug('Option %s set to value %s.', self._name, value) # Constraint checking ensures this should never happen if info_flags.value & SANE_INFO_INEXACT: raise AssertionError( 'sane_control_option reported that set value was inexact.') # TODO? if info_flags.value & SANE_INFO_RELOAD_PARAMS: pass # See SANE API 4.3.7 if info_flags.value & SANE_INFO_RELOAD_OPTIONS: raise SaneReloadOptionsError() value = property(__get_value, __set_value) # PUBLIC METHODS def is_soft_settable(self): """ Returns True if the option can be set by software. """ return self._capability & SANE_CAP_SOFT_SELECT def is_hard_settable(self): """ Returns True if the option can be set by hardware. """ return self._capability & SANE_CAP_HARD_SELECT def is_soft_gettable(self): """ Returns True if the option can be read by software. """ return self._capability & SANE_CAP_SOFT_DETECT def is_emulated(self): """ Returns True if the option is emulated by the backend driver. """ return self._capability & SANE_CAP_EMULATED # def is_automatic(self): # return self._capability & SANE_CAP_AUTOMATIC def is_active(self): """ Returns False if this device is unavailable because of the value of some other option. """ return not self._capability & SANE_CAP_INACTIVE # def is_advanced(self): # return self._capability & SANE_CAP_ADVANCED class ScanInfo(object): """ Contains the parameters and progress of a scan in progress. """ _width = 0 _height = 0 _depth = 0 _total_bytes = 0 def __init__(self, sane_parameters): """ Initialize the ScanInfo object from the sane_parameters. """ self._width = sane_parameters.pixels_per_line self._height = sane_parameters.lines self._depth = sane_parameters.depth self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines # Read only properties def __get_width(self): """Get the width of the current scan, in pixels.""" return self._width width = property(__get_width) def __get_height(self): """Get the height of the current scan, in pixels.""" return self._height height = property(__get_height) def __get_depth(self): """Get the depth of the current scan, in bits.""" return self._depth depth = property(__get_depth) def __get_total_bytes(self): """Get the total number of bytes comprising this scan.""" return self._total_bytes total_bytes = property(__get_total_bytes) if __name__ == '__main__': def progress_callback(sane_info, bytes_read): #print float(bytes_read) / sane_info.total_bytes pass import logging log_format = FORMAT = "%(message)s" logging.basicConfig(level=logging.DEBUG, format=log_format) sane = SaneMe(logging.getLogger()) devices = sane.get_device_list() for dev in devices: print dev.name devices[0].open() print devices[0].options.keys() try: devices[0].options['mode'].value = 'Gray' except SaneReloadOptionsError: pass try: devices[0].options['resolution'].value = 75 except SaneReloadOptionsError: pass try: devices[0].options['preview'].value = False except SaneReloadOptionsError: pass devices[0].scan(progress_callback).save('out.bmp') devices[0].close() \ No newline at end of file
onyxfish/nostaples
addd2cc426f396a67bd5378508a79e1de52cda0c
Moved import guards into bootstraping so that they execute as early as possible.
diff --git a/application.py b/application.py index f83a15c..5daa685 100644 --- a/application.py +++ b/application.py @@ -1,404 +1,334 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds NoStaples' main method which handles the instantiation of MVC objects and then starts the gtk main loop. """ import logging.config import os import sys -import pygtk -pygtk.require('2.0') import gtk from nostaples import constants from nostaples.controllers.about import AboutController from nostaples.controllers.document import DocumentController from nostaples.controllers.main import MainController from nostaples.controllers.page import PageController from nostaples.controllers.preferences import PreferencesController from nostaples.controllers.save import SaveController from nostaples.controllers.status import StatusController from nostaples.models.document import DocumentModel from nostaples.models.main import MainModel from nostaples.models.page import PageModel from nostaples.models.preferences import PreferencesModel from nostaples.models.save import SaveModel from nostaples.models.status import StatusModel import nostaples.sane as saneme import nostaples.utils.gtkexcepthook from nostaples.utils.state import GConfStateManager from nostaples.views.about import AboutView from nostaples.views.document import DocumentView from nostaples.views.main import MainView from nostaples.views.page import PageView from nostaples.views.preferences import PreferencesView from nostaples.views.save import SaveView -from nostaples.views.status import StatusView +from nostaples.views.status import StatusView class Application(object): """ A 'front controller' class that stores references to all top-level components of the application and facilitates communication between them. A reference to this class is injected into each controller component of the application via its constructor. These components then query the application object when they need to access other parts of the system. """ _state_manager = None _sane = None _main_model = None _main_controller = None _main_view = None _document_model = None _document_controller = None _document_view = None _null_page_model = None _page_controller = None _page_view = None _status_model = None _status_controller = None _status_view = None _preferences_model = None _preferences_controller = None _preferences_view = None _save_model = None _save_controller = None _save_view = None _about_controller = None _about_view = None def __init__(self): """ Set up the config directory, logging, and state persistence. Construct the Main MVC component triplet (which will in turn construct all sub components). Per """ - self._check_import_versions() self._init_config() self._init_logging() self._init_state() self._init_sane() self._init_main_components() self._init_settings() - - def _check_import_versions(self): - """ - Attempt to import all dependencies and check that supported versions - are available. - """ - # Python - if sys.version_info < (2, 5) or sys.version_info >= (3, 0): - self._display_import_error( - 'NoStaples requires Python version 2.5 or later (but not version 3.0 or later).') - - # GTK - if gtk.gtk_version < (2, 6, 0): - self._display_import_error( - 'NoStaples requires GTK+ version 2.6 or later.') - - if gtk.pygtk_version < (2, 8, 0): - self._display_import_error( - 'NoStaples requires PyGTK version 2.8 or later.') - - # PIL - try: - import Image - except ImportError: - self._display_import_error( - 'NoStaples requires the Python Imaging Library (PIL) 1.1.6 or later.') - - pil_version = tuple([int(i) for i in Image.VERSION.split('.')]) - - if pil_version < (1, 1, 6): - self._display_import_error( - 'NoStaples requires the Python Imaging Library (PIL) version 1.1.6 or later.') - - # ReportLab - try: - import reportlab - except ImportError: - self._display_import_error( - 'NoStaples requires ReportLab version 2.1 or later.') - - reportlab_version = tuple([int(i) for i in reportlab.Version.split('.')]) - - if reportlab_version < (2, 1): - self._display_import_error( - 'NoStaples requires ReportLab version 2.1 or later.') - - def _display_import_error(self, message): - """ - Displays a GTK message dialog containing the import error and then - exits the application. - """ - dialog = gtk.MessageDialog( - parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_NONE) - dialog.set_title('') - - primary = "<big><b>A required package is not installed.</b></big>" - secondary = '%s' % message - - dialog.set_markup(primary) - dialog.format_secondary_markup(secondary) - - dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) - - response = dialog.run() - dialog.destroy() - - sys.exit() def _init_config(self): """Setup the config directory.""" if not os.path.exists(constants.APP_DIRECTORY): os.mkdir(constants.APP_DIRECTORY) def _init_logging(self): """Setup logging for the application.""" logging.config.fileConfig(constants.LOGGING_CONFIG) def _init_state(self): """Setup the state manager.""" self._state_manager = GConfStateManager() def _init_sane(self): """Setup SANE.""" self._sane = saneme.SaneMe(logging.getLogger("saneme")) def _init_main_components(self): """ Create the main application components, which will request creation of other components as necessary. """ self._main_model = MainModel(self) self._main_controller = MainController(self) self._main_view = MainView(self) def _init_settings(self): """ Load current settings from the state manager and poll for available scanners. """ self._main_model.load_state() self.get_save_model().load_state() self.get_preferences_model().load_state() self._main_controller._update_available_scanners() # PUBLIC METHODS def run(self): """Execute the GTK main loop.""" assert isinstance(self._main_view, MainView) self._main_view.show() gtk.main() def get_state_manager(self): """Return the L{GConfStateManager} component.""" assert isinstance(self._state_manager, GConfStateManager) return self._state_manager def get_sane(self): """Return the SaneMe object.""" assert isinstance(self._sane, saneme.SaneMe) return self._sane def get_main_model(self): """Return the L{MainModel} component.""" assert self._main_model return self._main_model def get_main_controller(self): """Return the L{MainController} component.""" assert self._main_controller return self._main_controller def get_main_view(self): """Return the L{MainView} component.""" assert self._main_view return self._main_view def get_document_model(self): """Return the L{DocumentModel} component.""" if not self._document_model: self._document_model = DocumentModel(self) return self._document_model def get_document_controller(self): """Return the L{DocumentController} component.""" if not self._document_controller: self._document_controller = DocumentController(self) return self._document_controller def get_document_view(self): """Return the L{DocumentView} component.""" if not self._document_view: self._document_view = DocumentView(self) return self._document_view def get_null_page_model(self): """ Return an empty L{PageModel} object. This is the PageModel that is used when no pages have been scanned. """ if not self._null_page_model: self._null_page_model = PageModel(self) return self._null_page_model def get_current_page_model(self): """ Return the current/active L{PageModel} object. This is a convenience function. """ return self.get_page_controller().get_current_page_model() def get_page_controller(self): """Return the L{PageController} component.""" if not self._page_controller: self._page_controller = PageController(self) return self._page_controller def get_page_view(self): """Return the L{PageView} component.""" if not self._page_view: self._page_view = PageView(self) return self._page_view def get_status_model(self): """Return the L{StatusModel} component.""" if not self._status_model: self._status_model = StatusModel(self) return self._status_model def get_status_controller(self): """Return the L{StatusController} component.""" if not self._status_controller: self._status_controller = StatusController(self) return self._status_controller def get_status_view(self): """Return the L{StatusView} component.""" if not self._status_view: self._status_view = StatusView(self) return self._status_view def get_preferences_model(self): """Return the L{PreferencesModel} component.""" if not self._preferences_model: self._preferences_model = PreferencesModel(self) return self._preferences_model def get_preferences_controller(self): """Return the L{PreferencesController} component.""" if not self._preferences_controller: self._preferences_controller = PreferencesController(self) return self._preferences_controller def get_preferences_view(self): """Return the L{PreferencesView} component.""" if not self._preferences_view: self._preferences_view = PreferencesView(self) return self._preferences_view def show_preferences_dialog(self): """ Show the preferences dialog. This is a convenience function. """ self.get_preferences_controller().run() def get_save_model(self): """Return the L{SaveModel} component.""" if not self._save_model: self._save_model = SaveModel(self) return self._save_model def get_save_controller(self): """Return the L{SaveController} component.""" if not self._save_controller: self._save_controller = SaveController(self) return self._save_controller def get_save_view(self): """Return the L{SaveView} component.""" if not self._save_view: self._save_view = SaveView(self) return self._save_view def show_save_dialog(self): """ Show the save dialog. This is a convenience function. """ self.get_save_controller().run() def get_about_controller(self): """Return the L{SaveController} component.""" if not self._about_controller: self._about_controller = AboutController(self) return self._about_controller def get_about_view(self): """Return the L{SaveView} component.""" if not self._about_view: self._about_view = AboutView(self) return self._about_view def show_about_dialog(self): """ Show the about dialog. This is a convenience function. """ self.get_about_controller().run() diff --git a/nostaples b/nostaples index cb3c439..5d0b5f9 100755 --- a/nostaples +++ b/nostaples @@ -1,98 +1,169 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. ''' -This module parses command line options and bootstraps the NoStaples -application. +This module parses command line options, checks that imports are available, +and bootstraps the NoStaples application. ''' import optparse import sys +import pygtk +pygtk.require('2.0') +import gtk + +# COMMAND LINE PARSING + # Functions to pretty-print debugging info def print_device_debug(i, device): """Pretty-print device information.""" print 'Device %i' % i print '' print 'Name:\t%s' % device.name print 'Vendor:\t%s' % device.vendor print 'Model:\t%s' % device.model print 'Type:\t%s' % device.type print '' try: device.open() j = 1 for option in device.options.values(): print_option_debug(j, option) print '' j = j + 1 device.close() except Exception: print '\t**Failed to open device.**' def print_option_debug(j, option): """Pretty-print device option information.""" print '\tOption %i' % j print '' print '\tName:\t%s' % option._name print '\tTitle:\t%s' % option._title print '\tDesc:\t%s' % option._description print '\tType:\t%s' % option._type print '\tUnit:\t%s' % option._unit print '\tSize:\t%s' % option._size print '\tCap:\t%s' % option._capabilities print '\tConstraint Type:\t%s' % option._constraint_type print '\tConstraint:\t', option._constraint try: print '\tValue:\t%s' % str(option.value) except Exception: print '\t**Failed to get current value for option.**' # Parse command line options parser = optparse.OptionParser() parser.add_option("--debugdevices", action="store_true", dest="debug_devices", help="print debugging information for all connected devices") (options, args) = parser.parse_args() if options.debug_devices: import nostaples.sane as saneme sane_manager = saneme.SaneMe() devices = sane_manager.get_device_list() if len(devices) == 0: print 'No devices found.' i = 1 for device in devices: print_device_debug(i, device) print '' i = i + 1 sys.exit() + +# CHECK IMPORT VERSIONS + +def display_import_error(message): + """ + Displays a GTK message dialog containing the import error and then + exits the application. + """ + dialog = gtk.MessageDialog( + parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_NONE) + dialog.set_title('') + + primary = "<big><b>A required package is not installed.</b></big>" + secondary = '%s' % message + + dialog.set_markup(primary) + dialog.format_secondary_markup(secondary) + + dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) + + response = dialog.run() + dialog.destroy() + + sys.exit() + +# Python +if sys.version_info < (2, 5) or sys.version_info >= (3, 0): + display_import_error( + 'NoStaples requires Python version 2.5 or later (but not version 3.0 or later).') -# Bootstrap application +# GTK +if gtk.gtk_version < (2, 6, 0): + display_import_error( + 'NoStaples requires GTK+ version 2.6 or later.') + +if gtk.pygtk_version < (2, 8, 0): + display_import_error( + 'NoStaples requires PyGTK version 2.8 or later.') + +# PIL +try: + import Image +except ImportError: + display_import_error( + 'NoStaples requires the Python Imaging Library (PIL) 1.1.6 or later.') + +pil_version = tuple([int(i) for i in Image.VERSION.split('.')]) + +if pil_version < (1, 1, 6): + display_import_error( + 'NoStaples requires the Python Imaging Library (PIL) version 1.1.6 or later.') + +# ReportLab +try: + import reportlab +except ImportError: + display_import_error( + 'NoStaples requires ReportLab version 2.1 or later.') + +reportlab_version = tuple([int(i) for i in reportlab.Version.split('.')]) + +if reportlab_version < (2, 1): + display_import_error( + 'NoStaples requires ReportLab version 2.1 or later.') + +# BOOTSTRAP + from nostaples.application import Application nostaples = Application() nostaples.run() \ No newline at end of file
onyxfish/nostaples
1f1c87e90dda9ece6d49684a0e3d6b3a203e45fd
Added import guards for all dependencies.
diff --git a/application.py b/application.py index 5a78943..f83a15c 100644 --- a/application.py +++ b/application.py @@ -1,333 +1,404 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds NoStaples' main method which handles the instantiation of MVC objects and then starts the gtk main loop. """ import logging.config import os +import sys +import pygtk +pygtk.require('2.0') import gtk from nostaples import constants from nostaples.controllers.about import AboutController from nostaples.controllers.document import DocumentController from nostaples.controllers.main import MainController from nostaples.controllers.page import PageController from nostaples.controllers.preferences import PreferencesController from nostaples.controllers.save import SaveController from nostaples.controllers.status import StatusController from nostaples.models.document import DocumentModel from nostaples.models.main import MainModel from nostaples.models.page import PageModel from nostaples.models.preferences import PreferencesModel from nostaples.models.save import SaveModel from nostaples.models.status import StatusModel import nostaples.sane as saneme import nostaples.utils.gtkexcepthook from nostaples.utils.state import GConfStateManager from nostaples.views.about import AboutView from nostaples.views.document import DocumentView from nostaples.views.main import MainView from nostaples.views.page import PageView from nostaples.views.preferences import PreferencesView from nostaples.views.save import SaveView from nostaples.views.status import StatusView class Application(object): """ A 'front controller' class that stores references to all top-level components of the application and facilitates communication between them. A reference to this class is injected into each controller component of the application via its constructor. These components then query the application object when they need to access other parts of the system. """ _state_manager = None _sane = None _main_model = None _main_controller = None _main_view = None _document_model = None _document_controller = None _document_view = None _null_page_model = None _page_controller = None _page_view = None _status_model = None _status_controller = None _status_view = None _preferences_model = None _preferences_controller = None _preferences_view = None _save_model = None _save_controller = None _save_view = None _about_controller = None _about_view = None def __init__(self): """ Set up the config directory, logging, and state persistence. Construct the Main MVC component triplet (which will in turn construct all sub components). Per """ + self._check_import_versions() self._init_config() self._init_logging() self._init_state() self._init_sane() self._init_main_components() self._init_settings() + + def _check_import_versions(self): + """ + Attempt to import all dependencies and check that supported versions + are available. + """ + # Python + if sys.version_info < (2, 5) or sys.version_info >= (3, 0): + self._display_import_error( + 'NoStaples requires Python version 2.5 or later (but not version 3.0 or later).') + + # GTK + if gtk.gtk_version < (2, 6, 0): + self._display_import_error( + 'NoStaples requires GTK+ version 2.6 or later.') + + if gtk.pygtk_version < (2, 8, 0): + self._display_import_error( + 'NoStaples requires PyGTK version 2.8 or later.') + + # PIL + try: + import Image + except ImportError: + self._display_import_error( + 'NoStaples requires the Python Imaging Library (PIL) 1.1.6 or later.') + + pil_version = tuple([int(i) for i in Image.VERSION.split('.')]) + + if pil_version < (1, 1, 6): + self._display_import_error( + 'NoStaples requires the Python Imaging Library (PIL) version 1.1.6 or later.') + + # ReportLab + try: + import reportlab + except ImportError: + self._display_import_error( + 'NoStaples requires ReportLab version 2.1 or later.') + + reportlab_version = tuple([int(i) for i in reportlab.Version.split('.')]) + + if reportlab_version < (2, 1): + self._display_import_error( + 'NoStaples requires ReportLab version 2.1 or later.') + + def _display_import_error(self, message): + """ + Displays a GTK message dialog containing the import error and then + exits the application. + """ + dialog = gtk.MessageDialog( + parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_NONE) + dialog.set_title('') + + primary = "<big><b>A required package is not installed.</b></big>" + secondary = '%s' % message + + dialog.set_markup(primary) + dialog.format_secondary_markup(secondary) + + dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) + + response = dialog.run() + dialog.destroy() + + sys.exit() def _init_config(self): """Setup the config directory.""" - if not os.path.exists(constants.TEMP_IMAGES_DIRECTORY): - os.mkdir(constants.TEMP_IMAGES_DIRECTORY) + if not os.path.exists(constants.APP_DIRECTORY): + os.mkdir(constants.APP_DIRECTORY) def _init_logging(self): """Setup logging for the application.""" logging.config.fileConfig(constants.LOGGING_CONFIG) def _init_state(self): """Setup the state manager.""" self._state_manager = GConfStateManager() def _init_sane(self): """Setup SANE.""" self._sane = saneme.SaneMe(logging.getLogger("saneme")) def _init_main_components(self): """ Create the main application components, which will request creation of other components as necessary. """ self._main_model = MainModel(self) self._main_controller = MainController(self) self._main_view = MainView(self) def _init_settings(self): """ Load current settings from the state manager and poll for available scanners. """ self._main_model.load_state() self.get_save_model().load_state() self.get_preferences_model().load_state() self._main_controller._update_available_scanners() # PUBLIC METHODS def run(self): """Execute the GTK main loop.""" assert isinstance(self._main_view, MainView) self._main_view.show() gtk.main() def get_state_manager(self): """Return the L{GConfStateManager} component.""" assert isinstance(self._state_manager, GConfStateManager) return self._state_manager def get_sane(self): """Return the SaneMe object.""" assert isinstance(self._sane, saneme.SaneMe) return self._sane def get_main_model(self): """Return the L{MainModel} component.""" assert self._main_model return self._main_model def get_main_controller(self): """Return the L{MainController} component.""" assert self._main_controller return self._main_controller def get_main_view(self): """Return the L{MainView} component.""" assert self._main_view return self._main_view def get_document_model(self): """Return the L{DocumentModel} component.""" if not self._document_model: self._document_model = DocumentModel(self) return self._document_model def get_document_controller(self): """Return the L{DocumentController} component.""" if not self._document_controller: self._document_controller = DocumentController(self) return self._document_controller def get_document_view(self): """Return the L{DocumentView} component.""" if not self._document_view: self._document_view = DocumentView(self) return self._document_view def get_null_page_model(self): """ Return an empty L{PageModel} object. This is the PageModel that is used when no pages have been scanned. """ if not self._null_page_model: self._null_page_model = PageModel(self) return self._null_page_model def get_current_page_model(self): """ Return the current/active L{PageModel} object. This is a convenience function. """ return self.get_page_controller().get_current_page_model() def get_page_controller(self): """Return the L{PageController} component.""" if not self._page_controller: self._page_controller = PageController(self) return self._page_controller def get_page_view(self): """Return the L{PageView} component.""" if not self._page_view: self._page_view = PageView(self) return self._page_view def get_status_model(self): """Return the L{StatusModel} component.""" if not self._status_model: self._status_model = StatusModel(self) return self._status_model def get_status_controller(self): """Return the L{StatusController} component.""" if not self._status_controller: self._status_controller = StatusController(self) return self._status_controller def get_status_view(self): """Return the L{StatusView} component.""" if not self._status_view: self._status_view = StatusView(self) return self._status_view def get_preferences_model(self): """Return the L{PreferencesModel} component.""" if not self._preferences_model: self._preferences_model = PreferencesModel(self) return self._preferences_model def get_preferences_controller(self): """Return the L{PreferencesController} component.""" if not self._preferences_controller: self._preferences_controller = PreferencesController(self) return self._preferences_controller def get_preferences_view(self): """Return the L{PreferencesView} component.""" if not self._preferences_view: self._preferences_view = PreferencesView(self) return self._preferences_view def show_preferences_dialog(self): """ Show the preferences dialog. This is a convenience function. """ self.get_preferences_controller().run() def get_save_model(self): """Return the L{SaveModel} component.""" if not self._save_model: self._save_model = SaveModel(self) return self._save_model def get_save_controller(self): """Return the L{SaveController} component.""" if not self._save_controller: self._save_controller = SaveController(self) return self._save_controller def get_save_view(self): """Return the L{SaveView} component.""" if not self._save_view: self._save_view = SaveView(self) return self._save_view def show_save_dialog(self): """ Show the save dialog. This is a convenience function. """ self.get_save_controller().run() def get_about_controller(self): """Return the L{SaveController} component.""" if not self._about_controller: self._about_controller = AboutController(self) return self._about_controller def get_about_view(self): """Return the L{SaveView} component.""" if not self._about_view: self._about_view = AboutView(self) return self._about_view def show_about_dialog(self): """ Show the about dialog. This is a convenience function. """ self.get_about_controller().run() diff --git a/constants.py b/constants.py index a2a4bb1..89bed8e 100644 --- a/constants.py +++ b/constants.py @@ -1,105 +1,105 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. ''' This module contains global configuration constants that are not likely to change often as well as enumeration-like state constants. ''' import os import gtk import Image from reportlab.lib.pagesizes import A0, A1, A2, A3, A4, A5, A6, \ B0, B1, B2, B3, B4, B5, B6, LETTER, LEGAL, ELEVENSEVENTEEN PAGESIZES = {'A0' : A0, 'A1' : A1, 'A2' : A2, 'A3' : A3, 'A4' : A4, 'A5' : A5, 'A6' : A6, 'B0' : B0, 'B1' : B1, 'B2' : B2, 'B3' : B3, 'B4' : B4, 'B5' : B5, 'B6' : B6, 'LETTER' : LETTER, 'LEGAL' : LEGAL, 'ELEVENSEVENTEEN' : ELEVENSEVENTEEN} DEFAULT_SHOW_TOOLBAR = True DEFAULT_SHOW_STATUSBAR = True DEFAULT_SHOW_THUMBNAILS = True DEFAULT_SHOW_ADJUSTMENTS = False DEFAULT_ROTATE_ALL_PAGES = False DEFAULT_ACTIVE_SCANNER = '' DEFAULT_SCAN_MODE = 'Color' DEFAULT_SCAN_RESOLUTION = '75' DEFAULT_SAVE_PATH = '' DEFAULT_AUTHOR = os.getenv('LOGNAME') DEFAULT_SAVED_KEYWORDS = [] DEFAULT_PREVIEW_MODE = 'Bilinear (Default)' DEFAULT_THUMBNAIL_SIZE = 128 DEFAULT_SHOW_DOCUMENT_METADATA = True DEFAULT_BLACKLISTED_SCANNERS = [] THUMBNAILS_SCALING_MODE = Image.ANTIALIAS MAX_VALID_OPTION_VALUES = 11 SCAN_CANCELLED = -1 SCAN_FAILURE = 0 SCAN_SUCCESS = 1 RESPONSE_BLACKLIST_DEVICE = 1 GCONF_DIRECTORY = '/apps/nostaples' GCONF_TUPLE_SEPARATOR = '|' GCONF_LIST_SEPARATOR = '^' # TODO: rename to CONFIG_DIRECTORY -TEMP_IMAGES_DIRECTORY = os.path.expanduser('~/.nostaples') +APP_DIRECTORY = os.path.expanduser('~/.nostaples') LOGGING_CONFIG = os.path.join(os.path.dirname(__file__), 'logging.config') GUI_DIRECTORY = os.path.join(os.path.dirname(__file__), 'gui') PREVIEW_MODES = \ { 'Nearest (Fastest)': gtk.gdk.INTERP_NEAREST, 'Tiles': gtk.gdk.INTERP_TILES, 'Bilinear (Default)': gtk.gdk.INTERP_BILINEAR, 'Antialias (Smoothest)': gtk.gdk.INTERP_HYPER } PREVIEW_MODES_LIST = \ [ 'Nearest (Fastest)', 'Tiles', 'Bilinear (Default)', 'Antialias (Smoothest)' ] THUMBNAIL_SIZE_LIST = \ [ 32, 64, 128, 256 ] \ No newline at end of file diff --git a/views/main.py b/views/main.py index cfa8f26..d6ecf17 100644 --- a/views/main.py +++ b/views/main.py @@ -1,182 +1,178 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainView which exposes the application's main window. """ import logging import os import gtk from gtkmvc.view import View from nostaples import constants class MainView(View): """ Exposes the application's main window. """ def __init__(self, application): """ Constructs the MainView, including setting up controls that could not be configured in Glade and constructing sub-views. """ self.application = application scan_window_glade = os.path.join( constants.GUI_DIRECTORY, 'scan_window.glade') View.__init__( self, application.get_main_controller(), scan_window_glade, ['scan_window', 'progress_window'], None, False) self.log = logging.getLogger(self.__class__.__name__) # Setup controls which can not be configured in Glade self['scan_window'].set_geometry_hints(min_width=600, min_height=400) # Setup sub views document_view = self.application.get_document_view() document_view['document_view_horizontal_box'].reparent( self['document_view_docking_viewport']) self['document_view_docking_viewport'].show_all() status_view = self.application.get_status_view() status_view['statusbar'].reparent( self['status_view_docking_viewport']) self['status_view_docking_viewport'].show_all() # All controls are disabled by default, they become # avaiable when an event indicates that they should be. self.set_scan_controls_sensitive(False) self.set_file_controls_sensitive(False) self.set_delete_controls_sensitive(False) self.set_zoom_controls_sensitive(False) self.set_adjustment_controls_sensitive(False) self.set_navigation_controls_sensitive(False) document_view.set_adjustments_sensitive(False) application.get_main_controller().register_view(self) self.log.debug('Created.') def set_file_controls_sensitive(self, sensitive): """ Enables or disables all gui widgets related to saving. """ self['save_as_menu_item'].set_sensitive(sensitive) self['save_as_button'].set_sensitive(sensitive) def set_scan_controls_sensitive(self, sensitive): """ Enables or disables all gui widgets related to scanning and setting of scanner options. """ self['scan_menu_item'].set_sensitive(sensitive) self['scan_button'].set_sensitive(sensitive) self['scanner_menu_item'].set_sensitive(sensitive) self['scan_mode_menu_item'].set_sensitive(sensitive) self['scan_resolution_menu_item'].set_sensitive(sensitive) def set_refresh_scanner_controls_sensitive(self, sensitive): """ Enable or disable all gui widgets related to refreshing the available hardware for scanning. """ self['refresh_available_scanners_menu_item'].set_sensitive(sensitive) self['refresh_available_scanners_button'].set_sensitive(sensitive) def set_delete_controls_sensitive(self, sensitive): """ Enables or disables all gui widgets related to deleting or reordering pages. """ self['delete_menu_item'].set_sensitive(sensitive) def set_zoom_controls_sensitive(self, sensitive): """ Enables or disables all gui widgets related to zooming. """ self['zoom_in_menu_item'].set_sensitive(sensitive) self['zoom_out_menu_item'].set_sensitive(sensitive) self['zoom_one_to_one_menu_item'].set_sensitive(sensitive) self['zoom_best_fit_menu_item'].set_sensitive(sensitive) self['zoom_in_button'].set_sensitive(sensitive) self['zoom_out_button'].set_sensitive(sensitive) self['zoom_one_to_one_button'].set_sensitive(sensitive) self['zoom_best_fit_button'].set_sensitive(sensitive) def set_adjustment_controls_sensitive(self, sensitive): """ Enables or disables all gui widgets related to making adjustments to the current page. """ self['rotate_counter_clockwise_menu_item'].set_sensitive(sensitive) self['rotate_clockwise_menu_item'].set_sensitive(sensitive) self['rotate_all_pages_menu_item'].set_sensitive(sensitive) self['rotate_counter_clockwise_button'].set_sensitive(sensitive) self['rotate_clockwise_button'].set_sensitive(sensitive) self.application.get_document_view().set_adjustments_sensitive(sensitive) def set_navigation_controls_sensitive(self, sensitive): """ Enables or disables all gui widgets related to navigation. """ self['go_first_menu_item'].set_sensitive(sensitive) self['go_previous_menu_item'].set_sensitive(sensitive) self['go_next_menu_item'].set_sensitive(sensitive) self['go_last_menu_item'].set_sensitive(sensitive) self['go_first_button'].set_sensitive(sensitive) self['go_previous_button'].set_sensitive(sensitive) self['go_next_button'].set_sensitive(sensitive) self['go_last_button'].set_sensitive(sensitive) def run_device_exception_dialog(self, exc_info): """ Display an error dialog that provides the user with the option of blacklisting the device which caused the error. TODO: Rebuild dialog in Glade. """ dialog = gtk.MessageDialog( parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_NONE) dialog.set_title('') - - # TODO: is this needed? - if gtk.check_version (2, 4, 0) is not None: - dialog.set_has_separator (False) primary = "<big><b>A hardware exception has been logged.</b></big>" secondary = '<b>Device:</b> %s\n<b>Exception:</b> %s\n\n%s' % ( exc_info[1].device.display_name, exc_info[1].message, 'If this error continues to occur you may choose to blacklist the device so that it no longer appears in the list of available scanners.') dialog.set_markup(primary) dialog.format_secondary_markup(secondary) dialog.add_button('Blacklist Device', constants.RESPONSE_BLACKLIST_DEVICE) dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) response = dialog.run() dialog.destroy() return response \ No newline at end of file
onyxfish/nostaples
f8e4be136cac5661ce16f184fd4c9dc1bf2b1d4e
Fix bad constant.
diff --git a/constants.py b/constants.py index f0af9fc..a2a4bb1 100644 --- a/constants.py +++ b/constants.py @@ -1,105 +1,105 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. ''' This module contains global configuration constants that are not likely to change often as well as enumeration-like state constants. ''' import os import gtk import Image from reportlab.lib.pagesizes import A0, A1, A2, A3, A4, A5, A6, \ B0, B1, B2, B3, B4, B5, B6, LETTER, LEGAL, ELEVENSEVENTEEN PAGESIZES = {'A0' : A0, 'A1' : A1, 'A2' : A2, 'A3' : A3, 'A4' : A4, 'A5' : A5, 'A6' : A6, 'B0' : B0, 'B1' : B1, 'B2' : B2, 'B3' : B3, 'B4' : B4, 'B5' : B5, 'B6' : B6, 'LETTER' : LETTER, 'LEGAL' : LEGAL, 'ELEVENSEVENTEEN' : ELEVENSEVENTEEN} DEFAULT_SHOW_TOOLBAR = True DEFAULT_SHOW_STATUSBAR = True DEFAULT_SHOW_THUMBNAILS = True DEFAULT_SHOW_ADJUSTMENTS = False DEFAULT_ROTATE_ALL_PAGES = False DEFAULT_ACTIVE_SCANNER = '' DEFAULT_SCAN_MODE = 'Color' DEFAULT_SCAN_RESOLUTION = '75' DEFAULT_SAVE_PATH = '' DEFAULT_AUTHOR = os.getenv('LOGNAME') DEFAULT_SAVED_KEYWORDS = [] DEFAULT_PREVIEW_MODE = 'Bilinear (Default)' DEFAULT_THUMBNAIL_SIZE = 128 DEFAULT_SHOW_DOCUMENT_METADATA = True DEFAULT_BLACKLISTED_SCANNERS = [] THUMBNAILS_SCALING_MODE = Image.ANTIALIAS -MAX_VALID_OPTION_VALUES = 4 +MAX_VALID_OPTION_VALUES = 11 SCAN_CANCELLED = -1 SCAN_FAILURE = 0 SCAN_SUCCESS = 1 RESPONSE_BLACKLIST_DEVICE = 1 GCONF_DIRECTORY = '/apps/nostaples' GCONF_TUPLE_SEPARATOR = '|' GCONF_LIST_SEPARATOR = '^' # TODO: rename to CONFIG_DIRECTORY TEMP_IMAGES_DIRECTORY = os.path.expanduser('~/.nostaples') LOGGING_CONFIG = os.path.join(os.path.dirname(__file__), 'logging.config') GUI_DIRECTORY = os.path.join(os.path.dirname(__file__), 'gui') PREVIEW_MODES = \ { 'Nearest (Fastest)': gtk.gdk.INTERP_NEAREST, 'Tiles': gtk.gdk.INTERP_TILES, 'Bilinear (Default)': gtk.gdk.INTERP_BILINEAR, 'Antialias (Smoothest)': gtk.gdk.INTERP_HYPER } PREVIEW_MODES_LIST = \ [ 'Nearest (Fastest)', 'Tiles', 'Bilinear (Default)', 'Antialias (Smoothest)' ] THUMBNAIL_SIZE_LIST = \ [ 32, 64, 128, 256 ] \ No newline at end of file
onyxfish/nostaples
b79cb38384d1ac1abebc9c5caa7046abbf5a42c5
Reworked set_prop_active_scanner to push settings to new device silently.
diff --git a/models/main.py b/models/main.py index 20f16b1..63b1ae4 100644 --- a/models/main.py +++ b/models/main.py @@ -1,425 +1,450 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme import nostaples.utils.properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() + # Update the internal property variable + self._prop_active_scanner = value + # Only persist the state if the new value is not None # and it's option constraints can be queried without error. if value is not None: # Verify that the proper type is being set assert isinstance(value, saneme.Device) # Open the new scanner try: value.open() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Load the option constraints (valid_modes, etc.) for the new device self._load_scanner_option_constraints(value) + # Manually constrain option values + if self._prop_active_mode not in self._prop_valid_modes: + self._prop_active_mode = self._prop_valid_modes[0] + + if self._prop_active_resolution not in self._prop_valid_resolutions: + self._prop_active_resolution = self._prop_valid_resolutions[0] + + # Manually push option values to new device + try: + try: + value.options['mode'].value = self._prop_active_mode + except saneme.SaneReloadOptionsError: + pass + + try: + value.options['resolution'].value = \ + int(self._prop_active_resolution) + except saneme.SaneReloadOptionsError: + pass + except saneme.SaneError: + exc_info = sys.exc_info() + main_controller.run_device_exception_dialog(exc_info) + + # Emit change notifications for manually updated properties + + self.notify_property_value_change( + 'valid_modes', None, self.valid_modes) + + self.notify_property_value_change( + 'valid_resolutions', None, self.valid_resolutions) + + self.notify_property_value_change( + 'active_mode', None, self.active_mode) + + self.notify_property_value_change( + 'active_resolution', None, self.active_resolution) + # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name - # Update the internal property variable - self._prop_active_scanner = value - - # Emit the property change notification + # Emit the property change notifications self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() + + # Set new property value + self._prop_active_mode = value # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value self.active_scanner.options['mode'].value = value except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: - self.application.get_state_manager()['scan_mode'] = value - - # Set new property value - self._prop_active_mode = value + self.application.get_state_manager()['scan_mode'] = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() + # Set new property value + self._prop_active_resolution = value + # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value self.active_scanner.options['resolution'].value = int(value) except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: - self.application.get_state_manager()['scan_resolution'] = value - - # Set new property value - self._prop_active_resolution = value + self.application.get_state_manager()['scan_resolution'] = value # Emit change notification self.notify_property_value_change( 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ Set the list of available scanners and update the active_scanner. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() self._prop_available_scanners = value - # Force notification self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None - else: - # Select the first available scanner if the previously - # selected scanner is not in the new list - if self._prop_active_scanner not in value: - self.active_scanner = value[0] - # Otherwise maintain current selection - else: - self.active_scanner = self.active_scanner + elif self._prop_active_scanner not in value: + self.active_scanner = value[0] def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) - # Update the active mode if len(value) == 0: self.active_mode = None - else: - if self.active_mode not in value: - self.active_mode = value[0] - else: - self.active_mode = self.active_mode + elif self.active_mode not in value: + self.active_mode = value[0] def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) - - # Update the active resolution + if len(value) == 0: self.active_resolution = None - else: - if self.active_resolution not in value: - self.active_resolution = value[0] - else: - self.active_resolution = self.active_resolution + elif self.active_resolution not in value: + self.active_resolution = value[0] # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution # INTERNAL METHODS def _load_scanner_option_constraints(self, sane_device): """ Load the option constraints from a specified scanner. """ main_controller = self.application.get_main_controller() try: assert sane_device.options['mode'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST - self.valid_modes = sane_device.options['mode'].constraint + self._prop_valid_modes = sane_device.options['mode'].constraint if sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_RANGE: min, max, step = sane_device.options['resolution'].constraint resolutions = [] # If there are not an excessive number, include every possible # resolution if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: i = min while i <= max: resolutions.append(str(i)) i = i + step # Otherwise, take a crack at building a sensible set of options # that mean that constraint criteria else: i = 1 increment = (max - min) / (constants.MAX_VALID_OPTION_VALUES - 1) while (i <= constants.MAX_VALID_OPTION_VALUES - 2): unrounded = min + (i * increment) rounded = int(round(unrounded / step) * step) resolutions.append(str(rounded)) i = i + 1 resolutions.insert(0, str(min)) resolutions.append(str(max)) - self.valid_resolutions = resolutions + self._prop_valid_resolutions = resolutions elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_INTEGER_LIST: - self.valid_resolutions = \ + self._prop_valid_resolutions = \ [str(i) for i in sane_device.options['resolution'].constraint] elif sane_device.options['resolution'].constraint_type == \ saneme.OPTION_CONSTRAINT_STRING_LIST: sane_device.options['resolution'].constraint else: raise AssertionError('Unsupported constraint type.') except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) def _load_scanner_option_values(self): """ Get current scanner options from the active_scanner. Useful for reloading any option that may have changed in response to a SaneReloadOptionsError. """ + main_controller = self.application.get_main_controller() + try: + # TODO: ReloadOptions should reload constraints as well as values! self.active_mode = self.active_scanner.options['mode'].value self.active_resolution = \ str(self.active_scanner.options['resolution'].value) except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) \ No newline at end of file
onyxfish/nostaples
a2b1c1c89422aefd515c46a8bb762b1b6018ba95
Added support methods for getting individual SANE option capabilities.
diff --git a/controllers/main.py b/controllers/main.py index 9a2d914..ffc02df 100644 --- a/controllers/main.py +++ b/controllers/main.py @@ -55,707 +55,715 @@ class MainController(Controller): self.status_context = \ status_controller.get_context_id(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ self.adapt('show_toolbar', 'show_toolbar_menu_item') self.adapt('show_statusbar', 'show_statusbar_menu_item') self.adapt('show_thumbnails', 'show_thumbnails_menu_item') self.adapt('show_adjustments', 'show_adjustments_menu_item') self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS # Menu Items def on_scan_window_destroy(self, window): """Exits the application.""" self.quit() def on_scan_menu_item_activate(self, menu_item): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_menu_item_activate(self, menu_item): """Refresh the list of connected scanners from SANE.""" self._update_available_scanners() def on_save_as_menu_item_activate(self, menu_item): """Saves the current document to a file.""" self.application.show_save_dialog() def on_delete_menu_item_activate(self, menu_item): self.application.get_document_controller().delete_selected() def on_preferences_menu_item_activate(self, menu_item): """Creates and displays a preferences dialog.""" self.application.show_preferences_dialog() def on_quit_menu_item_activate(self, menu_item): """Exits the application.""" self.quit() def on_zoom_in_menu_item_activate(self, menu_item): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_menu_item_activate(self, menu_item): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_menu_item_activate(self, menu_item): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_menu_item_activate(self, menu_item): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_available_scanner_menu_item_toggled(self, menu_item): """ Set the active scanner. TODO: Need a second scanner to properly test this... """ main_model = self.application.get_main_model() if menu_item.get_active(): for scanner in main_model.available_scanners: if scanner.display_name == menu_item.get_children()[0].get_text(): main_model.active_scanner = scanner return def on_valid_mode_menu_item_toggled(self, menu_item): """Sets the active scan mode.""" if menu_item.get_active(): self.application.get_main_model().active_mode = \ menu_item.get_children()[0].get_text() def on_valid_resolution_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_resolution = \ menu_item.get_children()[0].get_text() def on_go_first_menu_item_activate(self, menu_item): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_menu_item_activate(self, menu_item): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_menu_item_activate(self, menu_item): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_menu_item_activate(self, menu_item): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() def on_contents_menu_item_clicked(self, menu_item): """TODO""" pass def on_about_menu_item_activate(self, menu_item): """Show the about dialog.""" self.application.show_about_dialog() # Toolbar Buttons def on_scan_button_clicked(self, button): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_button_clicked(self, button): self._update_available_scanners() def on_save_as_button_clicked(self, button): """Saves the current document to a file.""" self.application.show_save_dialog() def on_zoom_in_button_clicked(self, button): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_button_clicked(self, button): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_button_clicked(self, button): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_button_clicked(self, button): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_go_first_button_clicked(self, button): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_button_clicked(self, button): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_button_clicked(self, button): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_button_clicked(self, button): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() # Progress Window INTERFACE CALLBACKS def on_progress_window_delete_event(self, window, event): """ Emulate clicking of the cancel/close button and then hide the window. """ main_view = self.application.get_main_view() self.on_scan_cancel_button_clicked(None) main_view['progress_window'].hide() return True def on_scan_cancel_button_clicked(self, button): """ Cancel the current scan or, if the scan is finished, close the progress window. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress: assert self.cancel_event self.cancel_event.set() else: main_view['progress_window'].hide() def on_scan_again_button_clicked(self, button): """Initiate a new scan from the progress window.""" self._scan() def on_quick_save_button_clicked(self, button): """ Show the save dialog. If the user completes a save then disable the quick save button until another page is scanned. """ main_view = self.application.get_main_view() document_model = self.application.get_document_model() self.application.show_save_dialog() if document_model.count == 0: main_view['quick_save_button'].set_sensitive(False) # MainModel PROPERTY CALLBACKS def property_show_toolbar_value_change(self, model, old_value, new_value): """Update the visibility of the toolbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_toolbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['main_toolbar'].show() else: main_view['main_toolbar'].hide() def property_show_statusbar_value_change(self, model, old_value, new_value): """Update the visibility of the statusbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_statusbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['status_view_docking_viewport'].show() else: main_view['status_view_docking_viewport'].hide() def property_show_thumbnails_value_change(self, model, old_value, new_value): """Update the visibility of the thumbnails.""" main_view = self.application.get_main_view() menu_item = main_view['show_thumbnails_menu_item'] menu_item.set_active(new_value) self.application.get_document_controller().toggle_thumbnails_visible(new_value) def property_show_adjustments_value_change(self, model, old_value, new_value): """Update the visibility of the adjustments controls.""" document_controller = self.application.get_document_controller() main_view = self.application.get_main_view() menu_item = main_view['show_adjustments_menu_item'] menu_item.set_active(new_value) document_controller.toggle_adjustments_visible(new_value) def property_active_scanner_value_change(self, model, old_value, new_value): """ Update the menu and valid scanner options to match the new device. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() if new_value == None: return for menu_item in main_view['scanner_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value.display_name: menu_item.set_active(True) break def property_active_mode_value_change(self, model, old_value, new_value): """Select the active mode from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_mode_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_resolution_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() if new_value == None: return for menu_item in main_view['scan_resolution_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_available_scanners_value_change(self, model, old_value, new_value): """ Update the menu of available scanners. """ main_view = self.application.get_main_view() self._clear_available_scanners_sub_menu() # Generate the new menu if len(new_value) == 0: menu_item = gtk.MenuItem('No Scanners Connected') menu_item.set_sensitive(False) main_view['scanner_sub_menu'].append(menu_item) else: first_item = None for i in range(len(new_value)): # The first menu item defines the group if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i].display_name) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i].display_name) main_view['scanner_sub_menu'].append(menu_item) main_view['scanner_sub_menu'].show_all() def property_valid_modes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan modes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_modes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Modes") menu_item.set_sensitive(False) main_view['scan_mode_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled) main_view['scan_mode_sub_menu'].append(menu_item) main_view['scan_mode_sub_menu'].show_all() def property_valid_resolutions_value_change(self, model, old_value, new_value): """ Updates the list of valid scan resolutions for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_resolutions_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Resolutions") menu_item.set_sensitive(False) main_view['scan_resolution_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled) main_view['scan_resolution_sub_menu'].append(menu_item) main_view['scan_resolution_sub_menu'].show_all() def property_scan_in_progress_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() def property_updating_available_scanners_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() # DocumentModel PROPERTY CALLBACKS def property_count_value_change(self, model, old_value, new_value): """Toggle available controls.""" self._toggle_document_controls() # THREAD CALLBACKS def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned): main_view = self.application.get_main_view() short_bytes_scanned = float(bytes_scanned) / 1000 short_total_bytes = float(scan_info.total_bytes) / 1000 main_view['scan_progressbar'].set_fraction( float(bytes_scanned) / scan_info.total_bytes) main_view['scan_progressbar'].set_text( 'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes)) # TODO: multi page scans main_view['progress_secondary_label'].set_markup( '<i>Scanning page.</i>') def on_scan_succeeded(self, scanning_thread, pil_image): """ Append the new page to the current document. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['scan_progressbar'].set_fraction(1) main_view['scan_progressbar'].set_text('Scan complete') main_view['progress_secondary_label'].set_markup( '<i>Adding page to document.</i>') gtk.gdk.flush() new_page = PageModel(self.application, pil_image, int(main_model.active_resolution)) self.application.get_document_model().append(new_page) main_view['progress_secondary_label'].set_markup( '<i>Page added.</i>') main_view['scan_again_button'].set_sensitive(True) main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_failed(self, scanning_thread, reason): """ Set that scan is complete. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['progress_secondary_label'].set_markup( '<i>%s</i>' % reason) main_view['scan_again_button'].set_sensitive(True) if self.application.get_document_model().count > 0: main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_aborted(self, scanning_thread, exc_info): """ Change display to indicate that scanning failed and convey the to the user the reason why the thread aborted. If the failure was from a SANE exception then give the user the option to blacklist the device. If not, then reraise the error and let the sys.excepthook deal with it. """ self.on_scan_failed(scanning_thread, 'An error occurred.') if isinstance(exc_info[1], saneme.SaneError): self.run_device_exception_dialog(exc_info) else: raise exc_info[0], exc_info[1], exc_info[2] def on_update_available_scanners_thread_finished(self, update_thread, scanner_list): """Set the new list of available scanners.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() status_controller = self.application.get_status_controller() # Remove blacklisted scanners scanner_list = \ [scanner for scanner in scanner_list if not \ scanner.display_name in preferences_model.blacklisted_scanners] # Remove scanners that do not support necessary options or fail to # open entirely preferences_model.unavailable_scanners = [] - + + def is_supported_option(option): + """Verify an option supports necessary capabilities to be useful.""" + return option.is_active() and \ + option.is_soft_gettable() and \ + option.is_soft_settable() + for scanner in scanner_list: try: scanner.open() - + if not scanner.has_option('mode') or \ - not scanner.has_option('resolution'): + not is_supported_option(scanner.options['mode']) or \ + not scanner.has_option('resolution') or \ + not is_supported_option(scanner.options['resolution']): preferences_model.unavailable_scanners.append(scanner.display_name) scanner_list.remove(scanner) scanner.close() except saneme.SaneError: preferences_model.unavailable_scanners.append(scanner.display_name) scanner_list.remove(scanner) main_model.available_scanners = scanner_list main_model.updating_available_scanners = False def on_update_available_scanners_thread_aborted(self, update_thread, exc_info): """ Change the display to indicate that no scanners are available and reraise the exception so that it can be caught by the sys.excepthook. There is no reason to handle these cases with a special dialog, if the application failed to even enumerate the available devices then no other action will be possible. This should be fantastically rare. """ self.on_update_available_scanners_thread_finished(update_thread, []) raise exc_info[0], exc_info[1], exc_info[2] # PUBLIC METHODS def quit(self): """Exits the application.""" self.log.debug('Quit.') gtk.main_quit() def run_device_exception_dialog(self, exc_info): """ Display an error dialog that provides the user with the option of blacklisting the device which caused the error. TODO: Move into MainView. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() preferences_model = self.application.get_preferences_model() response = main_view.run_device_exception_dialog(exc_info) if response == constants.RESPONSE_BLACKLIST_DEVICE: temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(exc_info[1].device.display_name) temp_blacklist.sort() preferences_model.blacklisted_scanners = temp_blacklist # PRIVATE METHODS def _clear_available_scanners_sub_menu(self): """Clear the menu of available scanners.""" main_view = self.application.get_main_view() for child in main_view['scanner_sub_menu'].get_children(): main_view['scanner_sub_menu'].remove(child) def _clear_scan_modes_sub_menu(self): """Clear the menu of valid scan modes.""" main_view = self.application.get_main_view() for child in main_view['scan_mode_sub_menu'].get_children(): main_view['scan_mode_sub_menu'].remove(child) def _clear_scan_resolutions_sub_menu(self): """Clear the menu of valid scan resolutions.""" main_view = self.application.get_main_view() for child in main_view['scan_resolution_sub_menu'].get_children(): main_view['scan_resolution_sub_menu'].remove(child) def _toggle_scan_controls(self): """Toggle whether or not the scan controls or accessible.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_scan_controls_sensitive(False) main_view.set_refresh_scanner_controls_sensitive(False) else: if main_model.active_scanner != None: main_view.set_scan_controls_sensitive(True) main_view.set_refresh_scanner_controls_sensitive(True) def _toggle_document_controls(self): """ Toggle available document controls based on the current scanner status and the number of scanned pages. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() # Disable all controls when the scanner is in use if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: count = self.application.get_document_model().count # Disable all controls if no pages are scanned if count == 0: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: # Enable most controls if any pages scanned main_view.set_file_controls_sensitive(True) main_view.set_delete_controls_sensitive(True) main_view.set_zoom_controls_sensitive(True) main_view.set_adjustment_controls_sensitive(True) # Only enable navigation if more than one page scanned if count > 1: main_view.set_navigation_controls_sensitive(True) else: main_view.set_navigation_controls_sensitive(False) def _update_status(self): """ Update the text of the statusbar based on the current state of the application. """ main_model = self.application.get_main_model() status_controller = self.application.get_status_controller() status_controller.pop(self.status_context) if main_model.scan_in_progress: status_controller.push(self.status_context, 'Scanning...') elif main_model.updating_available_scanners: status_controller.push(self.status_context, 'Querying hardware...') else: if main_model.active_scanner: status_controller.push(self.status_context, 'Ready with %s.' % main_model.active_scanner.display_name) else: status_controller.push(self.status_context, 'No scanner available.') def _scan(self): """Begin a scan.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() main_model.scan_in_progress = True scanning_thread = ScanningThread(main_model.active_scanner) scanning_thread.connect("progress", self.on_scan_progress) scanning_thread.connect("succeeded", self.on_scan_succeeded) scanning_thread.connect("failed", self.on_scan_failed) scanning_thread.connect("aborted", self.on_scan_aborted) self.cancel_event = scanning_thread.cancel_event main_view['progress_primary_label'].set_markup( '<big><b>%s</b></big>' % main_model.active_scanner.display_name) main_view['scan_progressbar'].set_fraction(0) main_view['scan_progressbar'].set_text('Waiting for data') main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>') mode = main_model.active_mode if main_model.active_mode else 'Not set' main_view['progress_mode_label'].set_markup(mode) dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set' main_view['progress_resolution_label'].set_markup(dpi) main_view['scan_again_button'].set_sensitive(False) main_view['quick_save_button'].set_sensitive(False) main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL) main_view['progress_window'].show_all() scanning_thread.start() def _update_available_scanners(self): """ Start a new update thread to query for available scanners. """ sane = self.application.get_sane() main_model = self.application.get_main_model() main_model.updating_available_scanners = True update_thread = UpdateAvailableScannersThread(sane) update_thread.connect("finished", self.on_update_available_scanners_thread_finished) update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted) update_thread.start() \ No newline at end of file diff --git a/sane/saneme.py b/sane/saneme.py index 30f7161..c0916f5 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -170,810 +170,852 @@ class SaneMe(object): device_count = 0 self._devices = [] while cdevices[device_count]: self._devices.append( Device(cdevices[device_count].contents, self._log)) device_count += 1 if self._log: self._log.info('SANE queried, %i device(s) found.', device_count) return self._devices def get_device_by_name(self, name): """ Retrieve a L{Device} by name. Must be preceded by a call to L{get_device_list}. """ for device in self._devices: if device.name == name: return device raise SaneNoSuchDeviceError( 'The requested device does not exist.') class Device(object): """ This is the primary object for interacting with SANE. It represents a single device and handles enumeration of options, getting and setting of options, and starting and stopping of scanning jobs. """ _log = None _handle = None _name = '' _vendor = '' _model = '' _type = '' _display_name = '' _options = {} def __init__(self, ctypes_device, log=None): """ Sets the Devices properties from a ctypes SANE_Device and queries for its available options. """ self._log = log # String attributes should never be None self._name = ctypes_device.name if ctypes_device.name else '' self._vendor = ctypes_device.vendor if ctypes_device.vendor else '' self._model = ctypes_device.model if ctypes_device.model else '' self._type = ctypes_device.type if ctypes_device.type else '' self._display_name = ' '.join([self._vendor, self._model]) # Read only properties def __get_name(self): """ Get the complete SANE identifier for this device, e.g. 'lexmark:libusb:002:006'. """ return self._name name = property(__get_name) def __get_vendor(self): """Get the manufacturer of this device, e.g. 'Lexmark'.""" return self._vendor vendor = property(__get_vendor) def __get_model(self): """Get the specific model of this device, e.g. 'X1100/rev. B2'.""" return self._model model = property(__get_model) def __get_type(self): """Get the type of this device, e.g. 'flatbed scanner'.""" return self._type type = property(__get_type) def __get_display_name(self): """ Get an appropriate name to use for displaying this device to a user, e.g. 'Lexmark X1100/rev. B2'.""" return self._display_name display_name = property(__get_display_name) def __get_options(self): """Get the dictionary of options that this device has.""" return self._options options = property(__get_options) # Internal methods def _update_options(self): """ Update the list of available options for this device. As these are immutable, this should only need to be called when the Device is first instantiated. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') option_value = pointer(c_int()) status = sane_control_option( self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: raise SaneUnsupportedOperationError( 'sane_control_option reported that a value was outside the option\'s constraint.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) option_count = option_value.contents.value if self._log: self._log.debug('Device queried, %i option(s) found.', option_count) self._options.clear() i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) self._options[coption.contents.name] = Option( self, i, coption.contents, self._log) i = i + 1 # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Public methods def open(self): """ Open a new handle to this device. Must be called before any operations (including getting or setting options) are performed on this device. """ if self._handle: raise AssertionError('device handle already exists.') self._handle = SANE_Handle() status = sane_open(self.name, byref(self._handle)) # If and exception will be thrown, nullify device handle # so is_open() will return false for the device. if status != SANE_STATUS_GOOD.value: self._handle = None if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_open reported that the device was busy.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) self._update_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) def has_option(self, option_name): """Return true if option_name is available for this scanner.""" return (option_name in self.options.keys()) def scan(self, progress_callback=None): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) elif sane_parameters.format == SANE_FRAME_RGB.value: pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capabilities = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number # String attributes should never be None self._name = ctypes_option.name if ctypes_option.name else '' self._title = ctypes_option.title if ctypes_option.title else '' self._description = ctypes_option.desc if ctypes_option.desc else '' self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 else: self._constraint = None # Read only properties def __get_name(self): """ Get the short-form name of this option, e.g. 'mode'. May be an empty string, but never None. """ return self._name name = property(__get_name) def __get_title(self): """ Get the full name of this option, e.g. 'Scan mode'. May be an empty string, but never None. """ return self._title title = property(__get_title) def __get_description(self): """ Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' May be an empty string, but never None. """ return self._description description = property(__get_description) def __get_type(self): + """ + Get the type of this option, e.g. OPTION_TYPE_STRING. + """ return self._type type = property(__get_type) def __get_unit(self): + """ + Get the unit of this option, e.g.OPTION_UNIT_DPI. + """ return self._unit unit = property(__get_unit) - def __get_capability(self): - # TODO: break out into individual capabilities, rather than a bitset - return self._capability - - capability = property(__get_capability) - def __get_constraint_type(self): + """ + Get the type of constraint on this option, e.g. OPTION_CONSTRAINT_RANGE. + """ return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then this is a list of integers which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """value Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option( handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i.' % status, device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value else: option_value = option_value.contents.value if self._log: self._log.debug( 'Option %s queried, its current value is %s.', self._name, option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: raise TypeError( 'option set with %s, expected BooleanType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: raise TypeError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: raise ValueError( 'value for option is longer than max string size') c_value = c_char_p(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: if value < self._constraint[0]: raise ValueError('value for option is less than min.') if value > self._constraint[1]: raise ValueError('value for option is greater than max.') if value % self._constraint[2] != 0: raise ValueError( 'value for option is not divisible by step.') elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i .' % status, device=self._device) if self._log: self._log.debug('Option %s set to value %s.', self._name, value) # Constraint checking ensures this should never happen if info_flags.value & SANE_INFO_INEXACT: raise AssertionError( 'sane_control_option reported that set value was inexact.') # TODO? if info_flags.value & SANE_INFO_RELOAD_PARAMS: pass # See SANE API 4.3.7 if info_flags.value & SANE_INFO_RELOAD_OPTIONS: raise SaneReloadOptionsError() value = property(__get_value, __set_value) + # PUBLIC METHODS + + def is_soft_settable(self): + """ + Returns True if the option can be set by software. + """ + return self._capability & SANE_CAP_SOFT_SELECT + + def is_hard_settable(self): + """ + Returns True if the option can be set by hardware. + """ + return self._capability & SANE_CAP_HARD_SELECT + + def is_soft_gettable(self): + """ + Returns True if the option can be read by software. + """ + return self._capability & SANE_CAP_SOFT_DETECT + + def is_emulated(self): + """ + Returns True if the option is emulated by the backend driver. + """ + return self._capability & SANE_CAP_EMULATED + +# def is_automatic(self): +# return self._capability & SANE_CAP_AUTOMATIC + + def is_active(self): + """ + Returns False if this device is unavailable because of the value + of some other option. + """ + return not self._capability & SANE_CAP_INACTIVE + +# def is_advanced(self): +# return self._capability & SANE_CAP_ADVANCED + class ScanInfo(object): """ Contains the parameters and progress of a scan in progress. """ _width = 0 _height = 0 _depth = 0 _total_bytes = 0 def __init__(self, sane_parameters): """ Initialize the ScanInfo object from the sane_parameters. """ self._width = sane_parameters.pixels_per_line self._height = sane_parameters.lines self._depth = sane_parameters.depth self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines # Read only properties def __get_width(self): """Get the width of the current scan, in pixels.""" return self._width width = property(__get_width) def __get_height(self): """Get the height of the current scan, in pixels.""" return self._height height = property(__get_height) def __get_depth(self): """Get the depth of the current scan, in bits.""" return self._depth depth = property(__get_depth) def __get_total_bytes(self): """Get the total number of bytes comprising this scan.""" return self._total_bytes total_bytes = property(__get_total_bytes) if __name__ == '__main__': def progress_callback(sane_info, bytes_read): #print float(bytes_read) / sane_info.total_bytes pass import logging log_format = FORMAT = "%(message)s" logging.basicConfig(level=logging.DEBUG, format=log_format) sane = SaneMe(logging.getLogger()) devices = sane.get_device_list() for dev in devices: print dev.name devices[0].open() print devices[0].options.keys() try: devices[0].options['mode'].value = 'Gray' except SaneReloadOptionsError: pass try: devices[0].options['resolution'].value = 75 except SaneReloadOptionsError: pass try: devices[0].options['preview'].value = False except SaneReloadOptionsError: pass devices[0].scan(progress_callback).save('out.bmp') devices[0].close() \ No newline at end of file
onyxfish/nostaples
af7d27f8fb8fc0ce4b444c4e021163b42ce2ac4b
Added support for devices that specify there resolution as a range.
diff --git a/constants.py b/constants.py index b4bf349..f0af9fc 100644 --- a/constants.py +++ b/constants.py @@ -1,103 +1,105 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. ''' This module contains global configuration constants that are not likely to change often as well as enumeration-like state constants. ''' import os import gtk import Image from reportlab.lib.pagesizes import A0, A1, A2, A3, A4, A5, A6, \ B0, B1, B2, B3, B4, B5, B6, LETTER, LEGAL, ELEVENSEVENTEEN PAGESIZES = {'A0' : A0, 'A1' : A1, 'A2' : A2, 'A3' : A3, 'A4' : A4, 'A5' : A5, 'A6' : A6, 'B0' : B0, 'B1' : B1, 'B2' : B2, 'B3' : B3, 'B4' : B4, 'B5' : B5, 'B6' : B6, 'LETTER' : LETTER, 'LEGAL' : LEGAL, 'ELEVENSEVENTEEN' : ELEVENSEVENTEEN} DEFAULT_SHOW_TOOLBAR = True DEFAULT_SHOW_STATUSBAR = True DEFAULT_SHOW_THUMBNAILS = True DEFAULT_SHOW_ADJUSTMENTS = False DEFAULT_ROTATE_ALL_PAGES = False DEFAULT_ACTIVE_SCANNER = '' DEFAULT_SCAN_MODE = 'Color' DEFAULT_SCAN_RESOLUTION = '75' DEFAULT_SAVE_PATH = '' DEFAULT_AUTHOR = os.getenv('LOGNAME') DEFAULT_SAVED_KEYWORDS = [] DEFAULT_PREVIEW_MODE = 'Bilinear (Default)' DEFAULT_THUMBNAIL_SIZE = 128 DEFAULT_SHOW_DOCUMENT_METADATA = True DEFAULT_BLACKLISTED_SCANNERS = [] THUMBNAILS_SCALING_MODE = Image.ANTIALIAS +MAX_VALID_OPTION_VALUES = 4 + SCAN_CANCELLED = -1 SCAN_FAILURE = 0 SCAN_SUCCESS = 1 RESPONSE_BLACKLIST_DEVICE = 1 GCONF_DIRECTORY = '/apps/nostaples' GCONF_TUPLE_SEPARATOR = '|' GCONF_LIST_SEPARATOR = '^' # TODO: rename to CONFIG_DIRECTORY TEMP_IMAGES_DIRECTORY = os.path.expanduser('~/.nostaples') LOGGING_CONFIG = os.path.join(os.path.dirname(__file__), 'logging.config') GUI_DIRECTORY = os.path.join(os.path.dirname(__file__), 'gui') PREVIEW_MODES = \ { 'Nearest (Fastest)': gtk.gdk.INTERP_NEAREST, 'Tiles': gtk.gdk.INTERP_TILES, 'Bilinear (Default)': gtk.gdk.INTERP_BILINEAR, 'Antialias (Smoothest)': gtk.gdk.INTERP_HYPER } PREVIEW_MODES_LIST = \ [ 'Nearest (Fastest)', 'Tiles', 'Bilinear (Default)', 'Antialias (Smoothest)' ] THUMBNAIL_SIZE_LIST = \ [ 32, 64, 128, 256 ] \ No newline at end of file diff --git a/models/main.py b/models/main.py index 258981e..20f16b1 100644 --- a/models/main.py +++ b/models/main.py @@ -1,377 +1,425 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme import nostaples.utils.properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) if old_value is not None: assert isinstance(old_value, saneme.Device) if old_value.is_open(): old_value.close() # Only persist the state if the new value is not None - # and it can be opened without error. - # This prevents problems with trying to store a Null - # value in the state backend and also allows for smooth - # transitions if a scanner is disconnected and reconnected. + # and it's option constraints can be queried without error. if value is not None: - try: - # Verify that the proper type is being set - assert isinstance(value, saneme.Device) - + # Verify that the proper type is being set + assert isinstance(value, saneme.Device) + + # Open the new scanner + try: value.open() - - # TODO: ensure these are the expected constraints - # (resolution may be a range) - self.valid_modes = value.options['mode'].constraint - self.valid_resolutions = \ - [str(i) for i in value.options['resolution'].constraint] except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) + + # Load the option constraints (valid_modes, etc.) for the new device + self._load_scanner_option_constraints(value) + # Persist the scanner name self.application.get_state_manager()['active_scanner'] = value.name # Update the internal property variable self._prop_active_scanner = value # Emit the property change notification self.notify_property_value_change( 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['mode'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != value: try: # Set the new option value self.active_scanner.options['mode'].value = value except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_mode'] = value # Set new property value self._prop_active_mode = value # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Check if a valid scanner has been loaded (not None) if isinstance(self.active_scanner, saneme.Device): # The device should always be open if a value is being set assert self.active_scanner.is_open() # Store the current scanner value for comparison try: scanner_value = self.active_scanner.options['resolution'].value except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) # Never re-set a value or set None to a device option if value is not None and scanner_value != int(value): try: # Set the new option value self.active_scanner.options['resolution'].value = int(value) except saneme.SaneReloadOptionsError: # Reload any options that may have changed self._load_scanner_option_values() # Never persist None to state if value is not None: self.application.get_state_manager()['scan_resolution'] = value # Set new property value self._prop_active_resolution = value # Emit change notification self.notify_property_value_change( 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ Set the list of available scanners and update the active_scanner. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() self._prop_available_scanners = value # Force notification self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None else: # Select the first available scanner if the previously # selected scanner is not in the new list if self._prop_active_scanner not in value: self.active_scanner = value[0] # Otherwise maintain current selection else: self.active_scanner = self.active_scanner def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) # Update the active mode if len(value) == 0: self.active_mode = None else: if self.active_mode not in value: self.active_mode = value[0] else: self.active_mode = self.active_mode def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) # Update the active resolution if len(value) == 0: self.active_resolution = None else: if self.active_resolution not in value: self.active_resolution = value[0] else: self.active_resolution = self.active_resolution # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name( state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution # INTERNAL METHODS + + def _load_scanner_option_constraints(self, sane_device): + """ + Load the option constraints from a specified scanner. + """ + main_controller = self.application.get_main_controller() + + try: + assert sane_device.options['mode'].constraint_type == \ + saneme.OPTION_CONSTRAINT_STRING_LIST + + self.valid_modes = sane_device.options['mode'].constraint + + if sane_device.options['resolution'].constraint_type == \ + saneme.OPTION_CONSTRAINT_RANGE: + min, max, step = sane_device.options['resolution'].constraint + + resolutions = [] + + # If there are not an excessive number, include every possible + # resolution + if (max - min) / step <= constants.MAX_VALID_OPTION_VALUES: + i = min + while i <= max: + resolutions.append(str(i)) + i = i + step + # Otherwise, take a crack at building a sensible set of options + # that mean that constraint criteria + else: + i = 1 + increment = (max - min) / (constants.MAX_VALID_OPTION_VALUES - 1) + while (i <= constants.MAX_VALID_OPTION_VALUES - 2): + unrounded = min + (i * increment) + rounded = int(round(unrounded / step) * step) + resolutions.append(str(rounded)) + i = i + 1 + resolutions.insert(0, str(min)) + resolutions.append(str(max)) + + self.valid_resolutions = resolutions + elif sane_device.options['resolution'].constraint_type == \ + saneme.OPTION_CONSTRAINT_INTEGER_LIST: + self.valid_resolutions = \ + [str(i) for i in sane_device.options['resolution'].constraint] + elif sane_device.options['resolution'].constraint_type == \ + saneme.OPTION_CONSTRAINT_STRING_LIST: + sane_device.options['resolution'].constraint + else: + raise AssertionError('Unsupported constraint type.') + except saneme.SaneError: + exc_info = sys.exc_info() + main_controller.run_device_exception_dialog(exc_info) def _load_scanner_option_values(self): """ - Get current scanner options from the SaneDevice. + Get current scanner options from the active_scanner. Useful for reloading any option that may have changed in response to a SaneReloadOptionsError. """ try: self.active_mode = self.active_scanner.options['mode'].value self.active_resolution = \ str(self.active_scanner.options['resolution'].value) except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) \ No newline at end of file diff --git a/sane/saneme.py b/sane/saneme.py index 3bd069f..30f7161 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -116,862 +116,864 @@ class SaneMe(object): def _shutdown(self): """ Deinitialize SANE. This code would go in __del__, but it is not guaranteed that method will be called and sane_exit must be called to release resources. To ensure this method is called it is registered with atexit. """ for device in self._devices: if device.is_open(): device.close() sane_exit() self._version = None if self._log: self._log.info('SANE deinitialized.') # Public Methods def get_device_list(self): """ Poll for connected devices. This method may take several seconds to return. Note that SANE is exited and re-inited before querying for devices to workaround a limitation in SANE's USB driver which causes the device list to only be updated on init. This means that all settings applied to all devices will be B{lost} and must be restored by the calling application. This was found documented here: U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html} """ if not self._version: raise AssertionError('version was None') # See docstring for details on this voodoo self._shutdown() self._setup() cdevices = POINTER(POINTER(SANE_Device))() status = sane_get_devices(byref(cdevices), SANE_Bool(0)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_get_devices ran out of memory.') else: raise SaneUnknownError( 'sane_get_devices returned an invalid status: %i.' % status) device_count = 0 self._devices = [] while cdevices[device_count]: self._devices.append( Device(cdevices[device_count].contents, self._log)) device_count += 1 if self._log: self._log.info('SANE queried, %i device(s) found.', device_count) return self._devices def get_device_by_name(self, name): """ Retrieve a L{Device} by name. Must be preceded by a call to L{get_device_list}. """ for device in self._devices: if device.name == name: return device raise SaneNoSuchDeviceError( 'The requested device does not exist.') class Device(object): """ This is the primary object for interacting with SANE. It represents a single device and handles enumeration of options, getting and setting of options, and starting and stopping of scanning jobs. """ _log = None _handle = None _name = '' _vendor = '' _model = '' _type = '' _display_name = '' _options = {} def __init__(self, ctypes_device, log=None): """ Sets the Devices properties from a ctypes SANE_Device and queries for its available options. """ self._log = log # String attributes should never be None self._name = ctypes_device.name if ctypes_device.name else '' self._vendor = ctypes_device.vendor if ctypes_device.vendor else '' self._model = ctypes_device.model if ctypes_device.model else '' self._type = ctypes_device.type if ctypes_device.type else '' self._display_name = ' '.join([self._vendor, self._model]) # Read only properties def __get_name(self): """ Get the complete SANE identifier for this device, e.g. 'lexmark:libusb:002:006'. """ return self._name name = property(__get_name) def __get_vendor(self): """Get the manufacturer of this device, e.g. 'Lexmark'.""" return self._vendor vendor = property(__get_vendor) def __get_model(self): """Get the specific model of this device, e.g. 'X1100/rev. B2'.""" return self._model model = property(__get_model) def __get_type(self): """Get the type of this device, e.g. 'flatbed scanner'.""" return self._type type = property(__get_type) def __get_display_name(self): """ Get an appropriate name to use for displaying this device to a user, e.g. 'Lexmark X1100/rev. B2'.""" return self._display_name display_name = property(__get_display_name) def __get_options(self): """Get the dictionary of options that this device has.""" return self._options options = property(__get_options) # Internal methods def _update_options(self): """ Update the list of available options for this device. As these are immutable, this should only need to be called when the Device is first instantiated. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') option_value = pointer(c_int()) status = sane_control_option( self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: raise SaneUnsupportedOperationError( 'sane_control_option reported that a value was outside the option\'s constraint.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) option_count = option_value.contents.value if self._log: self._log.debug('Device queried, %i option(s) found.', option_count) self._options.clear() i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) self._options[coption.contents.name] = Option( self, i, coption.contents, self._log) i = i + 1 # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Public methods def open(self): """ Open a new handle to this device. Must be called before any operations (including getting or setting options) are performed on this device. """ if self._handle: raise AssertionError('device handle already exists.') self._handle = SANE_Handle() status = sane_open(self.name, byref(self._handle)) # If and exception will be thrown, nullify device handle # so is_open() will return false for the device. if status != SANE_STATUS_GOOD.value: self._handle = None if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_open reported that the device was busy.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) self._update_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) def has_option(self, option_name): """Return true if option_name is available for this scanner.""" return (option_name in self.options.keys()) def scan(self, progress_callback=None): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) elif sane_parameters.format == SANE_FRAME_RGB.value: pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capabilities = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number # String attributes should never be None self._name = ctypes_option.name if ctypes_option.name else '' self._title = ctypes_option.title if ctypes_option.title else '' self._description = ctypes_option.desc if ctypes_option.desc else '' self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass - elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: + elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) - elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: + elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 + else: + self._constraint = None # Read only properties def __get_name(self): """ Get the short-form name of this option, e.g. 'mode'. May be an empty string, but never None. """ return self._name name = property(__get_name) def __get_title(self): """ Get the full name of this option, e.g. 'Scan mode'. May be an empty string, but never None. """ return self._title title = property(__get_title) def __get_description(self): """ Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' May be an empty string, but never None. """ return self._description description = property(__get_description) def __get_type(self): return self._type type = property(__get_type) def __get_unit(self): return self._unit unit = property(__get_unit) def __get_capability(self): # TODO: break out into individual capabilities, rather than a bitset return self._capability capability = property(__get_capability) def __get_constraint_type(self): return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then this is a list of integers which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """value Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option( handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i.' % status, device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value else: option_value = option_value.contents.value if self._log: self._log.debug( 'Option %s queried, its current value is %s.', self._name, option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: raise TypeError( 'option set with %s, expected BooleanType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: raise TypeError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: raise ValueError( 'value for option is longer than max string size') c_value = c_char_p(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: if value < self._constraint[0]: raise ValueError('value for option is less than min.') if value > self._constraint[1]: raise ValueError('value for option is greater than max.') if value % self._constraint[2] != 0: raise ValueError( 'value for option is not divisible by step.') elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i .' % status, device=self._device) if self._log: self._log.debug('Option %s set to value %s.', self._name, value) # Constraint checking ensures this should never happen if info_flags.value & SANE_INFO_INEXACT: raise AssertionError( 'sane_control_option reported that set value was inexact.') # TODO? if info_flags.value & SANE_INFO_RELOAD_PARAMS: pass # See SANE API 4.3.7 if info_flags.value & SANE_INFO_RELOAD_OPTIONS: raise SaneReloadOptionsError() value = property(__get_value, __set_value) class ScanInfo(object): """ Contains the parameters and progress of a scan in progress. """ _width = 0 _height = 0 _depth = 0 _total_bytes = 0 def __init__(self, sane_parameters): """ Initialize the ScanInfo object from the sane_parameters. """ self._width = sane_parameters.pixels_per_line self._height = sane_parameters.lines self._depth = sane_parameters.depth self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines # Read only properties def __get_width(self): """Get the width of the current scan, in pixels.""" return self._width width = property(__get_width) def __get_height(self): """Get the height of the current scan, in pixels.""" return self._height height = property(__get_height) def __get_depth(self): """Get the depth of the current scan, in bits.""" return self._depth depth = property(__get_depth) def __get_total_bytes(self): """Get the total number of bytes comprising this scan.""" return self._total_bytes total_bytes = property(__get_total_bytes) if __name__ == '__main__': def progress_callback(sane_info, bytes_read): #print float(bytes_read) / sane_info.total_bytes pass import logging log_format = FORMAT = "%(message)s" logging.basicConfig(level=logging.DEBUG, format=log_format) sane = SaneMe(logging.getLogger()) devices = sane.get_device_list() for dev in devices: print dev.name devices[0].open() print devices[0].options.keys() try: devices[0].options['mode'].value = 'Gray' except SaneReloadOptionsError: pass try: devices[0].options['resolution'].value = 75 except SaneReloadOptionsError: pass try: devices[0].options['preview'].value = False except SaneReloadOptionsError: pass devices[0].scan(progress_callback).save('out.bmp') devices[0].close() \ No newline at end of file
onyxfish/nostaples
68fbc049b9a2e1de3e00569b77f9d1d19a647bc9
Revised MainModel's handling of devices to be more obvious.
diff --git a/models/main.py b/models/main.py index 225dbf4..258981e 100644 --- a/models/main.py +++ b/models/main.py @@ -1,357 +1,377 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme import nostaples.utils.properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Store previous device old_value = self._prop_active_scanner # Close the old scanner (if not None) - if isinstance(old_value, saneme.Device): + if old_value is not None: + assert isinstance(old_value, saneme.Device) + if old_value.is_open(): old_value.close() # Only persist the state if the new value is not None # and it can be opened without error. # This prevents problems with trying to store a Null # value in the state backend and also allows for smooth # transitions if a scanner is disconnected and reconnected. if value is not None: try: # Verify that the proper type is being set assert isinstance(value, saneme.Device) value.open() # TODO: ensure these are the expected constraints # (resolution may be a range) self.valid_modes = value.options['mode'].constraint self.valid_resolutions = \ [str(i) for i in value.options['resolution'].constraint] except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) self.application.get_state_manager()['active_scanner'] = value.name # Update the internal property variable self._prop_active_scanner = value - # Emit the property change notification to all observers. + # Emit the property change notification self.notify_property_value_change( - 'active_scanner', old_value, value) + 'active_scanner', None, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() - old_value = self._prop_active_mode - - try: - scanner_value = self.active_scanner.options['mode'].value - except saneme.SaneError: - exc_info = sys.exc_info() - main_controller.run_device_exception_dialog(exc_info) + # Check if a valid scanner has been loaded (not None) + if isinstance(self.active_scanner, saneme.Device): + # The device should always be open if a value is being set + assert self.active_scanner.is_open() - if old_value == value and \ - scanner_value == value: - return - - if value is not None: - # This catches the case where the value is being loaded from state - # but a scanner has not yet been activated. - if self.active_scanner: + # Store the current scanner value for comparison + try: + scanner_value = self.active_scanner.options['mode'].value + except saneme.SaneError: + exc_info = sys.exc_info() + main_controller.run_device_exception_dialog(exc_info) + + # Never re-set a value or set None to a device option + if value is not None and scanner_value != value: try: - # Only set if different (prevent ReloadOptions from firing) - if self.active_scanner.options['mode'].value != value: - self.active_scanner.options['mode'].value = value + # Set the new option value + self.active_scanner.options['mode'].value = value except saneme.SaneReloadOptionsError: - try: - self._load_scanner_option_values() - except saneme.SaneError: - exc_info = sys.exc_info() - main_controller.run_device_exception_dialog(exc_info) + # Reload any options that may have changed + self._load_scanner_option_values() + + # Never persist None to state + if value is not None: + self.application.get_state_manager()['scan_mode'] = value - self.application.get_state_manager()['scan_mode'] = value - + # Set new property value self._prop_active_mode = value + # Emit change notification self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() - if value is not None: - if self.active_scanner: + # Check if a valid scanner has been loaded (not None) + if isinstance(self.active_scanner, saneme.Device): + # The device should always be open if a value is being set + assert self.active_scanner.is_open() + + # Store the current scanner value for comparison + try: + scanner_value = self.active_scanner.options['resolution'].value + except saneme.SaneError: + exc_info = sys.exc_info() + main_controller.run_device_exception_dialog(exc_info) + + # Never re-set a value or set None to a device option + if value is not None and scanner_value != int(value): try: - if self.active_scanner.options['resolution'].value != int(value): - self.active_scanner.options['resolution'].value = int(value) + # Set the new option value + self.active_scanner.options['resolution'].value = int(value) except saneme.SaneReloadOptionsError: - try: - self._load_scanner_option_values() - except saneme.SaneError: - exc_info = sys.exc_info() - main_controller.run_device_exception_dialog(exc_info) - - self.application.get_state_manager()['scan_resolution'] = str(value) - + # Reload any options that may have changed + self._load_scanner_option_values() + + # Never persist None to state + if value is not None: + self.application.get_state_manager()['scan_resolution'] = value + + # Set new property value self._prop_active_resolution = value + # Emit change notification self.notify_property_value_change( - 'active_resolution', None, value) + 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ Set the list of available scanners and update the active_scanner. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() self._prop_available_scanners = value # Force notification self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None else: # Select the first available scanner if the previously # selected scanner is not in the new list if self._prop_active_scanner not in value: self.active_scanner = value[0] # Otherwise maintain current selection else: self.active_scanner = self.active_scanner def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) # Update the active mode if len(value) == 0: self.active_mode = None else: if self.active_mode not in value: self.active_mode = value[0] else: self.active_mode = self.active_mode def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) # Update the active resolution if len(value) == 0: self.active_resolution = None else: if self.active_resolution not in value: self.active_resolution = value[0] else: self.active_resolution = self.active_resolution # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: - self.active_scanner = sane.get_device_by_name(state_manager['active_scanner']) + self.active_scanner = sane.get_device_by_name( + state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution # INTERNAL METHODS def _load_scanner_option_values(self): """ Get current scanner options from the SaneDevice. - Exceptions should be handled by calling method. + Useful for reloading any option that may have changed in response to + a SaneReloadOptionsError. """ - self.active_mode = self.active_scanner.options['mode'].value - self.active_resolution = self.active_scanner.options['resolution'].value \ No newline at end of file + try: + self.active_mode = self.active_scanner.options['mode'].value + self.active_resolution = \ + str(self.active_scanner.options['resolution'].value) + except saneme.SaneError: + exc_info = sys.exc_info() + main_controller.run_device_exception_dialog(exc_info) \ No newline at end of file
onyxfish/nostaples
6fe9ec5dfc66d98bb247f05521331e48477905f8
Fixes for previous incremental work on handling SaneReloadOptionsError.
diff --git a/models/main.py b/models/main.py index ed573b3..225dbf4 100644 --- a/models/main.py +++ b/models/main.py @@ -1,339 +1,357 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme import nostaples.utils.properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() - # Ignore spurious updates + # Store previous device old_value = self._prop_active_scanner - # Close the old scanner + # Close the old scanner (if not None) if isinstance(old_value, saneme.Device): if old_value.is_open(): old_value.close() - # Verify that the proper type is being set - if value is not None: - assert isinstance(value, saneme.Device) - # Only persist the state if the new value is not None # and it can be opened without error. # This prevents problems with trying to store a Null # value in the state backend and also allows for smooth # transitions if a scanner is disconnected and reconnected. if value is not None: try: + # Verify that the proper type is being set + assert isinstance(value, saneme.Device) + value.open() - self._reload_scanner_options() + + # TODO: ensure these are the expected constraints + # (resolution may be a range) + self.valid_modes = value.options['mode'].constraint + self.valid_resolutions = \ + [str(i) for i in value.options['resolution'].constraint] except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) self.application.get_state_manager()['active_scanner'] = value.name # Update the internal property variable self._prop_active_scanner = value # Emit the property change notification to all observers. self.notify_property_value_change( 'active_scanner', old_value, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. - """ + """ + main_controller = self.application.get_main_controller() + + old_value = self._prop_active_mode + + try: + scanner_value = self.active_scanner.options['mode'].value + except saneme.SaneError: + exc_info = sys.exc_info() + main_controller.run_device_exception_dialog(exc_info) + + if old_value == value and \ + scanner_value == value: + return + if value is not None: # This catches the case where the value is being loaded from state # but a scanner has not yet been activated. - if self.active_scanner: + if self.active_scanner: try: - self.active_scanner.options['mode'].value = value + # Only set if different (prevent ReloadOptions from firing) + if self.active_scanner.options['mode'].value != value: + self.active_scanner.options['mode'].value = value except saneme.SaneReloadOptionsError: try: - self._reload_scanner_options() - except: + self._load_scanner_option_values() + except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) self.application.get_state_manager()['scan_mode'] = value self._prop_active_mode = value self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ + main_controller = self.application.get_main_controller() + if value is not None: - # This catches the case where the value is being loaded from state - # but a scanner has not yet been activated. if self.active_scanner: try: - self.active_scanner.options['resolution'].value = int(value) - except SaneReloadOptionsError: + if self.active_scanner.options['resolution'].value != int(value): + self.active_scanner.options['resolution'].value = int(value) + except saneme.SaneReloadOptionsError: try: - self._reload_scanner_options() - except: + self._load_scanner_option_values() + except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) - self.application.get_state_manager()['scan_resolution'] = value + self.application.get_state_manager()['scan_resolution'] = str(value) self._prop_active_resolution = value self.notify_property_value_change( 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ Set the list of available scanners and update the active_scanner. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() self._prop_available_scanners = value # Force notification self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None else: # Select the first available scanner if the previously # selected scanner is not in the new list if self._prop_active_scanner not in value: self.active_scanner = value[0] # Otherwise maintain current selection else: self.active_scanner = self.active_scanner def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) # Update the active mode if len(value) == 0: self.active_mode = None else: if self.active_mode not in value: self.active_mode = value[0] else: self.active_mode = self.active_mode def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) # Update the active resolution if len(value) == 0: self.active_resolution = None else: if self.active_resolution not in value: self.active_resolution = value[0] else: self.active_resolution = self.active_resolution # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name(state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution # INTERNAL METHODS - def _reload_scanner_options(self): + def _load_scanner_option_values(self): """ Get current scanner options from the SaneDevice. Exceptions should be handled by calling method. """ - # TODO: ensure these are the expected constraints - # (resolution may be a range) - self.valid_modes = self.active_scanner.options['mode'].constraint - self.valid_resolutions = \ - [str(i) for i in self.active_scanner.options['resolution'].constraint] \ No newline at end of file + self.active_mode = self.active_scanner.options['mode'].value + self.active_resolution = self.active_scanner.options['resolution'].value \ No newline at end of file
onyxfish/nostaples
874117f362512be61a4f8a0da810199b9b360027
Experimental support for SANE_RELOAD_OPTIONS.
diff --git a/models/main.py b/models/main.py index 74eb7df..ed573b3 100644 --- a/models/main.py +++ b/models/main.py @@ -1,321 +1,339 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.sane as saneme import nostaples.utils.properties class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Ignore spurious updates old_value = self._prop_active_scanner # Close the old scanner if isinstance(old_value, saneme.Device): if old_value.is_open(): old_value.close() # Verify that the proper type is being set if value is not None: assert isinstance(value, saneme.Device) - # Update the internal property variable - self._prop_active_scanner = value - # Only persist the state if the new value is not None # and it can be opened without error. # This prevents problems with trying to store a Null # value in the state backend and also allows for smooth # transitions if a scanner is disconnected and reconnected. if value is not None: try: value.open() - self.valid_modes = value.options['mode'].constraint - self.valid_resolutions = \ - [str(i) for i in value.options['resolution'].constraint] + self._reload_scanner_options() except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) self.application.get_state_manager()['active_scanner'] = value.name - + + # Update the internal property variable + self._prop_active_scanner = value + # Emit the property change notification to all observers. self.notify_property_value_change( 'active_scanner', old_value, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. - """ - self._prop_active_mode = value - + """ if value is not None: # This catches the case where the value is being loaded from state # but a scanner has not yet been activated. if self.active_scanner: try: self.active_scanner.options['mode'].value = value except saneme.SaneReloadOptionsError: - # TODO - pass + try: + self._reload_scanner_options() + except: + exc_info = sys.exc_info() + main_controller.run_device_exception_dialog(exc_info) self.application.get_state_manager()['scan_mode'] = value - + + self._prop_active_mode = value + self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. - """ - self._prop_active_resolution = value - + """ if value is not None: # This catches the case where the value is being loaded from state # but a scanner has not yet been activated. if self.active_scanner: try: self.active_scanner.options['resolution'].value = int(value) except SaneReloadOptionsError: - # TODO - pass - + try: + self._reload_scanner_options() + except: + exc_info = sys.exc_info() + main_controller.run_device_exception_dialog(exc_info) + self.application.get_state_manager()['scan_resolution'] = value - + + self._prop_active_resolution = value + self.notify_property_value_change( 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ Set the list of available scanners and update the active_scanner. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() self._prop_available_scanners = value # Force notification self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None else: # Select the first available scanner if the previously # selected scanner is not in the new list if self._prop_active_scanner not in value: self.active_scanner = value[0] # Otherwise maintain current selection else: self.active_scanner = self.active_scanner def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) # Update the active mode if len(value) == 0: self.active_mode = None else: if self.active_mode not in value: self.active_mode = value[0] else: self.active_mode = self.active_mode def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) # Update the active resolution if len(value) == 0: self.active_resolution = None else: if self.active_resolution not in value: self.active_resolution = value[0] else: self.active_resolution = self.active_resolution # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name(state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution + + # INTERNAL METHODS + + def _reload_scanner_options(self): + """ + Get current scanner options from the SaneDevice. + + Exceptions should be handled by calling method. + """ + # TODO: ensure these are the expected constraints + # (resolution may be a range) + self.valid_modes = self.active_scanner.options['mode'].constraint + self.valid_resolutions = \ + [str(i) for i in self.active_scanner.options['resolution'].constraint] \ No newline at end of file diff --git a/sane/saneme.py b/sane/saneme.py index 730dcf7..3bd069f 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -207,762 +207,771 @@ class Device(object): _name = '' _vendor = '' _model = '' _type = '' _display_name = '' _options = {} def __init__(self, ctypes_device, log=None): """ Sets the Devices properties from a ctypes SANE_Device and queries for its available options. """ self._log = log # String attributes should never be None self._name = ctypes_device.name if ctypes_device.name else '' self._vendor = ctypes_device.vendor if ctypes_device.vendor else '' self._model = ctypes_device.model if ctypes_device.model else '' self._type = ctypes_device.type if ctypes_device.type else '' self._display_name = ' '.join([self._vendor, self._model]) # Read only properties def __get_name(self): """ Get the complete SANE identifier for this device, e.g. 'lexmark:libusb:002:006'. """ return self._name name = property(__get_name) def __get_vendor(self): """Get the manufacturer of this device, e.g. 'Lexmark'.""" return self._vendor vendor = property(__get_vendor) def __get_model(self): """Get the specific model of this device, e.g. 'X1100/rev. B2'.""" return self._model model = property(__get_model) def __get_type(self): """Get the type of this device, e.g. 'flatbed scanner'.""" return self._type type = property(__get_type) def __get_display_name(self): """ Get an appropriate name to use for displaying this device to a user, e.g. 'Lexmark X1100/rev. B2'.""" return self._display_name display_name = property(__get_display_name) def __get_options(self): """Get the dictionary of options that this device has.""" return self._options options = property(__get_options) # Internal methods def _update_options(self): """ Update the list of available options for this device. As these are immutable, this should only need to be called when the Device is first instantiated. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') option_value = pointer(c_int()) status = sane_control_option( self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: raise SaneUnsupportedOperationError( 'sane_control_option reported that a value was outside the option\'s constraint.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) option_count = option_value.contents.value if self._log: self._log.debug('Device queried, %i option(s) found.', option_count) self._options.clear() i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) self._options[coption.contents.name] = Option( self, i, coption.contents, self._log) i = i + 1 # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Public methods def open(self): """ Open a new handle to this device. Must be called before any operations (including getting or setting options) are performed on this device. """ if self._handle: raise AssertionError('device handle already exists.') self._handle = SANE_Handle() status = sane_open(self.name, byref(self._handle)) # If and exception will be thrown, nullify device handle # so is_open() will return false for the device. if status != SANE_STATUS_GOOD.value: self._handle = None if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_open reported that the device was busy.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) self._update_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) def has_option(self, option_name): """Return true if option_name is available for this scanner.""" return (option_name in self.options.keys()) def scan(self, progress_callback=None): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) elif sane_parameters.format == SANE_FRAME_RGB.value: pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capabilities = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number # String attributes should never be None self._name = ctypes_option.name if ctypes_option.name else '' self._title = ctypes_option.title if ctypes_option.title else '' self._description = ctypes_option.desc if ctypes_option.desc else '' self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 # Read only properties def __get_name(self): """ Get the short-form name of this option, e.g. 'mode'. May be an empty string, but never None. """ return self._name name = property(__get_name) def __get_title(self): """ Get the full name of this option, e.g. 'Scan mode'. May be an empty string, but never None. """ return self._title title = property(__get_title) def __get_description(self): """ Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' May be an empty string, but never None. """ return self._description description = property(__get_description) def __get_type(self): return self._type type = property(__get_type) def __get_unit(self): return self._unit unit = property(__get_unit) def __get_capability(self): # TODO: break out into individual capabilities, rather than a bitset return self._capability capability = property(__get_capability) def __get_constraint_type(self): return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then this is a list of integers which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): - """ + """value Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option( handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i.' % status, device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value else: option_value = option_value.contents.value if self._log: self._log.debug( 'Option %s queried, its current value is %s.', self._name, option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: raise TypeError( 'option set with %s, expected BooleanType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: raise TypeError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: raise ValueError( 'value for option is longer than max string size') c_value = c_char_p(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: if value < self._constraint[0]: raise ValueError('value for option is less than min.') if value > self._constraint[1]: raise ValueError('value for option is greater than max.') if value % self._constraint[2] != 0: raise ValueError( 'value for option is not divisible by step.') elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i .' % status, device=self._device) if self._log: self._log.debug('Option %s set to value %s.', self._name, value) + # Constraint checking ensures this should never happen + if info_flags.value & SANE_INFO_INEXACT: + raise AssertionError( + 'sane_control_option reported that set value was inexact.') + + # TODO? + if info_flags.value & SANE_INFO_RELOAD_PARAMS: + pass + # See SANE API 4.3.7 if info_flags.value & SANE_INFO_RELOAD_OPTIONS: raise SaneReloadOptionsError() value = property(__get_value, __set_value) class ScanInfo(object): """ Contains the parameters and progress of a scan in progress. """ _width = 0 _height = 0 _depth = 0 _total_bytes = 0 def __init__(self, sane_parameters): """ Initialize the ScanInfo object from the sane_parameters. """ self._width = sane_parameters.pixels_per_line self._height = sane_parameters.lines self._depth = sane_parameters.depth self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines # Read only properties def __get_width(self): """Get the width of the current scan, in pixels.""" return self._width width = property(__get_width) def __get_height(self): """Get the height of the current scan, in pixels.""" return self._height height = property(__get_height) def __get_depth(self): """Get the depth of the current scan, in bits.""" return self._depth depth = property(__get_depth) def __get_total_bytes(self): """Get the total number of bytes comprising this scan.""" return self._total_bytes total_bytes = property(__get_total_bytes) if __name__ == '__main__': def progress_callback(sane_info, bytes_read): #print float(bytes_read) / sane_info.total_bytes pass import logging log_format = FORMAT = "%(message)s" logging.basicConfig(level=logging.DEBUG, format=log_format) sane = SaneMe(logging.getLogger()) devices = sane.get_device_list() for dev in devices: print dev.name devices[0].open() print devices[0].options.keys() try: devices[0].options['mode'].value = 'Gray' except SaneReloadOptionsError: pass try: devices[0].options['resolution'].value = 75 except SaneReloadOptionsError: pass try: devices[0].options['preview'].value = False except SaneReloadOptionsError: pass devices[0].scan(progress_callback).save('out.bmp') devices[0].close() \ No newline at end of file
onyxfish/nostaples
6ef01d5a3929363953d9a93358ab7c56914adada
Added clickable link and version info to About Dialog.
diff --git a/controllers/about.py b/controllers/about.py index da30c68..6d7eea9 100644 --- a/controllers/about.py +++ b/controllers/about.py @@ -1,83 +1,88 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{AboutController}, which manages interaction between the user and the L{AboutView}. """ import logging +import webbrowser from gtkmvc.controller import Controller from gtkmvc.model import Model from nostaples import constants class AboutController(Controller): """ Manages interaction between the user and the L{AboutView}. See U{http://faq.pygtk.org/index.py?req=show&file=faq10.013.htp} for an explanation of all the GTK signal handling voodoo in this class. """ # SETUP METHODS def __init__(self, application): """ Constructs the AboutController. Note that About has no model, an empty model is passed to the super constructor to avoid assertion failures later on. """ self.application = application Controller.__init__(self, Model()) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) # USER INTERFACE CALLBACKS def on_about_dialog_close(self, dialog): """Hide the about dialog.""" dialog.hide() def on_about_dialog_response(self, dialog, response): """Hide the about dialog.""" dialog.hide() def on_about_dialog_delete_event(self, dialog, event): """Hide the about dialog.""" dialog.hide() return True + def on_about_dialog_url_clicked(self, dialog, link): + """Open the webpage in the users default browser.""" + webbrowser.open(link) + # PUBLIC METHODS def run(self): """Run the modal about dialog.""" self.application.get_about_view().run() \ No newline at end of file diff --git a/gui/about_dialog.glade b/gui/about_dialog.glade index d6b624d..d2dfc76 100644 --- a/gui/about_dialog.glade +++ b/gui/about_dialog.glade @@ -1,58 +1,59 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> -<!--Generated with glade3 3.4.5 on Wed Dec 24 09:14:42 2008 --> +<!--Generated with glade3 3.4.5 on Wed Mar 4 12:52:10 2009 --> <glade-interface> <widget class="GtkAboutDialog" id="about_dialog"> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="border_width">5</property> <property name="title" translatable="yes">About NoStaples</property> <property name="resizable">False</property> <property name="modal">True</property> <property name="window_position">GTK_WIN_POS_CENTER_ON_PARENT</property> <property name="destroy_with_parent">True</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property> <property name="skip_taskbar_hint">True</property> <property name="skip_pager_hint">True</property> <property name="has_separator">False</property> <property name="program_name">NoStaples</property> - <property name="copyright" translatable="yes">Copyright © 2008 Christopher Groskopf </property> + <property name="version">0.4.0</property> + <property name="copyright" translatable="yes">Copyright © 2009 Christopher Groskopf </property> <property name="comments" translatable="yes">A low-volume document imaging solution for Gnome.</property> - <property name="website">http://www.etlafins.com/nostaples/</property> - <property name="website_label" translatable="yes">http://www.etlafins.com/nostaples/</property> + <property name="website">http://www.etlafins.com/nostaples</property> + <property name="website_label" translatable="yes">http://www.etlafins.com/nostaples</property> <property name="license" translatable="yes">NoStaples is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. NoStaples is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with NoStaples. If not, see &lt;http://www.gnu.org/licenses/&gt;.</property> <property name="authors">Christopher Groskopf &lt;[email protected]&gt;</property> <property name="documenters"></property> <signal name="close" handler="on_about_dialog_close"/> <signal name="delete_event" handler="on_about_dialog_delete_event"/> <signal name="response" handler="on_about_dialog_response"/> <child internal-child="vbox"> <widget class="GtkVBox" id="dialog-vbox1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="spacing">5</property> <child internal-child="action_area"> <widget class="GtkHButtonBox" id="dialog-action_area1"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="layout_style">GTK_BUTTONBOX_END</property> </widget> <packing> <property name="expand">False</property> <property name="pack_type">GTK_PACK_END</property> </packing> </child> </widget> </child> </widget> </glade-interface> diff --git a/views/about.py b/views/about.py index 4811a66..ebac133 100644 --- a/views/about.py +++ b/views/about.py @@ -1,59 +1,66 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the AboutView which exposes the application's about dialog. """ import logging import os import gtk from gtkmvc.view import View from nostaples import constants class AboutView(View): """ Exposes the application's main window. """ def __init__(self, application): """Constructs the AboutView.""" self.application = application + about_controller = self.application.get_about_controller() about_dialog_glade = os.path.join( constants.GUI_DIRECTORY, 'about_dialog.glade') + + # This must be set before the window is created or + # the url will not be clickable. + gtk.about_dialog_set_url_hook( + about_controller.on_about_dialog_url_clicked) + View.__init__( - self, self.application.get_about_controller(), + self, about_controller, about_dialog_glade, 'about_dialog', None, False) self.log = logging.getLogger(self.__class__.__name__) # Can't do this in constructor as main_view has multiple # top-level widgets self['about_dialog'].set_transient_for( self.application.get_main_view()['scan_window']) - + self.application.get_about_controller().register_view(self) self.log.debug('Created.') def run(self): """Run this modal dialog.""" self['about_dialog'].run() \ No newline at end of file
onyxfish/nostaples
8557e100a22128d968dab3b07b8a80eb6dffab6a
Preperations for 0.4 release.
diff --git a/setup.py b/setup.py index f0f622f..e36d29f 100644 --- a/setup.py +++ b/setup.py @@ -1,18 +1,18 @@ #!/usr/bin/env python from distutils.core import setup setup(name='nostaples', - version='0.3.0', + version='0.4.0', description='GNOME Document Scanning Application', author='Christopher Groskopf', author_email='[email protected]', url='http://www.etlafins.com/nostaples', license='GPL', packages=['nostaples', 'nostaples.controllers', 'nostaples.models', 'nostaples.utils', 'nostaples.views', 'nostaples.unittests', 'nostaples.sane'], package_dir={'nostaples' : ''}, package_data={'nostaples' : ['logging.config', 'gui/*.glade']}, scripts = ['nostaples'], data_files=[('share/applications', ['data/nostaples.desktop'])] )
onyxfish/nostaples
152fb66839a13ffeeaee820818c22ccd9d74d43a
Added --debugdevices command line option.
diff --git a/controllers/page.py b/controllers/page.py index f62ba5e..019b092 100644 --- a/controllers/page.py +++ b/controllers/page.py @@ -1,498 +1,499 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{PageController}, which manages interaction between the L{PageModel} and L{PageView}. """ import logging import gtk from gtkmvc.controller import Controller from nostaples import constants class PageController(Controller): """ Manages interaction between the L{PageModel} and L{PageView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the PageController. """ self.application = application Controller.__init__(self, application.get_null_page_model()) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) application.get_preferences_model().register_observer(self) self.log = logging.getLogger(self.__class__.__name__) # The preview pixbuf is cached so it can be rerendered without # reapplying zoom transformations. self.preview_pixbuf = None # Non persistent settings that apply to all scanned pages self.preview_width = 0 self.preview_height = 0 self.preview_zoom = 1.0 self.preview_is_best_fit = False # TODO: should be a gconf preference self.preview_zoom_rect_color = \ gtk.gdk.colormap_get_system().alloc_color( gtk.gdk.Color(65535, 0, 0), False, True) # Reusable temp vars to hold the start point of a mouse drag action. self.zoom_drag_start_x = 0 self.zoom_drag_start_y = 0 self.move_drag_start_x = 0 self.move_drag_start_y = 0 self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) # USER INTERFACE CALLBACKS def on_page_view_image_layout_button_press_event(self, widget, event): """ Begins a drag or zoom event. """ # Do not process mouse events if nothing is visible if not self.model.pixbuf: return if event.button == 1: self._begin_move(event.x, event.y) elif event.button == 3: self._begin_zoom(event.x, event.y) def on_page_view_image_layout_motion_notify_event(self, widget, event): """ Update the preview during a drag or zoom event. """ # Do not process mouse events if nothing is visible if not self.model.pixbuf: return # Handle both hint events and routine notifications # See: http://www.pygtk.org/pygtk2tutorial/sec-EventHandling.html if event.is_hint: mouse_state = event.window.get_pointer()[2] else: mouse_state = event.state # Move if (mouse_state & gtk.gdk.BUTTON1_MASK): self._update_move(event.x_root, event.y_root) # Zoom elif (mouse_state & gtk.gdk.BUTTON3_MASK): self._update_zoom(event.x, event.y) # NB: These need to be updated even if the button wasn't pressed self.move_drag_start_x = event.x_root self.move_drag_start_y = event.y_root def on_page_view_image_layout_button_release_event(self, widget, event): """ Ends a drag or zoom event. """ # Do not process mouse events if nothing is visible if not self.model.pixbuf: return # Move if event.button == 1: self._end_move() # Zoom elif event.button == 3: self._end_zoom(event.x, event.y) def on_page_view_image_layout_scroll_event(self, widget, event): """ TODO: Mouse scroll event. Go to next/prev page? Or scroll image? """ pass def on_page_view_image_layout_size_request(self, widget, size): size.width = 1 size.height = 1 def on_page_view_image_layout_size_allocate(self, widget, allocation): """ Resizes the image preview size to match that which is allocated to the preview layout widget. TODO: Resize of image does not occur until after the window has finished resizing (which looks awful). """ if allocation.width == self.preview_width and \ allocation.height == self.preview_height: return self.preview_width = allocation.width self.preview_height = allocation.height self._update_preview() # PROPERTY CALLBACKS def property_pixbuf_value_change(self, model, old_value, new_value): """Update the preview display.""" self._update_preview() # PreferencesModel PROPERTY CALLBACKS def property_preview_mode_value_change(self, model, old_value, new_value): """Update the preview display.""" self._update_preview() # PUBLIC METHODS def get_current_page_model(self): """ Return the currently visible/selected page model. This may be the null page model. """ return self.model def set_current_page_model(self, page_model): """ Sets the PageModel that is currently being displayed in the preview area. """ self.model.unregister_observer(self) self.model = page_model self.model.register_observer(self) self._update_preview() def zoom_in(self): """ Zooms the preview image in. """ # TODO: max zoom should be a gconf preference if self.preview_zoom == 5: return # TODO: zoom amount should be a gconf preference self.preview_zoom += 0.5 if self.preview_zoom > 5: self.preview_zoom = 5 self.preview_is_best_fit = False self._update_preview() def zoom_out(self): """ Zooms the preview image out. """ # TODO: min zoom should be a gconf preference if self.preview_zoom == 1.0: return self.preview_zoom -= 0.5 if self.preview_zoom < 0.5: self.preview_zoom = 0.5 self.preview_is_best_fit = False self._update_preview() def zoom_one_to_one(self): """ Zooms the preview image to its true size. """ self.preview_zoom = 1.0 self.preview_is_best_fit = False self._update_preview() def zoom_best_fit(self): """ Zooms the preview image so the entire image will fit within the preview window. """ self.preview_is_best_fit = True self._update_preview() # PRIVATE (INTERNAL) METHODS def _begin_move(self, x, y): """ Determines if there is anything to be dragged and if so, sets the 'drag' cursor. """ page_view = self.application.get_page_view() if page_view['page_view_horizontal_scrollbar'].get_property('visible') and \ page_view['page_view_vertical_scrollbar'].get_property('visible'): return page_view['page_view_image'].get_parent_window().set_cursor( gtk.gdk.Cursor(gtk.gdk.FLEUR)) def _begin_zoom(self, x, y): """ Saves the starting position of the zoom and sets the 'zoom' cursor. """ page_view = self.application.get_page_view() page_view['page_view_image'].get_parent_window().set_cursor( gtk.gdk.Cursor(gtk.gdk.CROSS)) self.zoom_drag_start_x = x self.zoom_drag_start_y = y def _update_move(self, x, y): """ Moves/drags the preview in response to mouse movement. """ page_view = self.application.get_page_view() horizontal_adjustment = \ page_view['page_view_image_layout'].get_hadjustment() new_x = horizontal_adjustment.value + \ (self.move_drag_start_x - x) if new_x >= horizontal_adjustment.lower and \ new_x <= horizontal_adjustment.upper - horizontal_adjustment.page_size: horizontal_adjustment.set_value(new_x) vertical_adjustment = \ page_view['page_view_image_layout'].get_vadjustment() new_y = vertical_adjustment.value + \ (self.move_drag_start_y - y) if new_y >= vertical_adjustment.lower and \ new_y <= vertical_adjustment.upper - vertical_adjustment.page_size: vertical_adjustment.set_value(new_y) def _update_zoom(self, x, y): """ Renders a box around the zoom region the user has specified by dragging the mouse. """ page_view = self.application.get_page_view() start_x = self.zoom_drag_start_x start_y = self.zoom_drag_start_y end_x = x end_y = y if end_x < start_x: start_x, end_x = end_x, start_x if end_y < start_y: start_y, end_y = end_y, start_y width = end_x - start_x height = end_y - start_y page_view['page_view_image'].set_from_pixbuf(self.preview_pixbuf) page_view['page_view_image'].get_parent_window().invalidate_rect( (0, 0, self.preview_width, self.preview_height), False) page_view['page_view_image'].get_parent_window(). \ process_updates(False) graphics_context = \ page_view['page_view_image'].get_parent_window().new_gc( foreground=self.preview_zoom_rect_color, line_style=gtk.gdk.LINE_ON_OFF_DASH, line_width=2) page_view['page_view_image'].get_parent_window().draw_rectangle( graphics_context, False, int(start_x), int(start_y), int(width), int(height)) def _end_move(self): """ Resets to the default cursor. """ page_view = self.application.get_page_view() page_view['page_view_image'].get_parent_window().set_cursor(None) def _end_zoom(self, x, y): """ Calculates and applies zoom to the preview and updates the display. """ page_view = self.application.get_page_view() # Transform to absolute coords start_x = self.zoom_drag_start_x / self.preview_zoom start_y = self.zoom_drag_start_y / self.preview_zoom end_x = x / self.preview_zoom end_y = y / self.preview_zoom # Swizzle values if coords are reversed if end_x < start_x: start_x, end_x = end_x, start_x if end_y < start_y: start_y, end_y = end_y, start_y # Calc width and height width = end_x - start_x height = end_y - start_y # Calculate centering offset target_width = \ self.model.width * self.preview_zoom target_height = \ self.model.height * self.preview_zoom shift_x = int((self.preview_width - target_width) / 2) if shift_x < 0: shift_x = 0 shift_y = int((self.preview_height - target_height) / 2) if shift_y < 0: shift_y = 0 # Compensate for centering start_x -= shift_x / self.preview_zoom start_y -= shift_y / self.preview_zoom # Determine center-point of zoom region center_x = start_x + width / 2 center_y = start_y + height / 2 # Determine correct zoom to fit region if width > height: + # TODO: ZeroDivisionError has occurred here... self.preview_zoom = self.preview_width / width else: self.preview_zoom = self.preview_height / height # Cap zoom at 500% if self.preview_zoom > 5.0: self.preview_zoom = 5.0 # Transform center-point to relative coords transform_x = int(center_x * self.preview_zoom) transform_y = int(center_y * self.preview_zoom) # Center in preview display transform_x -= int(self.preview_width / 2) transform_y -= int(self.preview_height / 2) self.preview_is_best_fit = False self._update_preview() page_view['page_view_image_layout'].get_hadjustment().set_value( transform_x) page_view['page_view_image_layout'].get_vadjustment().set_value( transform_y) page_view['page_view_image'].get_parent_window().set_cursor(None) def _update_preview(self): """ Render the current page to the preview display. """ page_view = self.application.get_page_view() preferences_model = self.application.get_preferences_model() status_controller = self.application.get_status_controller() # Short circuit if the PageModel does not have a pixbuf # (such as the null page). if not self.model.pixbuf: page_view['page_view_image'].clear() status_controller.pop(self.status_context) return # Fit if necessary if self.preview_is_best_fit: width_ratio = float(self.model.width) / self.preview_width height_ratio = float(self.model.height) / self.preview_height if width_ratio < height_ratio: self.preview_zoom = 1 / float(height_ratio) else: self.preview_zoom = 1 / float(width_ratio) # Zoom if necessary if self.preview_zoom != 1.0: target_width = \ int(self.model.width * self.preview_zoom) target_height = \ int(self.model.height * self.preview_zoom) gtk_scale_mode = \ constants.PREVIEW_MODES[preferences_model.preview_mode] self.preview_pixbuf = self.model.pixbuf.scale_simple( target_width, target_height, gtk_scale_mode) else: target_width = self.model.width target_height = self.model.height self.preview_pixbuf = self.model.pixbuf # Resize preview area page_view['page_view_image_layout'].set_size( target_width, target_height) # Center preview shift_x = int((self.preview_width - target_width) / 2) if shift_x < 0: shift_x = 0 shift_y = int((self.preview_height - target_height) / 2) if shift_y < 0: shift_y = 0 page_view['page_view_image_layout'].move( page_view['page_view_image'], shift_x, shift_y) # Show/hide scrollbars if target_width > self.preview_width: page_view['page_view_horizontal_scrollbar'].show() else: page_view['page_view_horizontal_scrollbar'].hide() if target_height > self.preview_height: page_view['page_view_vertical_scrollbar'].show() else: page_view['page_view_vertical_scrollbar'].hide() # Render updated preview page_view['page_view_image'].set_from_pixbuf(self.preview_pixbuf) # Update status status_controller.pop(self.status_context) status_controller.push(self.status_context, "%.0f%%" % (self.preview_zoom * 100)) \ No newline at end of file diff --git a/nostaples b/nostaples index e5938a4..cb3c439 100755 --- a/nostaples +++ b/nostaples @@ -1,26 +1,98 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. ''' -This module holds the main loop which instantiates the NoStaples +This module parses command line options and bootstraps the NoStaples application. ''' -from nostaples.application import Application +import optparse +import sys + +# Functions to pretty-print debugging info +def print_device_debug(i, device): + """Pretty-print device information.""" + print 'Device %i' % i + print '' + print 'Name:\t%s' % device.name + print 'Vendor:\t%s' % device.vendor + print 'Model:\t%s' % device.model + print 'Type:\t%s' % device.type + print '' + + try: + device.open() + + j = 1 + for option in device.options.values(): + print_option_debug(j, option) + + print '' + j = j + 1 + + device.close() + except Exception: + print '\t**Failed to open device.**' + +def print_option_debug(j, option): + """Pretty-print device option information.""" + print '\tOption %i' % j + print '' + print '\tName:\t%s' % option._name + print '\tTitle:\t%s' % option._title + print '\tDesc:\t%s' % option._description + print '\tType:\t%s' % option._type + print '\tUnit:\t%s' % option._unit + print '\tSize:\t%s' % option._size + print '\tCap:\t%s' % option._capabilities + print '\tConstraint Type:\t%s' % option._constraint_type + print '\tConstraint:\t', option._constraint + + try: + print '\tValue:\t%s' % str(option.value) + except Exception: + print '\t**Failed to get current value for option.**' + +# Parse command line options +parser = optparse.OptionParser() +parser.add_option("--debugdevices", action="store_true", dest="debug_devices", + help="print debugging information for all connected devices") + +(options, args) = parser.parse_args() +if options.debug_devices: + import nostaples.sane as saneme + + sane_manager = saneme.SaneMe() + devices = sane_manager.get_device_list() + + if len(devices) == 0: + print 'No devices found.' + + i = 1 + for device in devices: + print_device_debug(i, device) + + print '' + i = i + 1 + + sys.exit() + +# Bootstrap application +from nostaples.application import Application nostaples = Application() -nostaples.run() +nostaples.run() \ No newline at end of file diff --git a/utils/scanning.py b/utils/scanning.py index 8bc810d..0e5b61d 100644 --- a/utils/scanning.py +++ b/utils/scanning.py @@ -1,173 +1,173 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module contains those functions (in the form of Thread objects) that interface with scanning hardware via SANE. """ import commands import logging import os import re import sys import tempfile import threading import gobject from nostaples import constants -from nostaples.sane import saneme +import nostaples.sane as saneme class IdleObject(gobject.GObject): """ Override gobject.GObject to always emit signals in the main thread by emitting on an idle handler. This class is based on an example by John Stowers: U{http://www.johnstowers.co.nz/blog/index.php/tag/pygtk/} """ def __init__(self): gobject.GObject.__init__(self) def emit(self, *args): gobject.idle_add(gobject.GObject.emit, self, *args) def abort_on_exception(func): """ This function decorator wraps the run() method of a thread so that any exceptions in that thread will be logged and cause the threads 'abort' signal to be emitted with the exception as an argument. This way all exception handling can occur on the main thread. Note that the entire sys.exc_info() tuple is passed out, this allows the current traceback to be used in the other thread. """ def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception, e: thread_object = args[0] exc_info = sys.exc_info() thread_object.log.error('Exception type %s: %s' % (e.__class__.__name__, e.message)) thread_object.emit('aborted', exc_info) return wrapper class UpdateAvailableScannersThread(IdleObject, threading.Thread): """ Responsible for getting an updated list of available scanners and passing it back to the main thread. """ __gsignals__ = { 'finished': ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)), 'aborted': ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)), } def __init__(self, sane): """ Initialize the thread. """ IdleObject.__init__(self) threading.Thread.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.sane = sane self.log.debug('Created.') @abort_on_exception def run(self): """ Queries SANE for a list of connected scanners and updates the list of available scanners from the results. """ self.log.debug('Updating available scanners.') devices = self.sane.get_device_list() # NB: We callback with the lists so that they can updated on the main thread self.emit('finished', devices) class ScanningThread(IdleObject, threading.Thread): """ Responsible for scanning a page and emitting status callbacks on the main thread. This thread should treat its reference to the ScanningModel as read-only. That way we don't have to worry about making the Model thread-safe. """ __gsignals__ = { 'progress': ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_INT)), 'succeeded': ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)), 'failed': ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)), 'aborted': ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)), } def __init__(self, sane_device): """ Initialize the thread and get a tempfile name that will house the scanned image. """ IdleObject.__init__(self) threading.Thread.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.sane_device = sane_device self.cancel_event = threading.Event() def progress_callback(self, scan_info, bytes_scanned): """ Pass the progress information on the the main thread and cancel the scan if the cancel event has been set. """ self.emit("progress", scan_info, bytes_scanned) if self.cancel_event.isSet(): return True else: return False @abort_on_exception def run(self): """ Set scanner options, scan a page and emit status callbacks. """ if not self.sane_device.is_open(): raise AssertionError('sane_device.is_open() returned false') self.log.debug('Beginning scan.') pil_image = None pil_image = self.sane_device.scan(self.progress_callback) if self.cancel_event.isSet(): self.emit("failed", "Scan cancelled") else: if not pil_image: raise AssertionError('sane_device.scan() returned None') self.emit('succeeded', pil_image) \ No newline at end of file
onyxfish/nostaples
5a74e307c00bf0a7d45354998c56e802e2bbafc0
Removed completely worthless page_model unit tests.
diff --git a/runtests.py b/runtests.py index a153a8e..cb5ab00 100755 --- a/runtests.py +++ b/runtests.py @@ -1,24 +1,37 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ Executing this module runs all the NoStaples unittests. Pass -v for detailed output. """ -import nose +import sys + +try: + import nose +except ImportError: + print 'You must have python-nose installed to run these tests.' + sys.exit() + +try: + import mock +except ImportError: + print 'You must have Michael Foord\'s Mock installed to run these tests.' + sys.exit() + nose.run() \ No newline at end of file diff --git a/unittests/models/test_page.py b/unittests/models/test_page.py deleted file mode 100644 index 0d8e10c..0000000 --- a/unittests/models/test_page.py +++ /dev/null @@ -1,35 +0,0 @@ -import os -import unittest - -from mock import Mock - -import Image, ImageDraw - -from nostaples.models.page import PageModel - -class TestPageModel(unittest.TestCase): - TEST_PAGE_WIDTH = 93 - TEST_PAGE_HEIGHT = 266 - - def setUp(self): - self.mock_application = Mock(spec=Application) - - image = Image.new('RGB', (self.TEST_PAGE_WIDTH, self.TEST_PAGE_HEIGHT)) - draw = ImageDraw.Draw(image) - - draw.line((0, 0) + image.size, fill=128) - draw.line((0, image.size[1], image.size[0], 0), fill=128) - del draw - - image.save('TestPageModel.png') - - self.page_model = PageModel(self.mock_application, 'TestPageModel.png') - - def tearDown(self): - os.remove('TestPageModel.png') - - def test_width(self): - self.assertEquals(self.page_model.width, self.TEST_PAGE_WIDTH) - - def test_height(self): - self.assertEquals(self.page_model.height, self.TEST_PAGE_HEIGHT) \ No newline at end of file
onyxfish/nostaples
1d62730605d78ec93d06c7310f0d7df0007735ee
Fixed long-ago broken unit tests.
diff --git a/README b/README index 72fdca7..0fcceca 100644 --- a/README +++ b/README @@ -1,8 +1,8 @@ Downloaded from: <http://www.etlafins.com/nostaples> Send Questions/Comments to: Christopher Groskopf -<[email protected]> +<[email protected]> \ No newline at end of file diff --git a/runtests.py b/runtests.py old mode 100644 new mode 100755 diff --git a/unittests/models/test_document.py b/unittests/models/test_document.py index fd3ea82..f8ee5aa 100644 --- a/unittests/models/test_document.py +++ b/unittests/models/test_document.py @@ -1,126 +1,126 @@ import unittest from mock import Mock from nostaples.application import Application from nostaples.models.document import DocumentModel from nostaples.models.page import PageModel class TestDocumentModel(unittest.TestCase): def setUp(self): self.mock_application = Mock(spec=Application) self.document_model = DocumentModel(self.mock_application) def tearDown(self): self.mock_application = None self.document_model = None def test_append(self): self.assertEqual(self.document_model.count, 0) - self.document_model.append(PageModel()) - self.document_model.append(PageModel()) - p = PageModel() + self.document_model.append(PageModel(self.mock_application)) + self.document_model.append(PageModel(self.mock_application)) + p = PageModel(self.mock_application) self.document_model.append(p) self.assertEqual(self.document_model.count, 3) self.assertEqual(self.document_model[2][0], p) def test_prepend(self): self.assertEqual(self.document_model.count, 0) - self.document_model.prepend(PageModel()) - self.document_model.prepend(PageModel()) - p = PageModel() + self.document_model.prepend(PageModel(self.mock_application)) + self.document_model.prepend(PageModel(self.mock_application)) + p = PageModel(self.mock_application) self.document_model.prepend(p) self.assertEqual(self.document_model.count, 3) self.assertEqual(self.document_model[0][0], p) def test_insert(self): self.assertEqual(self.document_model.count, 0) - p0 = PageModel() - p1 = PageModel() - p2 = PageModel() + p0 = PageModel(self.mock_application) + p1 = PageModel(self.mock_application) + p2 = PageModel(self.mock_application) self.document_model.insert(0, p2) self.document_model.insert(0, p0) self.document_model.insert(1, p1) self.assertEqual(self.document_model.count, 3) self.assertEqual(self.document_model[0][0], p0) self.assertEqual(self.document_model[1][0], p1) self.assertEqual(self.document_model[2][0], p2) def test_insert_before(self): self.assertEqual(self.document_model.count, 0) - p0 = PageModel() - p1 = PageModel() - p2 = PageModel() + p0 = PageModel(self.mock_application) + p1 = PageModel(self.mock_application) + p2 = PageModel(self.mock_application) iter = self.document_model.get_iter_root() self.document_model.insert_before(iter, p2) iter = self.document_model.get_iter(0) self.document_model.insert_before(iter, p0) iter = self.document_model.get_iter(1) self.document_model.insert_before(iter, p1) self.assertEqual(self.document_model.count, 3) self.assertEqual(self.document_model[0][0], p0) self.assertEqual(self.document_model[1][0], p1) self.assertEqual(self.document_model[2][0], p2) def test_insert_after(self): self.assertEqual(self.document_model.count, 0) - p0 = PageModel() - p1 = PageModel() - p2 = PageModel() + p0 = PageModel(self.mock_application) + p1 = PageModel(self.mock_application) + p2 = PageModel(self.mock_application) iter = self.document_model.get_iter_root() self.document_model.insert_after(iter, p0) iter = self.document_model.get_iter(0) self.document_model.insert_after(iter, p2) iter = self.document_model.get_iter(0) self.document_model.insert_after(iter, p1) self.assertEqual(self.document_model.count, 3) self.assertEqual(self.document_model[0][0], p0) self.assertEqual(self.document_model[1][0], p1) self.assertEqual(self.document_model[2][0], p2) def test_remove(self): self.assertEqual(self.document_model.count, 0) - p0 = PageModel() - p1 = PageModel() - p2 = PageModel() + p0 = PageModel(self.mock_application) + p1 = PageModel(self.mock_application) + p2 = PageModel(self.mock_application) self.document_model.append(p0) self.document_model.append(p1) self.document_model.append(p2) iter = self.document_model.get_iter(1) self.document_model.remove(iter) self.assertEqual(self.document_model.count, 2) self.assertEqual(self.document_model[0][0], p0) self.assertEqual(self.document_model[1][0], p2) def test_clear(self): self.assertEqual(self.document_model.count, 0) - p0 = PageModel() - p1 = PageModel() - p2 = PageModel() + p0 = PageModel(self.mock_application) + p1 = PageModel(self.mock_application) + p2 = PageModel(self.mock_application) self.document_model.append(p0) self.document_model.append(p1) self.document_model.append(p2) self.document_model.clear() self.assertEqual(self.document_model.count, 0) self.assertRaises(ValueError, self.document_model.get_iter, 0) \ No newline at end of file diff --git a/unittests/models/test_page.py b/unittests/models/test_page.py index 36c74ca..0d8e10c 100644 --- a/unittests/models/test_page.py +++ b/unittests/models/test_page.py @@ -1,31 +1,35 @@ import os import unittest +from mock import Mock + import Image, ImageDraw from nostaples.models.page import PageModel class TestPageModel(unittest.TestCase): TEST_PAGE_WIDTH = 93 TEST_PAGE_HEIGHT = 266 def setUp(self): + self.mock_application = Mock(spec=Application) + image = Image.new('RGB', (self.TEST_PAGE_WIDTH, self.TEST_PAGE_HEIGHT)) draw = ImageDraw.Draw(image) draw.line((0, 0) + image.size, fill=128) draw.line((0, image.size[1], image.size[0], 0), fill=128) del draw image.save('TestPageModel.png') - self.page_model = PageModel('TestPageModel.png') + self.page_model = PageModel(self.mock_application, 'TestPageModel.png') def tearDown(self): os.remove('TestPageModel.png') def test_width(self): self.assertEquals(self.page_model.width, self.TEST_PAGE_WIDTH) def test_height(self): self.assertEquals(self.page_model.height, self.TEST_PAGE_HEIGHT) \ No newline at end of file
onyxfish/nostaples
77dcc7fa35965d6c8b80b9fb7be8c53c807961f0
Minor cosmetic UI tweaks.
diff --git a/controllers/preferences.py b/controllers/preferences.py index 20a2c4b..91eb89a 100644 --- a/controllers/preferences.py +++ b/controllers/preferences.py @@ -1,216 +1,218 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{PreferencesController}, which manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ import logging import gtk from gtkmvc.controller import Controller from nostaples import constants from nostaples.utils.gui import read_combobox class PreferencesController(Controller): """ Manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the PreferencesController. """ self.application = application Controller.__init__(self, application.get_preferences_model()) application.get_main_model().register_observer(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ pass # USER INTERFACE CALLBACKS def on_preview_mode_combobox_changed(self, combobox): + """Update the preview mode in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.preview_mode = \ read_combobox(preferences_view['preview_mode_combobox']) def on_thumbnail_size_combobox_changed(self, combobox): + """Update the thumbnail size in the PreferencesModel.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.thumbnail_size = \ int(read_combobox(preferences_view['thumbnail_size_combobox'])) def on_remove_from_blacklist_button_clicked(self, button): """ Remove the currently selected blacklist device from the list. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['blacklist_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.remove(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_add_to_blacklist_button_clicked(self, button): """ Move the currently selected available scanner to the blacklist. """ main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['available_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(selection_text) preferences_model.blacklisted_scanners = temp_blacklist main_controller._update_available_scanners() def on_remove_from_keywords_button_clicked(self, button): """ Remove the currently selected keyword from the list. """ preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['keywords_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_keywords = list(preferences_model.saved_keywords) temp_keywords.remove(selection_text) preferences_model.saved_keywords = temp_keywords def on_preferences_dialog_response(self, dialog, response): """Close the preferences dialog.""" preferences_view = self.application.get_preferences_view() preferences_view['preferences_dialog'].hide() # PROPERTY CALLBACKS def property_unavailable_scanners_value_change(self, model, old_value, new_value): """Update unavailable scanners liststore.""" preferences_view = self.application.get_preferences_view() unavailable_liststore = preferences_view['unavailable_tree_view'].get_model() unavailable_liststore.clear() for unavailable_item in new_value: unavailable_liststore.append([unavailable_item]) def property_blacklisted_scanners_value_change(self, model, old_value, new_value): """Update blacklisted scanners liststore.""" preferences_view = self.application.get_preferences_view() blacklist_liststore = preferences_view['blacklist_tree_view'].get_model() blacklist_liststore.clear() for blacklist_item in new_value: blacklist_liststore.append([blacklist_item]) def property_available_scanners_value_change(self, model, old_value, new_value): """Update available scanners liststore.""" preferences_view = self.application.get_preferences_view() available_liststore = preferences_view['available_tree_view'].get_model() available_liststore.clear() for available_item in new_value: available_liststore.append([available_item.display_name]) def property_saved_keywords_value_change(self, model, old_value, new_value): """Update keywords liststore.""" preferences_view = self.application.get_preferences_view() keywords_liststore = preferences_view['keywords_tree_view'].get_model() keywords_liststore.clear() for keyword in new_value: keywords_liststore.append([keyword]) # PUBLIC METHODS def run(self): """Run the preferences dialog.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() # Force property updates when dialog is run: this handles the case # where the PreferencesController has not been created until now # so it has not been receiving property notifications. self.property_unavailable_scanners_value_change( preferences_model, None, preferences_model.unavailable_scanners) self.property_blacklisted_scanners_value_change( preferences_model, None, preferences_model.blacklisted_scanners) self.property_available_scanners_value_change( main_model, None, main_model.available_scanners) self.property_saved_keywords_value_change( preferences_model, None, preferences_model.saved_keywords) preferences_view.run() \ No newline at end of file diff --git a/controllers/save.py b/controllers/save.py index df78d0e..fd680fb 100644 --- a/controllers/save.py +++ b/controllers/save.py @@ -1,309 +1,309 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{SaveController}, which manages interaction between the L{SaveModel} and L{SaveView}. """ import logging import os import sys import tempfile import gtk from gtkmvc.controller import Controller import Image, ImageEnhance from reportlab.pdfgen.canvas import Canvas as PdfCanvas from reportlab.lib.pagesizes import landscape, portrait from reportlab.lib.units import inch as points_per_inch from nostaples import constants import nostaples.utils.gui class SaveController(Controller): """ Manages interaction between the L{SaveModel} and L{SaveView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the SaveController. """ self.application = application Controller.__init__(self, application.get_save_model()) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) preferences_model = self.application.get_preferences_model() save_model = self.application.get_save_model() # Force refresh of keyword list keywords_liststore = view['keywords_entry'].get_liststore() keywords_liststore.clear() for keyword in preferences_model.saved_keywords: keywords_liststore.append([keyword]) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ self.adapt('title', 'title_entry') self.adapt('author', 'author_entry') self.adapt('keywords', 'keywords_entry') self.adapt('show_document_metadata', 'document_metadata_expander') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS def on_title_from_filename_button_clicked(self, button): """ Copy the selected filename to the pdf title property. """ save_view = self.application.get_save_view() title = save_view['save_dialog'].get_filename() if not title: save_view['title_entry'].set_text('') return title = title.split('/')[-1] if title[-4:] == '.pdf': title = title[:-4] save_view['title_entry'].set_text(title) def on_clear_title_button_clicked(self, button): """Clear the title.""" self.application.get_save_model().title = '' def on_clear_author_button_clicked(self, button): """Clear the author.""" self.application.get_save_model().author = '' def on_clear_keywords_button_clicked(self, button): """Clear the keywords.""" self.application.get_save_model().keywords = '' def on_save_dialog_response(self, dialog, response): """ Determine the selected file type and invoke the method that saves that file type. """ save_model = self.application.get_save_model() save_view = self.application.get_save_view() main_view = self.application.get_main_view() save_view['save_dialog'].hide() if response != gtk.RESPONSE_ACCEPT: return main_view['scan_window'].window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH)) nostaples.utils.gui.flush_pending_events() save_model.filename = save_view['save_dialog'].get_filename() filename_filter = save_view['save_dialog'].get_filter() if filename_filter.get_name() == 'PDF Files': if save_model.filename[-4:] != '.pdf': save_model.filename = ''.join([save_model.filename, '.pdf']) self._save_pdf() else: self.log.error('Unknown file type: %s.' % save_model.filename) self._update_saved_keywords() main_view['scan_window'].window.set_cursor(None) save_model.save_path = save_view['save_dialog'].get_current_folder() - + # PROPERTY CALLBACKS def property_saved_keywords_value_change(self, model, old_value, new_value): """ Update the keywords auto-completion control with the new keywords. """ save_view = self.application.get_save_view() keywords_liststore = save_view['keywords_entry'].get_liststore() keywords_liststore.clear() for keyword in new_value: keywords_liststore.append([keyword]) # PRIVATE METHODS def _save_pdf(self): """ Output the current document to a PDF file using ReportLab. """ save_model = self.application.get_save_model() save_view = self.application.get_save_view() document_model = self.application.get_document_model() # TODO: seperate saving code into its own thread? # Setup output pdf pdf = PdfCanvas(save_model.filename) pdf.setTitle(save_model.title) pdf.setAuthor(save_model.author) pdf.setKeywords(save_model.keywords) # Generate pages page_iter = document_model.get_iter_first() while page_iter: current_page = document_model.get_value(page_iter, 0) # Write transformed image temp_file_path = ''.join([tempfile.mktemp(), '.bmp']) current_page.pil_image.save(temp_file_path) assert os.path.exists(temp_file_path), \ 'Temporary bitmap file was not created by PIL.' width_in_inches = \ int(current_page.width / current_page.resolution) height_in_inches = \ int(current_page.height / current_page.resolution) # NB: Because not all SANE backends support specifying the size # of the scan area, the best we can do is scan at the default # setting and then convert that to an appropriate PDF. For the # vast majority of scanners we hope that this would be either # letter or A4. pdf_width, pdf_height = self._determine_best_fitting_pagesize( width_in_inches, height_in_inches) pdf.setPageSize((pdf_width, pdf_height)) pdf.drawImage( temp_file_path, 0, 0, width=pdf_width, height=pdf_height, preserveAspectRatio=True) pdf.showPage() os.remove(temp_file_path) page_iter = document_model.iter_next(page_iter) # Save complete PDF pdf.save() assert os.path.exists(save_model.filename), \ 'Final PDF file was not created by ReportLab.' document_model.clear() def _determine_best_fitting_pagesize(self, width_in_inches, height_in_inches): """ Searches through the possible page sizes and finds the smallest one that will contain the image without cropping. """ image_width_in_points = width_in_inches * points_per_inch image_height_in_points = height_in_inches * points_per_inch nearest_size = None nearest_distance = sys.maxint for size in constants.PAGESIZES.values(): # Orient the size to match the page if image_width_in_points > image_height_in_points: size = landscape(size) else: size = portrait(size) # Only compare the size if its large enough to contain the entire # image if size[0] < image_width_in_points or \ size[1] < image_height_in_points: continue # Compute distance for comparison distance = \ size[0] - image_width_in_points + \ size[1] - image_height_in_points # Save if closer than prior nearest distance if distance < nearest_distance: nearest_distance = distance nearest_size = size # Stop searching if a perfect match is found if nearest_distance == 0: break assert nearest_size != None, 'No nearest size found.' return nearest_size def _update_saved_keywords(self): """ Update the saved keywords with any new keywords that have been used. """ preferences_model = self.application.get_preferences_model() save_model = self.application.get_save_model() new_keywords = [] for keyword in save_model.keywords.split(): if keyword not in preferences_model.saved_keywords: new_keywords.append(keyword) if new_keywords: temp_list = [] temp_list.extend(preferences_model.saved_keywords) temp_list.extend(new_keywords) temp_list.sort() preferences_model.saved_keywords = temp_list # PUBLIC METHODS def run(self): """Run the save dialog.""" save_model = self.application.get_save_model() save_view = self.application.get_save_view() status_controller = self.application.get_status_controller() save_view['save_dialog'].set_current_folder(save_model.save_path) save_view['save_dialog'].set_current_name('') status_controller.push(self.status_context, 'Saving...') save_view.run() status_controller.pop(self.status_context) \ No newline at end of file diff --git a/gui/preferences_dialog.glade b/gui/preferences_dialog.glade index b8ed8cc..8f2f9a3 100644 --- a/gui/preferences_dialog.glade +++ b/gui/preferences_dialog.glade @@ -1,350 +1,350 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> -<!--Generated with glade3 3.4.5 on Mon Feb 23 20:34:14 2009 --> +<!--Generated with glade3 3.4.5 on Fri Feb 27 20:10:04 2009 --> <glade-interface> <widget class="GtkDialog" id="preferences_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">NoStaples Preferences</property> <property name="resizable">False</property> <property name="modal">True</property> <property name="window_position">GTK_WIN_POS_CENTER_ON_PARENT</property> <property name="destroy_with_parent">True</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property> <property name="skip_taskbar_hint">True</property> <property name="skip_pager_hint">True</property> <property name="has_separator">False</property> <signal name="response" handler="on_preferences_dialog_response"/> <child internal-child="vbox"> <widget class="GtkVBox" id="dialog-vbox5"> <property name="visible">True</property> <property name="spacing">12</property> <signal name="add" handler="on_preferences_dialog_close"/> <child> <widget class="GtkNotebook" id="notebook1"> <property name="visible">True</property> <property name="can_focus">True</property> <child> <widget class="GtkAlignment" id="alignment6"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="spacing">6</property> <child> <widget class="GtkHBox" id="hbox2"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkLabel" id="label4"> <property name="visible">True</property> <property name="label" translatable="yes">Preview Scaling Mode:</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkComboBox" id="preview_mode_combobox"> <property name="visible">True</property> <property name="items" translatable="yes"></property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkHBox" id="hbox1"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkLabel" id="label5"> <property name="visible">True</property> <property name="label" translatable="yes">Thumbnail Size:</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkComboBox" id="thumbnail_size_combobox"> <property name="visible">True</property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </widget> </child> </widget> </child> <child> <widget class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">View</property> </widget> <packing> <property name="type">tab</property> <property name="tab_fill">False</property> </packing> </child> <child> <widget class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="label8"> <property name="visible">True</property> <property name="xalign">0</property> - <property name="label" translatable="yes">Unavailable devices:</property> + <property name="label" translatable="yes">Unsupported or unavailable devices:</property> <property name="wrap_mode">PANGO_WRAP_WORD_CHAR</property> </widget> </child> <child> <widget class="GtkScrolledWindow" id="unavailable_scrolled_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="shadow_type">GTK_SHADOW_IN</property> <child> <placeholder/> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkLabel" id="label7"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Blacklisted devices:</property> <property name="wrap_mode">PANGO_WRAP_WORD_CHAR</property> </widget> <packing> <property name="position">2</property> </packing> </child> <child> <widget class="GtkScrolledWindow" id="blacklist_scrolled_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="shadow_type">GTK_SHADOW_IN</property> <child> <placeholder/> </child> </widget> <packing> <property name="position">3</property> </packing> </child> <child> <widget class="GtkButton" id="remove_from_blacklist_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="label" translatable="yes">Remove from Blacklist</property> <property name="response_id">0</property> <signal name="clicked" handler="on_remove_from_blacklist_button_clicked"/> </widget> <packing> <property name="position">4</property> </packing> </child> <child> <widget class="GtkLabel" id="label9"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Available devices:</property> <property name="wrap_mode">PANGO_WRAP_WORD_CHAR</property> </widget> <packing> <property name="position">5</property> </packing> </child> <child> <widget class="GtkScrolledWindow" id="available_scrolled_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="shadow_type">GTK_SHADOW_IN</property> <child> <placeholder/> </child> </widget> <packing> <property name="position">6</property> </packing> </child> <child> <widget class="GtkButton" id="add_to_blacklist_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="label" translatable="yes">Add to Blacklist</property> <property name="response_id">0</property> <signal name="clicked" handler="on_add_to_blacklist_button_clicked"/> </widget> <packing> <property name="position">7</property> </packing> </child> </widget> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkLabel" id="label3"> <property name="visible">True</property> <property name="label" translatable="yes">Devices</property> </widget> <packing> <property name="type">tab</property> <property name="position">1</property> <property name="tab_fill">False</property> </packing> </child> <child> <widget class="GtkAlignment" id="alignment2"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="label6"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Keywords for autocompletion:</property> <property name="use_markup">True</property> <property name="wrap">True</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkScrolledWindow" id="keywords_scrolled_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="shadow_type">GTK_SHADOW_IN</property> <child> <placeholder/> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkAlignment" id="alignment3"> <property name="visible">True</property> <child> <widget class="GtkButton" id="remove_from_keywords_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="label" translatable="yes">Remove</property> <property name="response_id">0</property> <signal name="clicked" handler="on_remove_from_keywords_button_clicked"/> </widget> </child> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> </widget> </child> </widget> <packing> <property name="position">2</property> </packing> </child> <child> <widget class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">Documents</property> </widget> <packing> <property name="type">tab</property> <property name="position">2</property> <property name="tab_fill">False</property> </packing> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <widget class="GtkHButtonBox" id="dialog-action_area5"> <property name="visible">True</property> <property name="layout_style">GTK_BUTTONBOX_END</property> <child> <placeholder/> </child> <child> <widget class="GtkButton" id="preferences_close_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">gtk-close</property> <property name="use_stock">True</property> <property name="response_id">0</property> <signal name="clicked" handler="on_preferences_close_button_clicked"/> </widget> <packing> <property name="expand">False</property> <property name="pack_type">GTK_PACK_END</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="expand">False</property> <property name="pack_type">GTK_PACK_END</property> </packing> </child> </widget> </child> </widget> </glade-interface> diff --git a/gui/save_dialog.glade b/gui/save_dialog.glade index 82e66e2..dfbfb8c 100644 --- a/gui/save_dialog.glade +++ b/gui/save_dialog.glade @@ -1,261 +1,261 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> -<!--Generated with glade3 3.4.5 on Fri Feb 20 20:29:18 2009 --> +<!--Generated with glade3 3.4.5 on Tue Feb 24 19:53:22 2009 --> <glade-interface> <widget class="GtkFileChooserDialog" id="save_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">Save</property> <property name="modal">True</property> <property name="window_position">GTK_WIN_POS_CENTER_ON_PARENT</property> <property name="destroy_with_parent">True</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property> <property name="skip_taskbar_hint">True</property> <property name="skip_pager_hint">True</property> <property name="has_separator">False</property> <property name="use_preview_label">False</property> <property name="do_overwrite_confirmation">True</property> <property name="preview_widget_active">False</property> <property name="action">GTK_FILE_CHOOSER_ACTION_SAVE</property> <signal name="response" handler="on_save_dialog_response"/> <child internal-child="vbox"> <widget class="GtkVBox" id="dialog-vbox6"> <property name="visible">True</property> <property name="spacing">2</property> <child> <widget class="GtkExpander" id="document_metadata_expander"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="expanded">True</property> <child> <widget class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">6</property> <child> <widget class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkHBox" id="hbox1"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="label2"> <property name="width_request">80</property> <property name="visible">True</property> <property name="xalign">1</property> <property name="label" translatable="yes">&lt;b&gt;Title:&lt;/b&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkEntry" id="title_entry"> <property name="visible">True</property> <property name="can_focus">True</property> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkButton" id="title_from_filename_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="tooltip" translatable="yes">Copy from filename</property> <property name="response_id">0</property> <signal name="clicked" handler="on_title_from_filename_button_clicked"/> <child> <widget class="GtkImage" id="image1"> <property name="visible">True</property> <property name="stock">gtk-copy</property> <property name="icon_size">1</property> </widget> </child> </widget> <packing> <property name="expand">False</property> <property name="position">2</property> </packing> </child> <child> <widget class="GtkButton" id="clear_title_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="tooltip" translatable="yes">Clear</property> <property name="response_id">0</property> <signal name="clicked" handler="on_clear_title_button_clicked"/> <child> <widget class="GtkImage" id="image2"> <property name="visible">True</property> <property name="stock">gtk-clear</property> <property name="icon_size">1</property> </widget> </child> </widget> <packing> <property name="expand">False</property> <property name="position">3</property> </packing> </child> </widget> </child> <child> <widget class="GtkHBox" id="hbox2"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="label3"> <property name="width_request">80</property> <property name="visible">True</property> <property name="xalign">1</property> <property name="label" translatable="yes">&lt;b&gt;Author:&lt;/b&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkEntry" id="author_entry"> <property name="visible">True</property> <property name="can_focus">True</property> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkButton" id="clear_author_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="tooltip" translatable="yes">Clear</property> <property name="response_id">0</property> <signal name="clicked" handler="on_clear_author_button_clicked"/> <child> <widget class="GtkImage" id="image3"> <property name="visible">True</property> <property name="stock">gtk-clear</property> <property name="icon_size">1</property> </widget> </child> </widget> <packing> <property name="expand">False</property> <property name="position">2</property> </packing> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkHBox" id="keywords_hbox"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="label4"> <property name="width_request">80</property> <property name="visible">True</property> <property name="xalign">1</property> <property name="label" translatable="yes">&lt;b&gt;Keywords:&lt;/b&gt;</property> <property name="use_markup">True</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <placeholder/> </child> <child> <widget class="GtkButton" id="clear_keywords_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="tooltip" translatable="yes">Clear</property> <property name="response_id">0</property> <signal name="clicked" handler="on_clear_keywords_button_clicked"/> <child> <widget class="GtkImage" id="image4"> <property name="visible">True</property> <property name="stock">gtk-clear</property> <property name="icon_size">1</property> </widget> </child> </widget> <packing> <property name="expand">False</property> <property name="pack_type">GTK_PACK_END</property> <property name="position">2</property> </packing> </child> </widget> <packing> <property name="position">2</property> </packing> </child> </widget> </child> </widget> </child> <child> <widget class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">Document Metadata</property> </widget> <packing> <property name="type">label_item</property> </packing> </child> </widget> <packing> <property name="expand">False</property> <property name="position">2</property> </packing> </child> <child internal-child="action_area"> <widget class="GtkHButtonBox" id="dialog-action_area6"> <property name="visible">True</property> <property name="layout_style">GTK_BUTTONBOX_END</property> <child> <widget class="GtkButton" id="button2"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="label" translatable="yes">gtk-cancel</property> <property name="use_stock">True</property> <property name="response_id">-6</property> </widget> </child> <child> <widget class="GtkButton" id="button1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="can_default">True</property> <property name="has_default">True</property> <property name="receives_default">True</property> <property name="label" translatable="yes">gtk-save</property> <property name="use_stock">True</property> <property name="response_id">-3</property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="expand">False</property> <property name="pack_type">GTK_PACK_END</property> </packing> </child> </widget> </child> </widget> </glade-interface>
onyxfish/nostaples
8adc981f40b351b506ca650f478740d277f02518
Changing the preview scale mode will not update the preview image immediately.
diff --git a/controllers/page.py b/controllers/page.py index b6dc2f0..f62ba5e 100644 --- a/controllers/page.py +++ b/controllers/page.py @@ -1,492 +1,498 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{PageController}, which manages interaction between the L{PageModel} and L{PageView}. """ import logging import gtk from gtkmvc.controller import Controller from nostaples import constants class PageController(Controller): """ Manages interaction between the L{PageModel} and L{PageView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the PageController. """ self.application = application Controller.__init__(self, application.get_null_page_model()) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) + + application.get_preferences_model().register_observer(self) self.log = logging.getLogger(self.__class__.__name__) # The preview pixbuf is cached so it can be rerendered without # reapplying zoom transformations. self.preview_pixbuf = None # Non persistent settings that apply to all scanned pages self.preview_width = 0 self.preview_height = 0 self.preview_zoom = 1.0 self.preview_is_best_fit = False # TODO: should be a gconf preference self.preview_zoom_rect_color = \ gtk.gdk.colormap_get_system().alloc_color( gtk.gdk.Color(65535, 0, 0), False, True) # Reusable temp vars to hold the start point of a mouse drag action. self.zoom_drag_start_x = 0 self.zoom_drag_start_y = 0 self.move_drag_start_x = 0 self.move_drag_start_y = 0 self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) # USER INTERFACE CALLBACKS def on_page_view_image_layout_button_press_event(self, widget, event): """ Begins a drag or zoom event. """ # Do not process mouse events if nothing is visible if not self.model.pixbuf: return if event.button == 1: self._begin_move(event.x, event.y) elif event.button == 3: self._begin_zoom(event.x, event.y) def on_page_view_image_layout_motion_notify_event(self, widget, event): """ Update the preview during a drag or zoom event. """ # Do not process mouse events if nothing is visible if not self.model.pixbuf: return # Handle both hint events and routine notifications # See: http://www.pygtk.org/pygtk2tutorial/sec-EventHandling.html if event.is_hint: mouse_state = event.window.get_pointer()[2] else: mouse_state = event.state # Move if (mouse_state & gtk.gdk.BUTTON1_MASK): self._update_move(event.x_root, event.y_root) # Zoom elif (mouse_state & gtk.gdk.BUTTON3_MASK): self._update_zoom(event.x, event.y) # NB: These need to be updated even if the button wasn't pressed self.move_drag_start_x = event.x_root self.move_drag_start_y = event.y_root def on_page_view_image_layout_button_release_event(self, widget, event): """ Ends a drag or zoom event. """ # Do not process mouse events if nothing is visible if not self.model.pixbuf: return # Move if event.button == 1: self._end_move() # Zoom elif event.button == 3: self._end_zoom(event.x, event.y) def on_page_view_image_layout_scroll_event(self, widget, event): """ TODO: Mouse scroll event. Go to next/prev page? Or scroll image? """ pass def on_page_view_image_layout_size_request(self, widget, size): size.width = 1 size.height = 1 def on_page_view_image_layout_size_allocate(self, widget, allocation): """ Resizes the image preview size to match that which is allocated to the preview layout widget. TODO: Resize of image does not occur until after the window has finished resizing (which looks awful). """ if allocation.width == self.preview_width and \ allocation.height == self.preview_height: return self.preview_width = allocation.width self.preview_height = allocation.height self._update_preview() # PROPERTY CALLBACKS def property_pixbuf_value_change(self, model, old_value, new_value): - """ - Update the preview display. - """ + """Update the preview display.""" + self._update_preview() + + # PreferencesModel PROPERTY CALLBACKS + + def property_preview_mode_value_change(self, model, old_value, new_value): + """Update the preview display.""" self._update_preview() # PUBLIC METHODS def get_current_page_model(self): """ Return the currently visible/selected page model. This may be the null page model. """ return self.model def set_current_page_model(self, page_model): """ Sets the PageModel that is currently being displayed in the preview area. """ self.model.unregister_observer(self) self.model = page_model self.model.register_observer(self) self._update_preview() def zoom_in(self): """ Zooms the preview image in. """ # TODO: max zoom should be a gconf preference if self.preview_zoom == 5: return # TODO: zoom amount should be a gconf preference self.preview_zoom += 0.5 if self.preview_zoom > 5: self.preview_zoom = 5 self.preview_is_best_fit = False self._update_preview() def zoom_out(self): """ Zooms the preview image out. """ # TODO: min zoom should be a gconf preference if self.preview_zoom == 1.0: return self.preview_zoom -= 0.5 if self.preview_zoom < 0.5: self.preview_zoom = 0.5 self.preview_is_best_fit = False self._update_preview() def zoom_one_to_one(self): """ Zooms the preview image to its true size. """ self.preview_zoom = 1.0 self.preview_is_best_fit = False self._update_preview() def zoom_best_fit(self): """ Zooms the preview image so the entire image will fit within the preview window. """ self.preview_is_best_fit = True self._update_preview() # PRIVATE (INTERNAL) METHODS def _begin_move(self, x, y): """ Determines if there is anything to be dragged and if so, sets the 'drag' cursor. """ page_view = self.application.get_page_view() if page_view['page_view_horizontal_scrollbar'].get_property('visible') and \ page_view['page_view_vertical_scrollbar'].get_property('visible'): return page_view['page_view_image'].get_parent_window().set_cursor( gtk.gdk.Cursor(gtk.gdk.FLEUR)) def _begin_zoom(self, x, y): """ Saves the starting position of the zoom and sets the 'zoom' cursor. """ page_view = self.application.get_page_view() page_view['page_view_image'].get_parent_window().set_cursor( gtk.gdk.Cursor(gtk.gdk.CROSS)) self.zoom_drag_start_x = x self.zoom_drag_start_y = y def _update_move(self, x, y): """ Moves/drags the preview in response to mouse movement. """ page_view = self.application.get_page_view() horizontal_adjustment = \ page_view['page_view_image_layout'].get_hadjustment() new_x = horizontal_adjustment.value + \ (self.move_drag_start_x - x) if new_x >= horizontal_adjustment.lower and \ new_x <= horizontal_adjustment.upper - horizontal_adjustment.page_size: horizontal_adjustment.set_value(new_x) vertical_adjustment = \ page_view['page_view_image_layout'].get_vadjustment() new_y = vertical_adjustment.value + \ (self.move_drag_start_y - y) if new_y >= vertical_adjustment.lower and \ new_y <= vertical_adjustment.upper - vertical_adjustment.page_size: vertical_adjustment.set_value(new_y) def _update_zoom(self, x, y): """ Renders a box around the zoom region the user has specified by dragging the mouse. """ page_view = self.application.get_page_view() start_x = self.zoom_drag_start_x start_y = self.zoom_drag_start_y end_x = x end_y = y if end_x < start_x: start_x, end_x = end_x, start_x if end_y < start_y: start_y, end_y = end_y, start_y width = end_x - start_x height = end_y - start_y page_view['page_view_image'].set_from_pixbuf(self.preview_pixbuf) page_view['page_view_image'].get_parent_window().invalidate_rect( (0, 0, self.preview_width, self.preview_height), False) page_view['page_view_image'].get_parent_window(). \ process_updates(False) graphics_context = \ page_view['page_view_image'].get_parent_window().new_gc( foreground=self.preview_zoom_rect_color, line_style=gtk.gdk.LINE_ON_OFF_DASH, line_width=2) page_view['page_view_image'].get_parent_window().draw_rectangle( graphics_context, False, int(start_x), int(start_y), int(width), int(height)) def _end_move(self): """ Resets to the default cursor. """ page_view = self.application.get_page_view() page_view['page_view_image'].get_parent_window().set_cursor(None) def _end_zoom(self, x, y): """ Calculates and applies zoom to the preview and updates the display. """ page_view = self.application.get_page_view() # Transform to absolute coords start_x = self.zoom_drag_start_x / self.preview_zoom start_y = self.zoom_drag_start_y / self.preview_zoom end_x = x / self.preview_zoom end_y = y / self.preview_zoom # Swizzle values if coords are reversed if end_x < start_x: start_x, end_x = end_x, start_x if end_y < start_y: start_y, end_y = end_y, start_y # Calc width and height width = end_x - start_x height = end_y - start_y # Calculate centering offset target_width = \ self.model.width * self.preview_zoom target_height = \ self.model.height * self.preview_zoom shift_x = int((self.preview_width - target_width) / 2) if shift_x < 0: shift_x = 0 shift_y = int((self.preview_height - target_height) / 2) if shift_y < 0: shift_y = 0 # Compensate for centering start_x -= shift_x / self.preview_zoom start_y -= shift_y / self.preview_zoom # Determine center-point of zoom region center_x = start_x + width / 2 center_y = start_y + height / 2 # Determine correct zoom to fit region if width > height: self.preview_zoom = self.preview_width / width else: self.preview_zoom = self.preview_height / height # Cap zoom at 500% if self.preview_zoom > 5.0: self.preview_zoom = 5.0 # Transform center-point to relative coords transform_x = int(center_x * self.preview_zoom) transform_y = int(center_y * self.preview_zoom) # Center in preview display transform_x -= int(self.preview_width / 2) transform_y -= int(self.preview_height / 2) self.preview_is_best_fit = False self._update_preview() page_view['page_view_image_layout'].get_hadjustment().set_value( transform_x) page_view['page_view_image_layout'].get_vadjustment().set_value( transform_y) page_view['page_view_image'].get_parent_window().set_cursor(None) def _update_preview(self): """ Render the current page to the preview display. """ page_view = self.application.get_page_view() preferences_model = self.application.get_preferences_model() status_controller = self.application.get_status_controller() # Short circuit if the PageModel does not have a pixbuf # (such as the null page). if not self.model.pixbuf: page_view['page_view_image'].clear() status_controller.pop(self.status_context) return # Fit if necessary if self.preview_is_best_fit: width_ratio = float(self.model.width) / self.preview_width height_ratio = float(self.model.height) / self.preview_height if width_ratio < height_ratio: self.preview_zoom = 1 / float(height_ratio) else: self.preview_zoom = 1 / float(width_ratio) # Zoom if necessary if self.preview_zoom != 1.0: target_width = \ int(self.model.width * self.preview_zoom) target_height = \ int(self.model.height * self.preview_zoom) gtk_scale_mode = \ constants.PREVIEW_MODES[preferences_model.preview_mode] self.preview_pixbuf = self.model.pixbuf.scale_simple( target_width, target_height, gtk_scale_mode) else: target_width = self.model.width target_height = self.model.height self.preview_pixbuf = self.model.pixbuf # Resize preview area page_view['page_view_image_layout'].set_size( target_width, target_height) # Center preview shift_x = int((self.preview_width - target_width) / 2) if shift_x < 0: shift_x = 0 shift_y = int((self.preview_height - target_height) / 2) if shift_y < 0: shift_y = 0 page_view['page_view_image_layout'].move( page_view['page_view_image'], shift_x, shift_y) # Show/hide scrollbars if target_width > self.preview_width: page_view['page_view_horizontal_scrollbar'].show() else: page_view['page_view_horizontal_scrollbar'].hide() if target_height > self.preview_height: page_view['page_view_vertical_scrollbar'].show() else: page_view['page_view_vertical_scrollbar'].hide() # Render updated preview page_view['page_view_image'].set_from_pixbuf(self.preview_pixbuf) # Update status status_controller.pop(self.status_context) status_controller.push(self.status_context, "%.0f%%" % (self.preview_zoom * 100)) \ No newline at end of file
onyxfish/nostaples
1ee9381d4b98ce0eea81f4d6a9f2487fcd5dc5db
Expanded device handling preferences.
diff --git a/controllers/main.py b/controllers/main.py index 5506069..dcfb430 100644 --- a/controllers/main.py +++ b/controllers/main.py @@ -1,752 +1,761 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{MainController}, which manages interaction between the L{MainModel} and L{MainView}. """ import commands import logging import os import re import threading import gobject import gtk from gtkmvc.controller import Controller from nostaples.models.page import PageModel from nostaples.utils.scanning import * import saneme class MainController(Controller): """ Manages interaction between the L{MainModel} and L{MainView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the MainController, as well as necessary sub-controllers and services. """ self.application = application Controller.__init__(self, application.get_main_model()) application.get_document_model().register_observer(self) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ self.adapt('show_toolbar', 'show_toolbar_menu_item') self.adapt('show_statusbar', 'show_statusbar_menu_item') self.adapt('show_thumbnails', 'show_thumbnails_menu_item') self.adapt('show_adjustments', 'show_adjustments_menu_item') self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS # Menu Items def on_scan_window_destroy(self, window): """Exits the application.""" self.quit() def on_scan_menu_item_activate(self, menu_item): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_menu_item_activate(self, menu_item): """Refresh the list of connected scanners from SANE.""" self._update_available_scanners() def on_save_as_menu_item_activate(self, menu_item): """Saves the current document to a file.""" self.application.show_save_dialog() def on_delete_menu_item_activate(self, menu_item): self.application.get_document_controller().delete_selected() def on_preferences_menu_item_activate(self, menu_item): """Creates and displays a preferences dialog.""" self.application.show_preferences_dialog() def on_quit_menu_item_activate(self, menu_item): """Exits the application.""" self.quit() def on_zoom_in_menu_item_activate(self, menu_item): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_menu_item_activate(self, menu_item): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_menu_item_activate(self, menu_item): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_menu_item_activate(self, menu_item): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_available_scanner_menu_item_toggled(self, menu_item): """ Set the active scanner. TODO: Need a second scanner to properly test this... """ main_model = self.application.get_main_model() if menu_item.get_active(): for scanner in main_model.available_scanners: if scanner.display_name == menu_item.get_children()[0].get_text(): main_model.active_scanner = scanner return def on_valid_mode_menu_item_toggled(self, menu_item): """Sets the active scan mode.""" if menu_item.get_active(): self.application.get_main_model().active_mode = \ menu_item.get_children()[0].get_text() def on_valid_resolution_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_resolution = \ menu_item.get_children()[0].get_text() def on_go_first_menu_item_activate(self, menu_item): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_menu_item_activate(self, menu_item): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_menu_item_activate(self, menu_item): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_menu_item_activate(self, menu_item): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() def on_contents_menu_item_clicked(self, menu_item): """TODO""" pass def on_about_menu_item_activate(self, menu_item): """Show the about dialog.""" self.application.show_about_dialog() # Toolbar Buttons def on_scan_button_clicked(self, button): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_button_clicked(self, button): self._update_available_scanners() def on_save_as_button_clicked(self, button): """Saves the current document to a file.""" self.application.show_save_dialog() def on_zoom_in_button_clicked(self, button): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_button_clicked(self, button): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_button_clicked(self, button): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_button_clicked(self, button): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_go_first_button_clicked(self, button): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_button_clicked(self, button): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_button_clicked(self, button): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_button_clicked(self, button): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() # Progress Window INTERFACE CALLBACKS def on_progress_window_delete_event(self, window, event): """ Emulate clicking of the cancel/close button and then hide the window. """ main_view = self.application.get_main_view() self.on_scan_cancel_button_clicked(None) main_view['progress_window'].hide() return True def on_scan_cancel_button_clicked(self, button): """ Cancel the current scan or, if the scan is finished, close the progress window. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress: assert self.cancel_event self.cancel_event.set() else: main_view['progress_window'].hide() def on_scan_again_button_clicked(self, button): """Initiate a new scan from the progress window.""" self._scan() def on_quick_save_button_clicked(self, button): """ Show the save dialog. If the user completes a save then disable the quick save button until another page is scanned. """ main_view = self.application.get_main_view() document_model = self.application.get_document_model() self.application.show_save_dialog() if document_model.count == 0: main_view['quick_save_button'].set_sensitive(False) # MainModel PROPERTY CALLBACKS def property_show_toolbar_value_change(self, model, old_value, new_value): """Update the visibility of the toolbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_toolbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['main_toolbar'].show() else: main_view['main_toolbar'].hide() def property_show_statusbar_value_change(self, model, old_value, new_value): """Update the visibility of the statusbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_statusbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['status_view_docking_viewport'].show() else: main_view['status_view_docking_viewport'].hide() def property_show_thumbnails_value_change(self, model, old_value, new_value): """Update the visibility of the thumbnails.""" main_view = self.application.get_main_view() menu_item = main_view['show_thumbnails_menu_item'] menu_item.set_active(new_value) self.application.get_document_controller().toggle_thumbnails_visible(new_value) def property_show_adjustments_value_change(self, model, old_value, new_value): """Update the visibility of the adjustments controls.""" document_controller = self.application.get_document_controller() main_view = self.application.get_main_view() menu_item = main_view['show_adjustments_menu_item'] menu_item.set_active(new_value) document_controller.toggle_adjustments_visible(new_value) def property_active_scanner_value_change(self, model, old_value, new_value): """ Update the menu and valid scanner options to match the new device. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() + if new_value == None: + return + for menu_item in main_view['scanner_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value.display_name: menu_item.set_active(True) break def property_active_mode_value_change(self, model, old_value, new_value): """Select the active mode from in the menu.""" main_view = self.application.get_main_view() + if new_value == None: + return + for menu_item in main_view['scan_mode_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_resolution_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() + if new_value == None: + return + for menu_item in main_view['scan_resolution_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_available_scanners_value_change(self, model, old_value, new_value): """ Update the menu of available scanners. """ main_view = self.application.get_main_view() self._clear_available_scanners_sub_menu() # Generate the new menu if len(new_value) == 0: menu_item = gtk.MenuItem('No Scanners Connected') menu_item.set_sensitive(False) main_view['scanner_sub_menu'].append(menu_item) else: first_item = None for i in range(len(new_value)): # The first menu item defines the group if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i].display_name) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i].display_name) main_view['scanner_sub_menu'].append(menu_item) main_view['scanner_sub_menu'].show_all() def property_valid_modes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan modes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_modes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Modes") menu_item.set_sensitive(False) main_view['scan_mode_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled) main_view['scan_mode_sub_menu'].append(menu_item) main_view['scan_mode_sub_menu'].show_all() def property_valid_resolutions_value_change(self, model, old_value, new_value): """ Updates the list of valid scan resolutions for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_resolutions_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Resolutions") menu_item.set_sensitive(False) main_view['scan_resolution_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled) main_view['scan_resolution_sub_menu'].append(menu_item) main_view['scan_resolution_sub_menu'].show_all() def property_scan_in_progress_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() def property_updating_available_scanners_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() # DocumentModel PROPERTY CALLBACKS def property_count_value_change(self, model, old_value, new_value): """Toggle available controls.""" self._toggle_document_controls() # THREAD CALLBACKS def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned): main_view = self.application.get_main_view() short_bytes_scanned = float(bytes_scanned) / 1000 short_total_bytes = float(scan_info.total_bytes) / 1000 main_view['scan_progressbar'].set_fraction( float(bytes_scanned) / scan_info.total_bytes) main_view['scan_progressbar'].set_text( 'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes)) # TODO: multi page scans main_view['progress_secondary_label'].set_markup( '<i>Scanning page.</i>') def on_scan_succeeded(self, scanning_thread, pil_image): """ Append the new page to the current document. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['scan_progressbar'].set_fraction(1) main_view['scan_progressbar'].set_text('Scan complete') main_view['progress_secondary_label'].set_markup( '<i>Adding page to document.</i>') gtk.gdk.flush() new_page = PageModel(self.application, pil_image, int(main_model.active_resolution)) self.application.get_document_model().append(new_page) main_view['progress_secondary_label'].set_markup( '<i>Page added.</i>') main_view['scan_again_button'].set_sensitive(True) main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_failed(self, scanning_thread, reason): """ Set that scan is complete. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['progress_secondary_label'].set_markup( '<i>%s</i>' % reason) main_view['scan_again_button'].set_sensitive(True) if self.application.get_document_model().count > 0: main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_aborted(self, scanning_thread, exc_info): """ Change display to indicate that scanning failed and convey the to the user the reason why the thread aborted. If the failure was from a SANE exception then give the user the option to blacklist the device. If not, then reraise the error and let the sys.excepthook deal with it. """ self.on_scan_failed(scanning_thread, 'An error occurred.') if isinstance(exc_info[1], saneme.SaneError): self.run_device_exception_dialog(exc_info) else: raise exc_info[0], exc_info[1], exc_info[2] def on_update_available_scanners_thread_finished(self, update_thread, scanner_list): """Set the new list of available scanners.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() status_controller = self.application.get_status_controller() # Remove blacklisted scanners scanner_list = \ [scanner for scanner in scanner_list if not \ scanner.display_name in preferences_model.blacklisted_scanners] # Remove scanners that do not support necessary options or fail to # open entirely preferences_model.unavailable_scanners = [] for scanner in scanner_list: try: scanner.open() if not scanner.has_option('mode') or \ not scanner.has_option('resolution'): preferences_model.unavailable_scanners.append(scanner.display_name) scanner_list.remove(scanner) scanner.close() except saneme.SaneError: preferences_model.unavailable_scanners.append(scanner.display_name) scanner_list.remove(scanner) main_model.available_scanners = scanner_list main_model.updating_available_scanners = False def on_update_available_scanners_thread_aborted(self, update_thread, exc_info): """ Change the display to indicate that no scanners are available and reraise the exception so that it can be caught by the sys.excepthook. There is no reason to handle these cases with a special dialog, if the application failed to even enumerate the available devices then no other action will be possible. This should be fantastically rare. """ self.on_update_available_scanners_thread_finished(update_thread, []) raise exc_info[0], exc_info[1], exc_info[2] # PUBLIC METHODS def quit(self): """Exits the application.""" self.log.debug('Quit.') gtk.main_quit() def run_device_exception_dialog(self, exc_info): """ Display an error dialog that provides the user with the option of blacklisting the device which caused the error. TODO: Move into MainView. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() preferences_model = self.application.get_preferences_model() response = main_view.run_device_exception_dialog(exc_info) if response == constants.RESPONSE_BLACKLIST_DEVICE: temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(exc_info[1].device.display_name) temp_blacklist.sort() preferences_model.blacklisted_scanners = temp_blacklist # PRIVATE METHODS def _clear_available_scanners_sub_menu(self): """Clear the menu of available scanners.""" main_view = self.application.get_main_view() for child in main_view['scanner_sub_menu'].get_children(): main_view['scanner_sub_menu'].remove(child) def _clear_scan_modes_sub_menu(self): """Clear the menu of valid scan modes.""" main_view = self.application.get_main_view() for child in main_view['scan_mode_sub_menu'].get_children(): main_view['scan_mode_sub_menu'].remove(child) def _clear_scan_resolutions_sub_menu(self): """Clear the menu of valid scan resolutions.""" main_view = self.application.get_main_view() for child in main_view['scan_resolution_sub_menu'].get_children(): main_view['scan_resolution_sub_menu'].remove(child) def _toggle_scan_controls(self): """Toggle whether or not the scan controls or accessible.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_scan_controls_sensitive(False) main_view.set_refresh_scanner_controls_sensitive(False) else: if main_model.active_scanner != None: main_view.set_scan_controls_sensitive(True) main_view.set_refresh_scanner_controls_sensitive(True) def _toggle_document_controls(self): """ Toggle available document controls based on the current scanner status and the number of scanned pages. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() # Disable all controls when the scanner is in use if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: count = self.application.get_document_model().count # Disable all controls if no pages are scanned if count == 0: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: # Enable most controls if any pages scanned main_view.set_file_controls_sensitive(True) main_view.set_delete_controls_sensitive(True) main_view.set_zoom_controls_sensitive(True) main_view.set_adjustment_controls_sensitive(True) # Only enable navigation if more than one page scanned if count > 1: main_view.set_navigation_controls_sensitive(True) else: main_view.set_navigation_controls_sensitive(False) def _update_status(self): """ Update the text of the statusbar based on the current state of the application. """ main_model = self.application.get_main_model() status_controller = self.application.get_status_controller() status_controller.pop(self.status_context) if main_model.scan_in_progress: status_controller.push(self.status_context, 'Scanning...') elif main_model.updating_available_scanners: status_controller.push(self.status_context, 'Querying hardware...') else: if main_model.active_scanner: status_controller.push(self.status_context, 'Ready with %s.' % main_model.active_scanner.display_name) else: status_controller.push(self.status_context, 'No scanner available.') def _scan(self): """Begin a scan.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() main_model.scan_in_progress = True scanning_thread = ScanningThread(main_model.active_scanner) scanning_thread.connect("progress", self.on_scan_progress) scanning_thread.connect("succeeded", self.on_scan_succeeded) scanning_thread.connect("failed", self.on_scan_failed) scanning_thread.connect("aborted", self.on_scan_aborted) self.cancel_event = scanning_thread.cancel_event main_view['progress_primary_label'].set_markup( '<big><b>%s</b></big>' % main_model.active_scanner.display_name) main_view['scan_progressbar'].set_fraction(0) main_view['scan_progressbar'].set_text('Waiting for data') main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>') mode = main_model.active_mode if main_model.active_mode else 'Not set' main_view['progress_mode_label'].set_markup(mode) dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set' main_view['progress_resolution_label'].set_markup(dpi) main_view['scan_again_button'].set_sensitive(False) main_view['quick_save_button'].set_sensitive(False) main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL) main_view['progress_window'].show_all() scanning_thread.start() def _update_available_scanners(self): """ Start a new update thread to query for available scanners. """ sane = self.application.get_sane() main_model = self.application.get_main_model() main_model.updating_available_scanners = True update_thread = UpdateAvailableScannersThread(sane) update_thread.connect("finished", self.on_update_available_scanners_thread_finished) update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted) update_thread.start() \ No newline at end of file diff --git a/controllers/preferences.py b/controllers/preferences.py index 4fd7c15..20a2c4b 100644 --- a/controllers/preferences.py +++ b/controllers/preferences.py @@ -1,154 +1,216 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{PreferencesController}, which manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ import logging import gtk from gtkmvc.controller import Controller from nostaples import constants from nostaples.utils.gui import read_combobox class PreferencesController(Controller): """ Manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the PreferencesController. """ self.application = application Controller.__init__(self, application.get_preferences_model()) + application.get_main_model().register_observer(self) + self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ pass # USER INTERFACE CALLBACKS def on_preview_mode_combobox_changed(self, combobox): preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.preview_mode = \ read_combobox(preferences_view['preview_mode_combobox']) def on_thumbnail_size_combobox_changed(self, combobox): preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.thumbnail_size = \ int(read_combobox(preferences_view['thumbnail_size_combobox'])) def on_remove_from_blacklist_button_clicked(self, button): """ Remove the currently selected blacklist device from the list. """ + main_controller = self.application.get_main_controller() preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['blacklist_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.remove(selection_text) preferences_model.blacklisted_scanners = temp_blacklist + + main_controller._update_available_scanners() + + def on_add_to_blacklist_button_clicked(self, button): + """ + Move the currently selected available scanner to the blacklist. + """ + main_controller = self.application.get_main_controller() + preferences_model = self.application.get_preferences_model() + preferences_view = self.application.get_preferences_view() + + model, selection_iter = \ + preferences_view['available_tree_view'].get_selection().get_selected() + + if not selection_iter: + return + + selection_text = model.get_value(selection_iter, 0) + model.remove(selection_iter) + + temp_blacklist = list(preferences_model.blacklisted_scanners) + temp_blacklist.append(selection_text) + preferences_model.blacklisted_scanners = temp_blacklist + + main_controller._update_available_scanners() def on_remove_from_keywords_button_clicked(self, button): """ Remove the currently selected keyword from the list. """ preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['keywords_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_keywords = list(preferences_model.saved_keywords) temp_keywords.remove(selection_text) preferences_model.saved_keywords = temp_keywords def on_preferences_dialog_response(self, dialog, response): """Close the preferences dialog.""" preferences_view = self.application.get_preferences_view() preferences_view['preferences_dialog'].hide() + + # PROPERTY CALLBACKS - # PUBLIC METHODS - - def run(self): - """Run the preferences dialog.""" - preferences_model = self.application.get_preferences_model() + def property_unavailable_scanners_value_change(self, model, old_value, new_value): + """Update unavailable scanners liststore.""" preferences_view = self.application.get_preferences_view() - # Refresh unavailable scanners unavailable_liststore = preferences_view['unavailable_tree_view'].get_model() unavailable_liststore.clear() - for unavailable_item in preferences_model.unavailable_scanners: + for unavailable_item in new_value: unavailable_liststore.append([unavailable_item]) + + def property_blacklisted_scanners_value_change(self, model, old_value, new_value): + """Update blacklisted scanners liststore.""" + preferences_view = self.application.get_preferences_view() - # Refresh blacklist blacklist_liststore = preferences_view['blacklist_tree_view'].get_model() blacklist_liststore.clear() - for blacklist_item in preferences_model.blacklisted_scanners: + for blacklist_item in new_value: blacklist_liststore.append([blacklist_item]) + + def property_available_scanners_value_change(self, model, old_value, new_value): + """Update available scanners liststore.""" + preferences_view = self.application.get_preferences_view() + + available_liststore = preferences_view['available_tree_view'].get_model() + available_liststore.clear() + + for available_item in new_value: + available_liststore.append([available_item.display_name]) - # Refresh keywords + def property_saved_keywords_value_change(self, model, old_value, new_value): + """Update keywords liststore.""" + preferences_view = self.application.get_preferences_view() + keywords_liststore = preferences_view['keywords_tree_view'].get_model() keywords_liststore.clear() - for keyword in preferences_model.saved_keywords: + for keyword in new_value: keywords_liststore.append([keyword]) + + # PUBLIC METHODS + + def run(self): + """Run the preferences dialog.""" + main_model = self.application.get_main_model() + preferences_model = self.application.get_preferences_model() + preferences_view = self.application.get_preferences_view() + + # Force property updates when dialog is run: this handles the case + # where the PreferencesController has not been created until now + # so it has not been receiving property notifications. + self.property_unavailable_scanners_value_change( + preferences_model, None, preferences_model.unavailable_scanners) + self.property_blacklisted_scanners_value_change( + preferences_model, None, preferences_model.blacklisted_scanners) + self.property_available_scanners_value_change( + main_model, None, main_model.available_scanners) + self.property_saved_keywords_value_change( + preferences_model, None, preferences_model.saved_keywords) preferences_view.run() \ No newline at end of file diff --git a/gui/preferences_dialog.glade b/gui/preferences_dialog.glade index a9b0c8d..b8ed8cc 100644 --- a/gui/preferences_dialog.glade +++ b/gui/preferences_dialog.glade @@ -1,313 +1,350 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> -<!--Generated with glade3 3.4.5 on Sun Feb 22 20:48:25 2009 --> +<!--Generated with glade3 3.4.5 on Mon Feb 23 20:34:14 2009 --> <glade-interface> <widget class="GtkDialog" id="preferences_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">NoStaples Preferences</property> <property name="resizable">False</property> <property name="modal">True</property> <property name="window_position">GTK_WIN_POS_CENTER_ON_PARENT</property> <property name="destroy_with_parent">True</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property> <property name="skip_taskbar_hint">True</property> <property name="skip_pager_hint">True</property> <property name="has_separator">False</property> <signal name="response" handler="on_preferences_dialog_response"/> <child internal-child="vbox"> <widget class="GtkVBox" id="dialog-vbox5"> <property name="visible">True</property> <property name="spacing">12</property> <signal name="add" handler="on_preferences_dialog_close"/> <child> <widget class="GtkNotebook" id="notebook1"> <property name="visible">True</property> <property name="can_focus">True</property> <child> <widget class="GtkAlignment" id="alignment6"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="spacing">6</property> <child> <widget class="GtkHBox" id="hbox2"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkLabel" id="label4"> <property name="visible">True</property> <property name="label" translatable="yes">Preview Scaling Mode:</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkComboBox" id="preview_mode_combobox"> <property name="visible">True</property> <property name="items" translatable="yes"></property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkHBox" id="hbox1"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkLabel" id="label5"> <property name="visible">True</property> <property name="label" translatable="yes">Thumbnail Size:</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkComboBox" id="thumbnail_size_combobox"> <property name="visible">True</property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="expand">False</property> <property name="position">1</property> </packing> </child> </widget> </child> </widget> </child> <child> <widget class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">View</property> </widget> <packing> <property name="type">tab</property> <property name="tab_fill">False</property> </packing> </child> <child> <widget class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="label8"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Unavailable devices:</property> <property name="wrap_mode">PANGO_WRAP_WORD_CHAR</property> </widget> </child> <child> <widget class="GtkScrolledWindow" id="unavailable_scrolled_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="shadow_type">GTK_SHADOW_IN</property> <child> <placeholder/> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkLabel" id="label7"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Blacklisted devices:</property> <property name="wrap_mode">PANGO_WRAP_WORD_CHAR</property> </widget> <packing> <property name="position">2</property> </packing> </child> <child> <widget class="GtkScrolledWindow" id="blacklist_scrolled_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="shadow_type">GTK_SHADOW_IN</property> <child> <placeholder/> </child> </widget> <packing> <property name="position">3</property> </packing> </child> <child> <widget class="GtkButton" id="remove_from_blacklist_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> - <property name="label" translatable="yes">Remove</property> + <property name="label" translatable="yes">Remove from Blacklist</property> <property name="response_id">0</property> <signal name="clicked" handler="on_remove_from_blacklist_button_clicked"/> </widget> <packing> - <property name="expand">False</property> - <property name="fill">False</property> <property name="position">4</property> </packing> </child> + <child> + <widget class="GtkLabel" id="label9"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="label" translatable="yes">Available devices:</property> + <property name="wrap_mode">PANGO_WRAP_WORD_CHAR</property> + </widget> + <packing> + <property name="position">5</property> + </packing> + </child> + <child> + <widget class="GtkScrolledWindow" id="available_scrolled_window"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> + <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> + <property name="shadow_type">GTK_SHADOW_IN</property> + <child> + <placeholder/> + </child> + </widget> + <packing> + <property name="position">6</property> + </packing> + </child> + <child> + <widget class="GtkButton" id="add_to_blacklist_button"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="receives_default">True</property> + <property name="label" translatable="yes">Add to Blacklist</property> + <property name="response_id">0</property> + <signal name="clicked" handler="on_add_to_blacklist_button_clicked"/> + </widget> + <packing> + <property name="position">7</property> + </packing> + </child> </widget> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkLabel" id="label3"> <property name="visible">True</property> <property name="label" translatable="yes">Devices</property> </widget> <packing> <property name="type">tab</property> <property name="position">1</property> <property name="tab_fill">False</property> </packing> </child> <child> <widget class="GtkAlignment" id="alignment2"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="label6"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Keywords for autocompletion:</property> <property name="use_markup">True</property> <property name="wrap">True</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkScrolledWindow" id="keywords_scrolled_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="shadow_type">GTK_SHADOW_IN</property> <child> <placeholder/> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkAlignment" id="alignment3"> <property name="visible">True</property> <child> <widget class="GtkButton" id="remove_from_keywords_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="label" translatable="yes">Remove</property> <property name="response_id">0</property> <signal name="clicked" handler="on_remove_from_keywords_button_clicked"/> </widget> </child> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> </widget> </child> </widget> <packing> <property name="position">2</property> </packing> </child> <child> <widget class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">Documents</property> </widget> <packing> <property name="type">tab</property> <property name="position">2</property> <property name="tab_fill">False</property> </packing> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <widget class="GtkHButtonBox" id="dialog-action_area5"> <property name="visible">True</property> <property name="layout_style">GTK_BUTTONBOX_END</property> <child> <placeholder/> </child> <child> <widget class="GtkButton" id="preferences_close_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">gtk-close</property> <property name="use_stock">True</property> <property name="response_id">0</property> <signal name="clicked" handler="on_preferences_close_button_clicked"/> </widget> <packing> <property name="expand">False</property> <property name="pack_type">GTK_PACK_END</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="expand">False</property> <property name="pack_type">GTK_PACK_END</property> </packing> </child> </widget> </child> </widget> </glade-interface> diff --git a/models/main.py b/models/main.py index 8afba06..00db148 100644 --- a/models/main.py +++ b/models/main.py @@ -1,320 +1,321 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.utils.properties import saneme class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # saneme.Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Open the new scanner and write its name to the StateManager. Note: This and all other propertys setters related to scanner hardware will force notifications to all observers by setting the old_value parameter to None when calling notify_property_value_change(). This has the effect of making changes in the active scanner or its available options propagate down to the active mode and other dependent properties. This way the GUI and the settings applied to the SANE device are kept synchronized. """ main_controller = self.application.get_main_controller() # Ignore spurious updates old_value = self._prop_active_scanner # Close the old scanner if isinstance(old_value, saneme.Device): - old_value.close() + if old_value.is_open(): + old_value.close() # Verify that the proper type is being set if value is not None: assert isinstance(value, saneme.Device) # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it can be opened without error. # This prevents problems with trying to store a Null # value in the state backend and also allows for smooth # transitions if a scanner is disconnected and reconnected. if value is not None: try: value.open() self.valid_modes = value.options['mode'].constraint self.valid_resolutions = \ [str(i) for i in value.options['resolution'].constraint] except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notification to all observers. self.notify_property_value_change( 'active_scanner', old_value, value) def set_prop_active_mode(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ self._prop_active_mode = value if value is not None: # This catches the case where the value is being loaded from state # but a scanner has not yet been activated. if self.active_scanner: try: self.active_scanner.options['mode'].value = value except saneme.SaneReloadOptionsError: # TODO pass self.application.get_state_manager()['scan_mode'] = value self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Update the scanner options and write state to the StateManager. See L{set_prop_active_scanner} for detailed comments. """ self._prop_active_resolution = value if value is not None: # This catches the case where the value is being loaded from state # but a scanner has not yet been activated. if self.active_scanner: try: self.active_scanner.options['resolution'].value = int(value) except saneme.SaneReloadOptionsError: # TODO pass self.application.get_state_manager()['scan_resolution'] = value self.notify_property_value_change( 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ Set the list of available scanners and update the active_scanner. See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() self._prop_available_scanners = value # Force notification self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None else: # Select the first available scanner if the previously # selected scanner is not in the new list if self._prop_active_scanner not in value: self.active_scanner = value[0] # Otherwise maintain current selection else: self.active_scanner = self.active_scanner def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, update the active mode and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) # Update the active mode if len(value) == 0: self.active_mode = None else: if self.active_mode not in value: self.active_mode = value[0] else: self.active_mode = self.active_mode def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, update the active resolution and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) # Update the active resolution if len(value) == 0: self.active_resolution = None else: if self.active_resolution not in value: self.active_resolution = value[0] else: self.active_resolution = self.active_resolution # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name(state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution diff --git a/views/preferences.py b/views/preferences.py index fead3ca..e34894e 100644 --- a/views/preferences.py +++ b/views/preferences.py @@ -1,138 +1,155 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the PreferencesView which exposes user settings through a dialog seperate from the main application window. """ import logging import os import gtk from gtkmvc.view import View from nostaples import constants from nostaples.utils.gui import read_combobox, setup_combobox class PreferencesView(View): """ Exposes user settings through a dialog seperate from the main application window. """ def __init__(self, application): """ Constructs the PreferencesView, including setting up controls that could not be configured in Glade. """ self.application = application preferences_controller = application.get_preferences_controller() preferences_dialog_glade = os.path.join( constants.GUI_DIRECTORY, 'preferences_dialog.glade') View.__init__( self, preferences_controller, preferences_dialog_glade, 'preferences_dialog', None, False) self.log = logging.getLogger(self.__class__.__name__) # Can not configure this via constructor do to the multiple # root windows in the Main View. self['preferences_dialog'].set_transient_for( application.get_main_view()['scan_window']) # These two combobox's are setup dynamically. Because of this they # must have their signal handlers connected manually. Otherwise # their signals will fire before the view creation is finished. setup_combobox( self['preview_mode_combobox'], constants.PREVIEW_MODES_LIST, application.get_preferences_model().preview_mode) self['preview_mode_combobox'].connect( 'changed', preferences_controller.on_preview_mode_combobox_changed) setup_combobox( self['thumbnail_size_combobox'], constants.THUMBNAIL_SIZE_LIST, application.get_preferences_model().thumbnail_size) self['thumbnail_size_combobox'].connect( 'changed', preferences_controller.on_thumbnail_size_combobox_changed) # Setup the unavailable scanners tree view unavailable_liststore = gtk.ListStore(str) self['unavailable_tree_view'] = gtk.TreeView() self['unavailable_tree_view'].set_model(unavailable_liststore) self['unavailable_column'] = gtk.TreeViewColumn(None) self['unavailable_cell'] = gtk.CellRendererText() self['unavailable_tree_view'].append_column(self['unavailable_column']) self['unavailable_column'].pack_start(self['unavailable_cell'], True) self['unavailable_column'].add_attribute( self['unavailable_cell'], 'text', 0) self['unavailable_tree_view'].get_selection().set_mode( gtk.SELECTION_NONE) self['unavailable_tree_view'].set_headers_visible(False) self['unavailable_tree_view'].set_property('can-focus', False) self['unavailable_scrolled_window'].add(self['unavailable_tree_view']) self['unavailable_scrolled_window'].show_all() # Setup the blacklist tree view blacklist_liststore = gtk.ListStore(str) self['blacklist_tree_view'] = gtk.TreeView() self['blacklist_tree_view'].set_model(blacklist_liststore) self['blacklist_column'] = gtk.TreeViewColumn(None) self['blacklist_cell'] = gtk.CellRendererText() self['blacklist_tree_view'].append_column(self['blacklist_column']) self['blacklist_column'].pack_start(self['blacklist_cell'], True) self['blacklist_column'].add_attribute(self['blacklist_cell'], 'text', 0) self['blacklist_tree_view'].get_selection().set_mode( gtk.SELECTION_SINGLE) self['blacklist_tree_view'].set_headers_visible(False) self['blacklist_tree_view'].set_property('can-focus', False) self['blacklist_scrolled_window'].add(self['blacklist_tree_view']) self['blacklist_scrolled_window'].show_all() # Setup the keywords tree view keywords_liststore = gtk.ListStore(str) self['keywords_tree_view'] = gtk.TreeView() self['keywords_tree_view'].set_model(keywords_liststore) self['keywords_column'] = gtk.TreeViewColumn(None) self['keywords_cell'] = gtk.CellRendererText() self['keywords_tree_view'].append_column(self['keywords_column']) self['keywords_column'].pack_start(self['keywords_cell'], True) self['keywords_column'].add_attribute(self['keywords_cell'], 'text', 0) self['keywords_tree_view'].get_selection().set_mode( gtk.SELECTION_SINGLE) self['keywords_tree_view'].set_headers_visible(False) self['keywords_tree_view'].set_property('can-focus', False) self['keywords_scrolled_window'].add(self['keywords_tree_view']) self['keywords_scrolled_window'].show_all() + # Setup the available devices tree view + available_liststore = gtk.ListStore(str) + self['available_tree_view'] = gtk.TreeView() + self['available_tree_view'].set_model(available_liststore) + self['available_column'] = gtk.TreeViewColumn(None) + self['available_cell'] = gtk.CellRendererText() + self['available_tree_view'].append_column(self['available_column']) + self['available_column'].pack_start(self['available_cell'], True) + self['available_column'].add_attribute(self['available_cell'], 'text', 0) + self['available_tree_view'].get_selection().set_mode( + gtk.SELECTION_SINGLE) + self['available_tree_view'].set_headers_visible(False) + self['available_tree_view'].set_property('can-focus', False) + + self['available_scrolled_window'].add(self['available_tree_view']) + self['available_scrolled_window'].show_all() + application.get_preferences_controller().register_view(self) self.log.debug('Created.') def run(self): """Run the modal preferences dialog.""" self['preferences_dialog'].run() \ No newline at end of file
onyxfish/nostaples
7c952683ea612b8ce00a02c3ec585aec750883cc
Minor changes to support better device management (improved logging).
diff --git a/sane/saneme.py b/sane/saneme.py index 248b915..4ef85d5 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -1,863 +1,866 @@ #!/usr/bin/python #~ This file is part of SaneMe. #~ SaneMe is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ SaneMe is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with SaneMe. If not, see <http://www.gnu.org/licenses/>. """ This module contains the Pythonic implementation of the SANE API. The flat C functions have been wrapped in a set of objects and all ctypes of the underlying implmentation have been hidden from the user's view. This enumerations and definiations which are absolutely necessary to the end user have been redeclared. """ # TODO: document what exceptions can be thrown by each method, # including those that could bubble up from array import * import atexit import ctypes from types import * from PIL import Image from errors import * from saneh import * # Redeclare saneh enumerations which are visible to the application (OPTION_TYPE_BOOL, OPTION_TYPE_INT, OPTION_TYPE_FIXED, OPTION_TYPE_STRING, OPTION_TYPE_BUTTON, OPTION_TYPE_GROUP) = xrange(6) (OPTION_UNIT_NONE, OPTION_UNIT_PIXEL, OPTION_UNIT_BIT, OPTION_UNIT_MM, OPTION_UNIT_DPI, OPTION_UNIT_PERCENT, OPTION_UNIT_MICROSECOND) = xrange(7) (OPTION_CONSTRAINT_NONE, OPTION_CONSTRAINT_RANGE, OPTION_CONSTRAINT_INTEGER_LIST, OPTION_CONSTRAINT_STRING_LIST) = xrange(4) class SaneMe(object): """ The top-level object for interacting with the SANE API. Handles polling for devices. This object should only be instantiated once. """ _log = None _version = None # (major, minor, build) _devices = [] def __init__(self, log=None): """ Create the SANE object, perform setup, and register the cleanup function. @param log: an optional Python logging object to log to. """ self._log = log self._setup() atexit.register(self._shutdown) # Read only properties def __get_version(self): """Get the current installed version of SANE.""" return self._version version = property(__get_version) def _setup(self): """ Iniitalize SANE and retrieve the current installed version. """ version_code = SANE_Int() auth_callback = SANE_Auth_Callback(self._sane_auth_callback) status = sane_init(byref(version_code), auth_callback) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_init returned an invalid status: %i.' % status) self._version = (SANE_VERSION_MAJOR(version_code), SANE_VERSION_MINOR(version_code), SANE_VERSION_BUILD(version_code)) if self._log: - self._log.debug('SANE version %s initalized.', self._version) + self._log.info('SANE version %s initalized.', self._version) def _sane_auth_callback(self, resource, username, password): """ TODO """ raise NotImplementedError( 'sane_auth_callback requested, but not yet implemented.') def _shutdown(self): """ Deinitialize SANE. This code would go in L{__del__}, but it is not guaranteed that method will be called and sane_exit must be called to release resources. To ensure this method is called it is registered with atexit. """ for device in self._devices: if device.is_open(): device.close() sane_exit() self._version = None if self._log: - self._log.debug('SANE deinitialized.') + self._log.info('SANE deinitialized.') # Public Methods def get_device_list(self): """ Poll for connected devices. This method may take several seconds to return. Note that SANE is exited and re-inited before querying for devices to workaround a limitation in SANE's USB driver which causes the device list to only be updated on init. This means that all settings applied to all devices will be B{lost} and must be restored by the calling application. This was found documented here: U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html} """ if not self._version: raise AssertionError('version was None') # See docstring for details on this voodoo self._shutdown() self._setup() cdevices = POINTER(POINTER(SANE_Device))() status = sane_get_devices(byref(cdevices), SANE_Bool(0)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_get_devices ran out of memory.') else: raise SaneUnknownError( 'sane_get_devices returned an invalid status: %i.' % status) device_count = 0 self._devices = [] while cdevices[device_count]: - self._devices.append(Device(cdevices[device_count].contents)) + self._devices.append( + Device(cdevices[device_count].contents, self._log)) device_count += 1 if self._log: - self._log.debug('SANE queried, %i device(s) found.', device_count) + self._log.info('SANE queried, %i device(s) found.', device_count) return self._devices def get_device_by_name(self, name): """ Retrieve a L{Device} by name. Must be preceded by a call to L{get_device_list}. """ for device in self._devices: if device.name == name: return device raise SaneNoSuchDeviceError( 'The requested device does not exist.') class Device(object): """ This is the primary object for interacting with SANE. It represents a single device and handles enumeration of options, getting and setting of options, and starting and stopping of scanning jobs. """ _log = None _handle = None _name = '' _vendor = '' _model = '' _type = '' _display_name = '' _options = {} def __init__(self, ctypes_device, log=None): """ Sets the Devices properties from a ctypes SANE_Device and queries for its available options. """ self._log = log # String attributes should never be None self._name = ctypes_device.name if ctypes_device.name else '' self._vendor = ctypes_device.vendor if ctypes_device.vendor else '' self._model = ctypes_device.model if ctypes_device.model else '' self._type = ctypes_device.type if ctypes_device.type else '' self._display_name = ' '.join([self._vendor, self._model]) # Read only properties def __get_name(self): """ Get the complete SANE identifier for this device, e.g. 'lexmark:libusb:002:006'. """ return self._name name = property(__get_name) def __get_vendor(self): """Get the manufacturer of this device, e.g. 'Lexmark'.""" return self._vendor vendor = property(__get_vendor) def __get_model(self): """Get the specific model of this device, e.g. 'X1100/rev. B2'.""" return self._model model = property(__get_model) def __get_type(self): """Get the type of this device, e.g. 'flatbed scanner'.""" return self._type type = property(__get_type) def __get_display_name(self): """ Get an appropriate name to use for displaying this device to a user, e.g. 'Lexmark X1100/rev. B2'.""" return self._display_name display_name = property(__get_display_name) def __get_options(self): """Get the dictionary of options that this device has.""" return self._options options = property(__get_options) # Internal methods def _update_options(self): """ Update the list of available options for this device. As these are immutable, this should only need to be called when the Device is first instantiated. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') option_value = pointer(c_int()) - status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) + status = sane_control_option( + self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: raise SaneUnsupportedOperationError( 'sane_control_option reported that a value was outside the option\'s constraint.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) option_count = option_value.contents.value if self._log: self._log.debug('Device queried, %i option(s) found.', option_count) self._options.clear() i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) - self._options[coption.contents.name] = Option(self, i, coption.contents) + self._options[coption.contents.name] = Option( + self, i, coption.contents, self._log) i = i + 1 # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Public methods def open(self): """ Open a new handle to this device. - Must be called before any operations (including setting options) - are performed on this device. + Must be called before any operations (including getting or setting + options) are performed on this device. """ if self._handle: raise AssertionError('device handle already exists.') self._handle = SANE_Handle() status = sane_open(self.name, byref(self._handle)) # If and exception will be thrown, nullify device handle # so is_open() will return false for the device. if status != SANE_STATUS_GOOD.value: self._handle = None if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_open reported that the device was busy.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) self._update_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) def has_option(self, option_name): """Return true if option_name is available for this scanner.""" return (option_name in self.options.keys()) def scan(self, progress_callback=None): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) elif sane_parameters.format == SANE_FRAME_RGB.value: pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capabilities = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number # String attributes should never be None self._name = ctypes_option.name if ctypes_option.name else '' self._title = ctypes_option.title if ctypes_option.title else '' self._description = ctypes_option.desc if ctypes_option.desc else '' self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 # Read only properties def __get_name(self): """ Get the short-form name of this option, e.g. 'mode'. May be an empty string, but never None. """ return self._name name = property(__get_name) def __get_title(self): """ Get the full name of this option, e.g. 'Scan mode'. May be an empty string, but never None. """ return self._title title = property(__get_title) def __get_description(self): """ Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' May be an empty string, but never None. """ return self._description description = property(__get_description) def __get_type(self): return self._type type = property(__get_type) def __get_unit(self): return self._unit unit = property(__get_unit) def __get_capability(self): # TODO: break out into individual capabilities, rather than a bitset return self._capability capability = property(__get_capability) def __get_constraint_type(self): return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then this is a list of integers which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """ Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option( handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i.' % status, device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value else: option_value = option_value.contents.value if self._log: self._log.debug( 'Option %s queried, its current value is %s.', self._name, option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: raise TypeError( 'option set with %s, expected BooleanType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: raise TypeError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: raise ValueError( 'value for option is longer than max string size') c_value = c_char_p(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: if value < self._constraint[0]: raise ValueError('value for option is less than min.') if value > self._constraint[1]: raise ValueError('value for option is greater than max.') if value % self._constraint[2] != 0: raise ValueError( 'value for option is not divisible by step.') elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: raise ValueError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value:
onyxfish/nostaples
82a8fcec2f826339e5d525c40a23812d2cfdf385
Removed automated options polling that was a temporary fix for NoStaples.
diff --git a/sane/saneme.py b/sane/saneme.py index ba14a31..248b915 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -1,745 +1,741 @@ #!/usr/bin/python #~ This file is part of SaneMe. #~ SaneMe is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ SaneMe is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with SaneMe. If not, see <http://www.gnu.org/licenses/>. """ This module contains the Pythonic implementation of the SANE API. The flat C functions have been wrapped in a set of objects and all ctypes of the underlying implmentation have been hidden from the user's view. This enumerations and definiations which are absolutely necessary to the end user have been redeclared. """ # TODO: document what exceptions can be thrown by each method, # including those that could bubble up from array import * import atexit import ctypes from types import * from PIL import Image from errors import * from saneh import * # Redeclare saneh enumerations which are visible to the application (OPTION_TYPE_BOOL, OPTION_TYPE_INT, OPTION_TYPE_FIXED, OPTION_TYPE_STRING, OPTION_TYPE_BUTTON, OPTION_TYPE_GROUP) = xrange(6) (OPTION_UNIT_NONE, OPTION_UNIT_PIXEL, OPTION_UNIT_BIT, OPTION_UNIT_MM, OPTION_UNIT_DPI, OPTION_UNIT_PERCENT, OPTION_UNIT_MICROSECOND) = xrange(7) (OPTION_CONSTRAINT_NONE, OPTION_CONSTRAINT_RANGE, OPTION_CONSTRAINT_INTEGER_LIST, OPTION_CONSTRAINT_STRING_LIST) = xrange(4) class SaneMe(object): """ The top-level object for interacting with the SANE API. Handles polling for devices. This object should only be instantiated once. """ _log = None _version = None # (major, minor, build) _devices = [] def __init__(self, log=None): """ Create the SANE object, perform setup, and register the cleanup function. @param log: an optional Python logging object to log to. """ self._log = log self._setup() atexit.register(self._shutdown) # Read only properties def __get_version(self): """Get the current installed version of SANE.""" return self._version version = property(__get_version) def _setup(self): """ Iniitalize SANE and retrieve the current installed version. """ version_code = SANE_Int() auth_callback = SANE_Auth_Callback(self._sane_auth_callback) status = sane_init(byref(version_code), auth_callback) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_init returned an invalid status: %i.' % status) self._version = (SANE_VERSION_MAJOR(version_code), SANE_VERSION_MINOR(version_code), SANE_VERSION_BUILD(version_code)) if self._log: self._log.debug('SANE version %s initalized.', self._version) def _sane_auth_callback(self, resource, username, password): """ TODO """ raise NotImplementedError( 'sane_auth_callback requested, but not yet implemented.') def _shutdown(self): """ Deinitialize SANE. This code would go in L{__del__}, but it is not guaranteed that method will be called and sane_exit must be called to release resources. To ensure this method is called it is registered with atexit. """ for device in self._devices: if device.is_open(): device.close() sane_exit() self._version = None if self._log: self._log.debug('SANE deinitialized.') # Public Methods def get_device_list(self): """ Poll for connected devices. This method may take several seconds to return. Note that SANE is exited and re-inited before querying for devices to workaround a limitation in SANE's USB driver which causes the device list to only be updated on init. This means that all settings applied to all devices will be B{lost} and must be restored by the calling application. This was found documented here: U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html} """ if not self._version: raise AssertionError('version was None') # See docstring for details on this voodoo self._shutdown() self._setup() cdevices = POINTER(POINTER(SANE_Device))() status = sane_get_devices(byref(cdevices), SANE_Bool(0)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_get_devices ran out of memory.') else: raise SaneUnknownError( 'sane_get_devices returned an invalid status: %i.' % status) device_count = 0 self._devices = [] while cdevices[device_count]: self._devices.append(Device(cdevices[device_count].contents)) device_count += 1 if self._log: self._log.debug('SANE queried, %i device(s) found.', device_count) return self._devices def get_device_by_name(self, name): """ Retrieve a L{Device} by name. Must be preceded by a call to L{get_device_list}. """ for device in self._devices: if device.name == name: return device raise SaneNoSuchDeviceError( 'The requested device does not exist.') class Device(object): """ This is the primary object for interacting with SANE. It represents a single device and handles enumeration of options, getting and setting of options, and starting and stopping of scanning jobs. """ _log = None _handle = None _name = '' _vendor = '' _model = '' _type = '' _display_name = '' _options = {} def __init__(self, ctypes_device, log=None): """ Sets the Devices properties from a ctypes SANE_Device and queries for its available options. """ self._log = log # String attributes should never be None self._name = ctypes_device.name if ctypes_device.name else '' self._vendor = ctypes_device.vendor if ctypes_device.vendor else '' self._model = ctypes_device.model if ctypes_device.model else '' self._type = ctypes_device.type if ctypes_device.type else '' self._display_name = ' '.join([self._vendor, self._model]) - # Temporarily open the device to populate its options - self.open() - self.close() - # Read only properties def __get_name(self): """ Get the complete SANE identifier for this device, e.g. 'lexmark:libusb:002:006'. """ return self._name name = property(__get_name) def __get_vendor(self): """Get the manufacturer of this device, e.g. 'Lexmark'.""" return self._vendor vendor = property(__get_vendor) def __get_model(self): """Get the specific model of this device, e.g. 'X1100/rev. B2'.""" return self._model model = property(__get_model) def __get_type(self): """Get the type of this device, e.g. 'flatbed scanner'.""" return self._type type = property(__get_type) def __get_display_name(self): """ Get an appropriate name to use for displaying this device to a user, e.g. 'Lexmark X1100/rev. B2'.""" return self._display_name display_name = property(__get_display_name) def __get_options(self): """Get the dictionary of options that this device has.""" return self._options options = property(__get_options) # Internal methods def _update_options(self): """ Update the list of available options for this device. As these are immutable, this should only need to be called when the Device is first instantiated. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') option_value = pointer(c_int()) status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: raise SaneUnsupportedOperationError( 'sane_control_option reported that a value was outside the option\'s constraint.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) option_count = option_value.contents.value if self._log: self._log.debug('Device queried, %i option(s) found.', option_count) self._options.clear() i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) self._options[coption.contents.name] = Option(self, i, coption.contents) i = i + 1 # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Public methods def open(self): """ Open a new handle to this device. Must be called before any operations (including setting options) are performed on this device. """ if self._handle: raise AssertionError('device handle already exists.') self._handle = SANE_Handle() status = sane_open(self.name, byref(self._handle)) # If and exception will be thrown, nullify device handle # so is_open() will return false for the device. if status != SANE_STATUS_GOOD.value: self._handle = None if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_open reported that the device was busy.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) self._update_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) def has_option(self, option_name): """Return true if option_name is available for this scanner.""" return (option_name in self.options.keys()) def scan(self, progress_callback=None): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) elif sane_parameters.format == SANE_FRAME_RGB.value: pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capabilities = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number # String attributes should never be None self._name = ctypes_option.name if ctypes_option.name else '' self._title = ctypes_option.title if ctypes_option.title else '' self._description = ctypes_option.desc if ctypes_option.desc else '' self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 # Read only properties def __get_name(self): """ Get the short-form name of this option, e.g. 'mode'. May be an empty string, but never None. """ return self._name name = property(__get_name) def __get_title(self): """ Get the full name of this option, e.g. 'Scan mode'. May be an empty string, but never None. """ return self._title title = property(__get_title) def __get_description(self): """ Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' May be an empty string, but never None. """ return self._description description = property(__get_description) def __get_type(self): return self._type type = property(__get_type) def __get_unit(self): return self._unit unit = property(__get_unit) def __get_capability(self): # TODO: break out into individual capabilities, rather than a bitset return self._capability capability = property(__get_capability) def __get_constraint_type(self): return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then this is a list of integers which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """ Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, # see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option(
onyxfish/nostaples
cd2d5cd385c8a407b0beb5cf56fb59df556bd27b
Removed extraneous value-checking and handled cases where c_char_p may be None/null.
diff --git a/sane/saneme.py b/sane/saneme.py index 3b59113..ba14a31 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -1,1009 +1,969 @@ #!/usr/bin/python #~ This file is part of SaneMe. #~ SaneMe is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ SaneMe is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with SaneMe. If not, see <http://www.gnu.org/licenses/>. """ This module contains the Pythonic implementation of the SANE API. The flat C functions have been wrapped in a set of objects and all ctypes of the underlying implmentation have been hidden from the user's view. This enumerations and definiations which are absolutely necessary to the end user have been redeclared. """ # TODO: document what exceptions can be thrown by each method, # including those that could bubble up from array import * import atexit import ctypes from types import * from PIL import Image from errors import * from saneh import * # Redeclare saneh enumerations which are visible to the application (OPTION_TYPE_BOOL, OPTION_TYPE_INT, OPTION_TYPE_FIXED, OPTION_TYPE_STRING, OPTION_TYPE_BUTTON, OPTION_TYPE_GROUP) = xrange(6) (OPTION_UNIT_NONE, OPTION_UNIT_PIXEL, OPTION_UNIT_BIT, OPTION_UNIT_MM, OPTION_UNIT_DPI, OPTION_UNIT_PERCENT, OPTION_UNIT_MICROSECOND) = xrange(7) (OPTION_CONSTRAINT_NONE, OPTION_CONSTRAINT_RANGE, OPTION_CONSTRAINT_INTEGER_LIST, OPTION_CONSTRAINT_STRING_LIST) = xrange(4) class SaneMe(object): """ The top-level object for interacting with the SANE API. Handles polling for devices. This object should only be instantiated once. """ _log = None _version = None # (major, minor, build) _devices = [] def __init__(self, log=None): """ Create the SANE object, perform setup, and register the cleanup function. @param log: an optional Python logging object to log to. """ self._log = log self._setup() atexit.register(self._shutdown) # Read only properties def __get_version(self): """Get the current installed version of SANE.""" return self._version version = property(__get_version) def _setup(self): """ Iniitalize SANE and retrieve the current installed version. """ version_code = SANE_Int() auth_callback = SANE_Auth_Callback(self._sane_auth_callback) status = sane_init(byref(version_code), auth_callback) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_init returned an invalid status: %i.' % status) self._version = (SANE_VERSION_MAJOR(version_code), SANE_VERSION_MINOR(version_code), SANE_VERSION_BUILD(version_code)) if self._log: self._log.debug('SANE version %s initalized.', self._version) def _sane_auth_callback(self, resource, username, password): """ TODO """ raise NotImplementedError( 'sane_auth_callback requested, but not yet implemented.') def _shutdown(self): """ Deinitialize SANE. This code would go in L{__del__}, but it is not guaranteed that method will be called and sane_exit must be called to release resources. To ensure this method is called it is registered with atexit. """ for device in self._devices: if device.is_open(): device.close() sane_exit() self._version = None if self._log: self._log.debug('SANE deinitialized.') # Public Methods def get_device_list(self): """ Poll for connected devices. This method may take several seconds to return. Note that SANE is exited and re-inited before querying for devices to workaround a limitation in SANE's USB driver which causes the device list to only be updated on init. This means that all settings applied to all devices will be B{lost} and must be restored by the calling application. This was found documented here: U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html} """ if not self._version: raise AssertionError('version was None') # See docstring for details on this voodoo self._shutdown() self._setup() cdevices = POINTER(POINTER(SANE_Device))() status = sane_get_devices(byref(cdevices), SANE_Bool(0)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_get_devices ran out of memory.') else: raise SaneUnknownError( 'sane_get_devices returned an invalid status: %i.' % status) device_count = 0 self._devices = [] while cdevices[device_count]: self._devices.append(Device(cdevices[device_count].contents)) device_count += 1 if self._log: self._log.debug('SANE queried, %i device(s) found.', device_count) return self._devices def get_device_by_name(self, name): """ Retrieve a L{Device} by name. Must be preceded by a call to L{get_device_list}. """ for device in self._devices: if device.name == name: return device raise SaneNoSuchDeviceError( 'The requested device does not exist.') class Device(object): """ This is the primary object for interacting with SANE. It represents a single device and handles enumeration of options, getting and setting of options, and starting and stopping of scanning jobs. """ _log = None _handle = None _name = '' _vendor = '' _model = '' _type = '' _display_name = '' _options = {} def __init__(self, ctypes_device, log=None): """ Sets the Devices properties from a ctypes SANE_Device and queries for its available options. """ self._log = log - if type(ctypes_device.name) is not str: - raise AssertionError( - 'device name was %s, expected StringType' % type(ctypes_device.name)) - if type(ctypes_device.vendor) is not str: - raise AssertionError( - 'device vendor was %s, expected StringType' % type(ctypes_device.vendor)) - if type(ctypes_device.model) is not str: - raise AssertionError( - 'device model was %s, expected StringType' % type(ctypes_device.model)) - if type(ctypes_device.type) is not str: - raise AssertionError( - 'device type was %s, expected StringType' % type(ctypes_device.type)) - - self._name = ctypes_device.name - self._vendor = ctypes_device.vendor - self._model = ctypes_device.model - self._type = ctypes_device.type + # String attributes should never be None + self._name = ctypes_device.name if ctypes_device.name else '' + self._vendor = ctypes_device.vendor if ctypes_device.vendor else '' + self._model = ctypes_device.model if ctypes_device.model else '' + self._type = ctypes_device.type if ctypes_device.type else '' self._display_name = ' '.join([self._vendor, self._model]) # Temporarily open the device to populate its options self.open() self.close() # Read only properties def __get_name(self): """ Get the complete SANE identifier for this device, e.g. 'lexmark:libusb:002:006'. """ return self._name name = property(__get_name) def __get_vendor(self): """Get the manufacturer of this device, e.g. 'Lexmark'.""" return self._vendor vendor = property(__get_vendor) def __get_model(self): """Get the specific model of this device, e.g. 'X1100/rev. B2'.""" return self._model model = property(__get_model) def __get_type(self): """Get the type of this device, e.g. 'flatbed scanner'.""" return self._type type = property(__get_type) def __get_display_name(self): """ Get an appropriate name to use for displaying this device to a user, e.g. 'Lexmark X1100/rev. B2'.""" return self._display_name display_name = property(__get_display_name) def __get_options(self): """Get the dictionary of options that this device has.""" return self._options options = property(__get_options) # Internal methods def _update_options(self): """ Update the list of available options for this device. As these are immutable, this should only need to be called when the Device is first instantiated. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') option_value = pointer(c_int()) status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: raise SaneUnsupportedOperationError( 'sane_control_option reported that a value was outside the option\'s constraint.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) option_count = option_value.contents.value if self._log: self._log.debug('Device queried, %i option(s) found.', option_count) self._options.clear() i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) self._options[coption.contents.name] = Option(self, i, coption.contents) i = i + 1 # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Public methods def open(self): """ Open a new handle to this device. Must be called before any operations (including setting options) are performed on this device. """ if self._handle: raise AssertionError('device handle already exists.') self._handle = SANE_Handle() status = sane_open(self.name, byref(self._handle)) # If and exception will be thrown, nullify device handle # so is_open() will return false for the device. if status != SANE_STATUS_GOOD.value: self._handle = None if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_open reported that the device was busy.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) self._update_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) def has_option(self, option_name): """Return true if option_name is available for this scanner.""" return (option_name in self.options.keys()) def scan(self, progress_callback=None): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) elif sane_parameters.format == SANE_FRAME_RGB.value: pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capabilities = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number - if type(ctypes_option.name) is not StringType: - raise AssertionError( - 'option name was %s, expected StringType.' % type(ctypes_option.name)) - if type(ctypes_option.title) is not StringType: - raise AssertionError( - 'option title was %s, expected StringType.' % type(ctypes_option.title)) - if type(ctypes_option.desc) is not StringType: - raise AssertionError( - 'option description was %s, expected StringType.' % type(ctypes_option.desc)) - if type(ctypes_option.type) is not IntType: - raise AssertionError( - 'option type was %s, expected IntType.' % type(ctypes_option.type)) - if type(ctypes_option.unit) is not IntType: - raise AssertionError( - 'option unit was %s, expected IntType.' % type(ctypes_option.unit)) - if type(ctypes_option.size) is not IntType: - raise AssertionError( - 'option size was %s, expected IntType.' % type(ctypes_option.size)) - if type(ctypes_option.cap) is not IntType: - raise AssertionError( - 'option cap was %s, expected IntType.' % type(ctypes_option.cap)) - if type(ctypes_option.constraint_type) is not IntType: - raise AssertionError( - 'option constraint_type was %s, expected IntType.' % type(ctypes_option.constraint_type)) - - self._name = ctypes_option.name - self._title = ctypes_option.title - self._description = ctypes_option.desc + # String attributes should never be None + self._name = ctypes_option.name if ctypes_option.name else '' + self._title = ctypes_option.title if ctypes_option.title else '' + self._description = ctypes_option.desc if ctypes_option.desc else '' + self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass - elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: - if type(ctypes_option.constraint.range) is not POINTER(SANE_Range): - raise AssertionError('option\'s constraint range was not a pointer to a SANE_Range.') - if type(ctypes_option.constraint.range.contents.min) is not IntType: - raise AssertionError('option\'s constraint range min was not of IntType.') - if type(ctypes_option.constraint.range.contents.max) is not IntType: - raise AssertionError('option\'s constraint range max was not of IntType.') - if type(ctypes_option.constraint.range.contents.quant) is not IntType: - raise AssertionError('option\'s constraint range quant was not of IntType.') - + elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) - elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: - if type(ctypes_option.constraint.word_list) is not POINTER(SANE_Word): - raise AssertionError('option\'s constraint range was not a pointer to a SANE_Word.') - + elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: - if type(ctypes_option.constraint.string_list) is not POINTER(SANE_String_Const): - raise AssertionError('option\'s constraint range was not a pointer to a SANE_String_Const.') - string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 # Read only properties def __get_name(self): - """Get the short-form name of this option, e.g. 'mode'.""" + """ + Get the short-form name of this option, e.g. 'mode'. + May be an empty string, but never None. + """ return self._name name = property(__get_name) def __get_title(self): - """Get the full name of this option, e.g. 'Scan mode'.""" + """ + Get the full name of this option, e.g. 'Scan mode'. + May be an empty string, but never None. + """ return self._title title = property(__get_title) def __get_description(self): - """, - device=self + """ Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' + May be an empty string, but never None. """ return self._description description = property(__get_description) def __get_type(self): return self._type type = property(__get_type) def __get_unit(self): return self._unit unit = property(__get_unit) def __get_capability(self): # TODO: break out into individual capabilities, rather than a bitset return self._capability capability = property(__get_capability) def __get_constraint_type(self): return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then this is a list of integers which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """ Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: - # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 + # TODO: these may not always be a single char wide, + # see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: - # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 + # TODO: these may not always be a single char wide, + # see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') - status = sane_control_option(handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) + status = sane_control_option( + handle, self._option_number, + SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i.' % status, device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value else: option_value = option_value.contents.value if self._log: self._log.debug( 'Option %s queried, its current value is %s.', self._name, option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: - raise AssertionError( + raise TypeError( 'option set with %s, expected BooleanType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: - raise AssertionError( + raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: - raise AssertionError( + raise TypeError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: - raise AssertionError( + raise TypeError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: - raise AssertionError( + raise ValueError( 'value for option is longer than max string size') c_value = c_char_p(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: if value < self._constraint[0]: - raise AssertionError('value for option is less than min.') + raise ValueError('value for option is less than min.') if value > self._constraint[1]: - raise AssertionError('value for option is greater than max.') + raise ValueError('value for option is greater than max.') if value % self._constraint[2] != 0: - raise AssertionError( - 'value for option is not divisible by quant.') + raise ValueError( + 'value for option is not divisible by step.') elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: - raise AssertionError( + raise ValueError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: - raise AssertionError( + raise ValueError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i .' % status, device=self._device) if self._log: self._log.debug('Option %s set to value %s.', self._name, value) # See SANE API 4.3.7 if info_flags.value & SANE_INFO_RELOAD_OPTIONS: raise SaneReloadOptionsError() value = property(__get_value, __set_value) class ScanInfo(object): """ Contains the parameters and progress of a scan in progress. """ _width = 0 _height = 0 _depth = 0 _total_bytes = 0 def __init__(self, sane_parameters): """ Initialize the ScanInfo object from the sane_parameters. """ self._width = sane_parameters.pixels_per_line self._height = sane_parameters.lines self._depth = sane_parameters.depth self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines # Read only properties def __get_width(self): """Get the width of the current scan, in pixels.""" return self._width width = property(__get_width) def __get_height(self): """Get the height of the current scan, in pixels.""" return self._height height = property(__get_height) def __get_depth(self): """Get the depth of the current scan, in bits.""" return self._depth depth = property(__get_depth) def __get_total_bytes(self): """Get the total number of bytes comprising this scan.""" return self._total_bytes total_bytes = property(__get_total_bytes) if __name__ == '__main__': def progress_callback(sane_info, bytes_read): #print float(bytes_read) / sane_info.total_bytes pass import logging log_format = FORMAT = "%(message)s" logging.basicConfig(level=logging.DEBUG, format=log_format) sane = SaneMe(logging.getLogger()) devices = sane.get_device_list() for dev in devices: print dev.name devices[0].open() print devices[0].options.keys() try: devices[0].options['mode'].value = 'Gray' except SaneReloadOptionsError: pass try: devices[0].options['resolution'].value = 75 except SaneReloadOptionsError: pass try: devices[0].options['preview'].value = False except SaneReloadOptionsError: pass devices[0].scan(progress_callback).save('out.bmp') devices[0].close() \ No newline at end of file
onyxfish/nostaples
4e3c1d6e95fafd50506acdb790c9e9485e2bd06a
Moved thumbnail scaling mode definition to constants.
diff --git a/constants.py b/constants.py index 3af88b6..b4bf349 100644 --- a/constants.py +++ b/constants.py @@ -1,101 +1,103 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. ''' This module contains global configuration constants that are not likely to change often as well as enumeration-like state constants. ''' import os import gtk import Image from reportlab.lib.pagesizes import A0, A1, A2, A3, A4, A5, A6, \ B0, B1, B2, B3, B4, B5, B6, LETTER, LEGAL, ELEVENSEVENTEEN PAGESIZES = {'A0' : A0, 'A1' : A1, 'A2' : A2, 'A3' : A3, 'A4' : A4, 'A5' : A5, 'A6' : A6, 'B0' : B0, 'B1' : B1, 'B2' : B2, 'B3' : B3, 'B4' : B4, 'B5' : B5, 'B6' : B6, 'LETTER' : LETTER, 'LEGAL' : LEGAL, 'ELEVENSEVENTEEN' : ELEVENSEVENTEEN} DEFAULT_SHOW_TOOLBAR = True DEFAULT_SHOW_STATUSBAR = True DEFAULT_SHOW_THUMBNAILS = True DEFAULT_SHOW_ADJUSTMENTS = False DEFAULT_ROTATE_ALL_PAGES = False DEFAULT_ACTIVE_SCANNER = '' DEFAULT_SCAN_MODE = 'Color' DEFAULT_SCAN_RESOLUTION = '75' DEFAULT_SAVE_PATH = '' DEFAULT_AUTHOR = os.getenv('LOGNAME') DEFAULT_SAVED_KEYWORDS = [] DEFAULT_PREVIEW_MODE = 'Bilinear (Default)' DEFAULT_THUMBNAIL_SIZE = 128 DEFAULT_SHOW_DOCUMENT_METADATA = True DEFAULT_BLACKLISTED_SCANNERS = [] +THUMBNAILS_SCALING_MODE = Image.ANTIALIAS + SCAN_CANCELLED = -1 SCAN_FAILURE = 0 SCAN_SUCCESS = 1 RESPONSE_BLACKLIST_DEVICE = 1 GCONF_DIRECTORY = '/apps/nostaples' GCONF_TUPLE_SEPARATOR = '|' GCONF_LIST_SEPARATOR = '^' # TODO: rename to CONFIG_DIRECTORY TEMP_IMAGES_DIRECTORY = os.path.expanduser('~/.nostaples') LOGGING_CONFIG = os.path.join(os.path.dirname(__file__), 'logging.config') GUI_DIRECTORY = os.path.join(os.path.dirname(__file__), 'gui') PREVIEW_MODES = \ { 'Nearest (Fastest)': gtk.gdk.INTERP_NEAREST, 'Tiles': gtk.gdk.INTERP_TILES, 'Bilinear (Default)': gtk.gdk.INTERP_BILINEAR, 'Antialias (Smoothest)': gtk.gdk.INTERP_HYPER } PREVIEW_MODES_LIST = \ [ 'Nearest (Fastest)', 'Tiles', 'Bilinear (Default)', 'Antialias (Smoothest)' ] THUMBNAIL_SIZE_LIST = \ [ 32, 64, 128, 256 ] \ No newline at end of file diff --git a/gui/preferences_dialog.glade b/gui/preferences_dialog.glade index f2a945b..c3c4178 100644 --- a/gui/preferences_dialog.glade +++ b/gui/preferences_dialog.glade @@ -1,283 +1,283 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> -<!--Generated with glade3 3.4.5 on Sat Feb 21 22:48:17 2009 --> +<!--Generated with glade3 3.4.5 on Sun Feb 22 20:48:25 2009 --> <glade-interface> <widget class="GtkDialog" id="preferences_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">NoStaples Preferences</property> <property name="resizable">False</property> <property name="modal">True</property> <property name="window_position">GTK_WIN_POS_CENTER_ON_PARENT</property> <property name="destroy_with_parent">True</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property> <property name="skip_taskbar_hint">True</property> <property name="skip_pager_hint">True</property> <property name="has_separator">False</property> <signal name="response" handler="on_preferences_dialog_response"/> <child internal-child="vbox"> <widget class="GtkVBox" id="dialog-vbox5"> <property name="visible">True</property> <property name="spacing">12</property> <signal name="add" handler="on_preferences_dialog_close"/> <child> <widget class="GtkNotebook" id="notebook1"> <property name="visible">True</property> <property name="can_focus">True</property> <child> <widget class="GtkAlignment" id="alignment6"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="spacing">6</property> <child> <widget class="GtkHBox" id="hbox2"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkLabel" id="label4"> <property name="visible">True</property> - <property name="label" translatable="yes">Preview Mode:</property> + <property name="label" translatable="yes">Preview Scaling Mode:</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkComboBox" id="preview_mode_combobox"> <property name="visible">True</property> <property name="items" translatable="yes"></property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkHBox" id="hbox1"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkLabel" id="label5"> <property name="visible">True</property> <property name="label" translatable="yes">Thumbnail Size:</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkComboBox" id="thumbnail_size_combobox"> <property name="visible">True</property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> </child> </widget> </child> <child> <widget class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">View</property> </widget> <packing> <property name="type">tab</property> <property name="tab_fill">False</property> </packing> </child> <child> <widget class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="label7"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Blacklisted devices:</property> <property name="wrap_mode">PANGO_WRAP_WORD_CHAR</property> </widget> </child> <child> <widget class="GtkScrolledWindow" id="blacklist_scrolled_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="shadow_type">GTK_SHADOW_IN</property> <child> <placeholder/> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkButton" id="remove_from_blacklist_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="label" translatable="yes">Remove</property> <property name="response_id">0</property> <signal name="clicked" handler="on_remove_from_blacklist_button_clicked"/> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> </widget> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkLabel" id="label3"> <property name="visible">True</property> <property name="label" translatable="yes">Devices</property> </widget> <packing> <property name="type">tab</property> <property name="position">1</property> <property name="tab_fill">False</property> </packing> </child> <child> <widget class="GtkAlignment" id="alignment2"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="label6"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Keywords for autocompletion:</property> <property name="use_markup">True</property> <property name="wrap">True</property> </widget> </child> <child> <widget class="GtkScrolledWindow" id="keywords_scrolled_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="shadow_type">GTK_SHADOW_IN</property> <child> <placeholder/> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkAlignment" id="alignment3"> <property name="visible">True</property> <child> <widget class="GtkButton" id="remove_from_keywords_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="label" translatable="yes">Remove</property> <property name="response_id">0</property> <signal name="clicked" handler="on_remove_from_keywords_button_clicked"/> </widget> </child> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> </widget> </child> </widget> <packing> <property name="position">2</property> </packing> </child> <child> <widget class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">Documents</property> </widget> <packing> <property name="type">tab</property> <property name="position">2</property> <property name="tab_fill">False</property> </packing> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <widget class="GtkHButtonBox" id="dialog-action_area5"> <property name="visible">True</property> <property name="layout_style">GTK_BUTTONBOX_END</property> <child> <placeholder/> </child> <child> <widget class="GtkButton" id="preferences_close_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">gtk-close</property> <property name="use_stock">True</property> <property name="response_id">0</property> <signal name="clicked" handler="on_preferences_close_button_clicked"/> </widget> <packing> <property name="expand">False</property> <property name="pack_type">GTK_PACK_END</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="expand">False</property> <property name="pack_type">GTK_PACK_END</property> </packing> </child> </widget> </child> </widget> </glade-interface> diff --git a/models/page.py b/models/page.py index 21c5767..30cd3b2 100644 --- a/models/page.py +++ b/models/page.py @@ -1,226 +1,226 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the PageModel, which represents a single scanned page. """ import logging import gtk from gtkmvc.model import Model import Image, ImageEnhance from nostaples import constants from nostaples.utils.graphics import * class PageModel(Model): """ Represents a single scanned page. """ __properties__ = \ { '_raw_pil_image' : None, 'rotation' : 0, 'brightness' : 1.0, 'contrast' : 1.0, 'sharpness' : 1.0, 'resolution' : 75, 'pil_image' : None, 'pixbuf' : None, 'thumbnail_pixbuf': None, } # SETUP METHODS def __init__(self, application, pil_image=None, resolution=75): """ Constructs the PageModel. @type pil_image: a PIL image @param pil_image: The image data for this page. @type resolution: int @param resolution: The dpi that the page was scanned at. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.resolution = resolution if pil_image: self._raw_pil_image = pil_image self._update_pixbuf() self._update_thumbnail_pixbuf() self.register_observer(self) # TODO: Wtf am I doing here, solves a bug, but why? self.accepts_spurious_change = lambda : True self.log.debug('Created.') # COMPUTED PROPERTIES @property def width(self): """ Gets the width of the page after transformations have been applied. """ return self.pixbuf.get_width() @property def height(self): """ Gets the height of the page after transformations have been applied. """ return self.pixbuf.get_height() # PROPERTY CALLBACKS def property_rotation_value_change(self, model, old_value, new_value): """Updates the full and thumbnail pixbufs.""" self._update_pixbuf() self._update_thumbnail_pixbuf() def property_brightness_value_change(self, model, old_value, new_value): """Updates the full and thumbnail pixbufs.""" self._update_pixbuf() self._update_thumbnail_pixbuf() def property_contrast_value_change(self, model, old_value, new_value): """Updates the full and thumbnail pixbufs.""" self._update_pixbuf() self._update_thumbnail_pixbuf() def property_sharpness_value_change(self, model, old_value, new_value): """Updates the full and thumbnail pixbufs.""" self._update_pixbuf() self._update_thumbnail_pixbuf() # PUBLIC METHODS def rotate_counter_clockwise(self): """ Rotate this page ninety degrees counter-clockwise. """ self.rotation += 90 def rotate_clockwise(self): """ Rotate this page ninety degrees clockwise. """ self.rotation -= 90 def set_adjustments(self, brightness, contrast, sharpness): """ Sets all three adjustment values in one method without triggering each property callback. This prevents the pixbuf and thumbnail from being update multiple times. """ if (self.__properties__['brightness'] == brightness and self.__properties__['contrast'] == contrast and self.__properties__['sharpness'] == sharpness): return self.__properties__['brightness'] = brightness self.__properties__['contrast'] = contrast self.__properties__['sharpness'] = sharpness self._update_pixbuf() self._update_thumbnail_pixbuf() # PRIVATE METHODS def _update_pixbuf(self): """ Creates a full-size pixbuf of the scanned image with all transformations applied. """ image = self._raw_pil_image if self.brightness != 1.0: image = ImageEnhance.Brightness(image).enhance( self.brightness) if self.contrast != 1.0: image = ImageEnhance.Contrast(image).enhance( self.contrast) if self.sharpness != 1.0: image = ImageEnhance.Sharpness(image).enhance( self.sharpness) if abs(self.rotation % 360) == 90: image = image.transpose(Image.ROTATE_90) elif abs(self.rotation % 360) == 180: image = image.transpose(Image.ROTATE_180) elif abs(self.rotation % 360) == 270: image = image.transpose(Image.ROTATE_270) self.pil_image = image self.pixbuf = convert_pil_image_to_pixbuf(image) def _update_thumbnail_pixbuf(self): """ Creates a thumbnail image with all transformations applied. """ preferences_model = self.application.get_preferences_model() image = self._raw_pil_image if self.brightness != 1.0: image = ImageEnhance.Brightness(image).enhance( self.brightness) if self.contrast != 1.0: image = ImageEnhance.Contrast(image).enhance( self.contrast) if self.sharpness != 1.0: image = ImageEnhance.Sharpness(image).enhance( self.sharpness) if abs(self.rotation % 360) == 90: image = image.transpose(Image.ROTATE_90) elif abs(self.rotation % 360) == 180: image = image.transpose(Image.ROTATE_180) elif abs(self.rotation % 360) == 270: image = image.transpose(Image.ROTATE_270) width, height = image.size thumbnail_size = preferences_model.thumbnail_size width_ratio = float(width) / thumbnail_size height_ratio = float(height) / thumbnail_size if width_ratio < height_ratio: zoom = 1 / float(height_ratio) else: zoom = 1 / float(width_ratio) target_width = int(width * zoom) target_height = int(height * zoom) image = image.resize( (target_width, target_height), - Image.ANTIALIAS) + constants.THUMBNAILS_SCALING_MODE) self.thumbnail_pixbuf = convert_pil_image_to_pixbuf(image) \ No newline at end of file
onyxfish/nostaples
6edf951193395e422e9e8ed26ea7793f58431ef1
Iterative work on intelligent device blacklisting.
diff --git a/controllers/main.py b/controllers/main.py index 0c33a01..5506069 100644 --- a/controllers/main.py +++ b/controllers/main.py @@ -38,706 +38,715 @@ class MainController(Controller): """ Manages interaction between the L{MainModel} and L{MainView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the MainController, as well as necessary sub-controllers and services. """ self.application = application Controller.__init__(self, application.get_main_model()) application.get_document_model().register_observer(self) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ self.adapt('show_toolbar', 'show_toolbar_menu_item') self.adapt('show_statusbar', 'show_statusbar_menu_item') self.adapt('show_thumbnails', 'show_thumbnails_menu_item') self.adapt('show_adjustments', 'show_adjustments_menu_item') self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS # Menu Items def on_scan_window_destroy(self, window): """Exits the application.""" self.quit() def on_scan_menu_item_activate(self, menu_item): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_menu_item_activate(self, menu_item): """Refresh the list of connected scanners from SANE.""" self._update_available_scanners() def on_save_as_menu_item_activate(self, menu_item): """Saves the current document to a file.""" self.application.show_save_dialog() def on_delete_menu_item_activate(self, menu_item): self.application.get_document_controller().delete_selected() def on_preferences_menu_item_activate(self, menu_item): """Creates and displays a preferences dialog.""" self.application.show_preferences_dialog() def on_quit_menu_item_activate(self, menu_item): """Exits the application.""" self.quit() def on_zoom_in_menu_item_activate(self, menu_item): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_menu_item_activate(self, menu_item): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_menu_item_activate(self, menu_item): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_menu_item_activate(self, menu_item): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_available_scanner_menu_item_toggled(self, menu_item): """ Set the active scanner. TODO: Need a second scanner to properly test this... """ main_model = self.application.get_main_model() if menu_item.get_active(): for scanner in main_model.available_scanners: if scanner.display_name == menu_item.get_children()[0].get_text(): main_model.active_scanner = scanner return def on_valid_mode_menu_item_toggled(self, menu_item): """Sets the active scan mode.""" if menu_item.get_active(): self.application.get_main_model().active_mode = \ menu_item.get_children()[0].get_text() def on_valid_resolution_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_resolution = \ menu_item.get_children()[0].get_text() def on_go_first_menu_item_activate(self, menu_item): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_menu_item_activate(self, menu_item): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_menu_item_activate(self, menu_item): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_menu_item_activate(self, menu_item): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() def on_contents_menu_item_clicked(self, menu_item): """TODO""" pass def on_about_menu_item_activate(self, menu_item): """Show the about dialog.""" self.application.show_about_dialog() # Toolbar Buttons def on_scan_button_clicked(self, button): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_button_clicked(self, button): self._update_available_scanners() def on_save_as_button_clicked(self, button): """Saves the current document to a file.""" self.application.show_save_dialog() def on_zoom_in_button_clicked(self, button): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_button_clicked(self, button): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_button_clicked(self, button): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_button_clicked(self, button): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_go_first_button_clicked(self, button): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_button_clicked(self, button): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_button_clicked(self, button): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_button_clicked(self, button): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() # Progress Window INTERFACE CALLBACKS def on_progress_window_delete_event(self, window, event): """ Emulate clicking of the cancel/close button and then hide the window. """ main_view = self.application.get_main_view() self.on_scan_cancel_button_clicked(None) main_view['progress_window'].hide() return True def on_scan_cancel_button_clicked(self, button): """ Cancel the current scan or, if the scan is finished, close the progress window. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress: assert self.cancel_event self.cancel_event.set() else: main_view['progress_window'].hide() def on_scan_again_button_clicked(self, button): """Initiate a new scan from the progress window.""" self._scan() def on_quick_save_button_clicked(self, button): """ Show the save dialog. If the user completes a save then disable the quick save button until another page is scanned. """ main_view = self.application.get_main_view() document_model = self.application.get_document_model() self.application.show_save_dialog() if document_model.count == 0: main_view['quick_save_button'].set_sensitive(False) # MainModel PROPERTY CALLBACKS def property_show_toolbar_value_change(self, model, old_value, new_value): """Update the visibility of the toolbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_toolbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['main_toolbar'].show() else: main_view['main_toolbar'].hide() def property_show_statusbar_value_change(self, model, old_value, new_value): """Update the visibility of the statusbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_statusbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['status_view_docking_viewport'].show() else: main_view['status_view_docking_viewport'].hide() def property_show_thumbnails_value_change(self, model, old_value, new_value): """Update the visibility of the thumbnails.""" main_view = self.application.get_main_view() menu_item = main_view['show_thumbnails_menu_item'] menu_item.set_active(new_value) self.application.get_document_controller().toggle_thumbnails_visible(new_value) def property_show_adjustments_value_change(self, model, old_value, new_value): """Update the visibility of the adjustments controls.""" document_controller = self.application.get_document_controller() main_view = self.application.get_main_view() menu_item = main_view['show_adjustments_menu_item'] menu_item.set_active(new_value) document_controller.toggle_adjustments_visible(new_value) def property_active_scanner_value_change(self, model, old_value, new_value): """ Update the menu and valid scanner options to match the new device. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() for menu_item in main_view['scanner_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value.display_name: menu_item.set_active(True) break def property_active_mode_value_change(self, model, old_value, new_value): """Select the active mode from in the menu.""" main_view = self.application.get_main_view() for menu_item in main_view['scan_mode_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_resolution_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() for menu_item in main_view['scan_resolution_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_available_scanners_value_change(self, model, old_value, new_value): """ Update the menu of available scanners. """ main_view = self.application.get_main_view() self._clear_available_scanners_sub_menu() # Generate the new menu if len(new_value) == 0: menu_item = gtk.MenuItem('No Scanners Connected') menu_item.set_sensitive(False) main_view['scanner_sub_menu'].append(menu_item) else: first_item = None for i in range(len(new_value)): # The first menu item defines the group if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i].display_name) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i].display_name) main_view['scanner_sub_menu'].append(menu_item) main_view['scanner_sub_menu'].show_all() def property_valid_modes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan modes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_modes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Modes") menu_item.set_sensitive(False) main_view['scan_mode_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled) main_view['scan_mode_sub_menu'].append(menu_item) main_view['scan_mode_sub_menu'].show_all() def property_valid_resolutions_value_change(self, model, old_value, new_value): """ Updates the list of valid scan resolutions for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_resolutions_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Resolutions") menu_item.set_sensitive(False) main_view['scan_resolution_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled) main_view['scan_resolution_sub_menu'].append(menu_item) main_view['scan_resolution_sub_menu'].show_all() def property_scan_in_progress_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() def property_updating_available_scanners_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() # DocumentModel PROPERTY CALLBACKS def property_count_value_change(self, model, old_value, new_value): """Toggle available controls.""" self._toggle_document_controls() # THREAD CALLBACKS def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned): main_view = self.application.get_main_view() short_bytes_scanned = float(bytes_scanned) / 1000 short_total_bytes = float(scan_info.total_bytes) / 1000 main_view['scan_progressbar'].set_fraction( float(bytes_scanned) / scan_info.total_bytes) main_view['scan_progressbar'].set_text( 'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes)) # TODO: multi page scans main_view['progress_secondary_label'].set_markup( '<i>Scanning page.</i>') def on_scan_succeeded(self, scanning_thread, pil_image): """ Append the new page to the current document. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['scan_progressbar'].set_fraction(1) main_view['scan_progressbar'].set_text('Scan complete') main_view['progress_secondary_label'].set_markup( '<i>Adding page to document.</i>') gtk.gdk.flush() new_page = PageModel(self.application, pil_image, int(main_model.active_resolution)) self.application.get_document_model().append(new_page) main_view['progress_secondary_label'].set_markup( '<i>Page added.</i>') main_view['scan_again_button'].set_sensitive(True) main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_failed(self, scanning_thread, reason): """ Set that scan is complete. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['progress_secondary_label'].set_markup( '<i>%s</i>' % reason) main_view['scan_again_button'].set_sensitive(True) if self.application.get_document_model().count > 0: main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_aborted(self, scanning_thread, exc_info): """ Change display to indicate that scanning failed and convey the to the user the reason why the thread aborted. If the failure was from a SANE exception then give the user the option to blacklist the device. If not, then reraise the error and let the sys.excepthook deal with it. """ self.on_scan_failed(scanning_thread, 'An error occurred.') if isinstance(exc_info[1], saneme.SaneError): self.run_device_exception_dialog(exc_info) else: raise exc_info[0], exc_info[1], exc_info[2] def on_update_available_scanners_thread_finished(self, update_thread, scanner_list): """Set the new list of available scanners.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() status_controller = self.application.get_status_controller() - # Remove scanners that do not support necessary options - preferences_model.unsupported_scanners = [] - - for scanner in scanner_list: - if not scanner.has_option('mode') or \ - not scanner.has_option('resolution'): - preferences_model.unsupported_scanners.append(scanner.display_name) - scanner_list.remove(scanner) - # Remove blacklisted scanners scanner_list = \ [scanner for scanner in scanner_list if not \ scanner.display_name in preferences_model.blacklisted_scanners] + # Remove scanners that do not support necessary options or fail to + # open entirely + preferences_model.unavailable_scanners = [] + + for scanner in scanner_list: + try: + scanner.open() + + if not scanner.has_option('mode') or \ + not scanner.has_option('resolution'): + preferences_model.unavailable_scanners.append(scanner.display_name) + scanner_list.remove(scanner) + + scanner.close() + except saneme.SaneError: + preferences_model.unavailable_scanners.append(scanner.display_name) + scanner_list.remove(scanner) + main_model.available_scanners = scanner_list main_model.updating_available_scanners = False def on_update_available_scanners_thread_aborted(self, update_thread, exc_info): """ Change the display to indicate that no scanners are available and reraise the exception so that it can be caught by the sys.excepthook. There is no reason to handle these cases with a special dialog, if the application failed to even enumerate the available devices then no other action will be possible. This should be fantastically rare. """ self.on_update_available_scanners_thread_finished(update_thread, []) raise exc_info[0], exc_info[1], exc_info[2] # PUBLIC METHODS def quit(self): """Exits the application.""" self.log.debug('Quit.') gtk.main_quit() def run_device_exception_dialog(self, exc_info): """ Display an error dialog that provides the user with the option of blacklisting the device which caused the error. TODO: Move into MainView. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() preferences_model = self.application.get_preferences_model() response = main_view.run_device_exception_dialog(exc_info) if response == constants.RESPONSE_BLACKLIST_DEVICE: temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(exc_info[1].device.display_name) temp_blacklist.sort() preferences_model.blacklisted_scanners = temp_blacklist # PRIVATE METHODS def _clear_available_scanners_sub_menu(self): """Clear the menu of available scanners.""" main_view = self.application.get_main_view() for child in main_view['scanner_sub_menu'].get_children(): main_view['scanner_sub_menu'].remove(child) def _clear_scan_modes_sub_menu(self): """Clear the menu of valid scan modes.""" main_view = self.application.get_main_view() for child in main_view['scan_mode_sub_menu'].get_children(): main_view['scan_mode_sub_menu'].remove(child) def _clear_scan_resolutions_sub_menu(self): """Clear the menu of valid scan resolutions.""" main_view = self.application.get_main_view() for child in main_view['scan_resolution_sub_menu'].get_children(): main_view['scan_resolution_sub_menu'].remove(child) def _toggle_scan_controls(self): """Toggle whether or not the scan controls or accessible.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_scan_controls_sensitive(False) main_view.set_refresh_scanner_controls_sensitive(False) else: if main_model.active_scanner != None: main_view.set_scan_controls_sensitive(True) main_view.set_refresh_scanner_controls_sensitive(True) def _toggle_document_controls(self): """ Toggle available document controls based on the current scanner status and the number of scanned pages. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() # Disable all controls when the scanner is in use if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: count = self.application.get_document_model().count # Disable all controls if no pages are scanned if count == 0: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: # Enable most controls if any pages scanned main_view.set_file_controls_sensitive(True) main_view.set_delete_controls_sensitive(True) main_view.set_zoom_controls_sensitive(True) main_view.set_adjustment_controls_sensitive(True) # Only enable navigation if more than one page scanned if count > 1: main_view.set_navigation_controls_sensitive(True) else: main_view.set_navigation_controls_sensitive(False) def _update_status(self): """ Update the text of the statusbar based on the current state of the application. """ main_model = self.application.get_main_model() status_controller = self.application.get_status_controller() status_controller.pop(self.status_context) if main_model.scan_in_progress: status_controller.push(self.status_context, 'Scanning...') elif main_model.updating_available_scanners: status_controller.push(self.status_context, 'Querying hardware...') else: if main_model.active_scanner: status_controller.push(self.status_context, 'Ready with %s.' % main_model.active_scanner.display_name) else: status_controller.push(self.status_context, 'No scanner available.') def _scan(self): """Begin a scan.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() main_model.scan_in_progress = True scanning_thread = ScanningThread(main_model.active_scanner) scanning_thread.connect("progress", self.on_scan_progress) scanning_thread.connect("succeeded", self.on_scan_succeeded) scanning_thread.connect("failed", self.on_scan_failed) scanning_thread.connect("aborted", self.on_scan_aborted) self.cancel_event = scanning_thread.cancel_event main_view['progress_primary_label'].set_markup( '<big><b>%s</b></big>' % main_model.active_scanner.display_name) main_view['scan_progressbar'].set_fraction(0) main_view['scan_progressbar'].set_text('Waiting for data') main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>') mode = main_model.active_mode if main_model.active_mode else 'Not set' main_view['progress_mode_label'].set_markup(mode) dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set' main_view['progress_resolution_label'].set_markup(dpi) main_view['scan_again_button'].set_sensitive(False) main_view['quick_save_button'].set_sensitive(False) main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL) main_view['progress_window'].show_all() scanning_thread.start() def _update_available_scanners(self): """ Start a new update thread to query for available scanners. """ sane = self.application.get_sane() main_model = self.application.get_main_model() main_model.updating_available_scanners = True update_thread = UpdateAvailableScannersThread(sane) update_thread.connect("finished", self.on_update_available_scanners_thread_finished) update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted) update_thread.start() \ No newline at end of file diff --git a/controllers/preferences.py b/controllers/preferences.py index f1bfe08..4fd7c15 100644 --- a/controllers/preferences.py +++ b/controllers/preferences.py @@ -1,147 +1,154 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{PreferencesController}, which manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ import logging import gtk from gtkmvc.controller import Controller from nostaples import constants from nostaples.utils.gui import read_combobox class PreferencesController(Controller): """ Manages interaction between the L{PreferencesModel} and L{PreferencesView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the PreferencesController. """ self.application = application Controller.__init__(self, application.get_preferences_model()) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ pass # USER INTERFACE CALLBACKS def on_preview_mode_combobox_changed(self, combobox): preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.preview_mode = \ read_combobox(preferences_view['preview_mode_combobox']) def on_thumbnail_size_combobox_changed(self, combobox): preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() preferences_model.thumbnail_size = \ int(read_combobox(preferences_view['thumbnail_size_combobox'])) def on_remove_from_blacklist_button_clicked(self, button): """ Remove the currently selected blacklist device from the list. """ preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['blacklist_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.remove(selection_text) preferences_model.blacklisted_scanners = temp_blacklist def on_remove_from_keywords_button_clicked(self, button): """ Remove the currently selected keyword from the list. """ preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() model, selection_iter = \ preferences_view['keywords_tree_view'].get_selection().get_selected() if not selection_iter: return selection_text = model.get_value(selection_iter, 0) model.remove(selection_iter) temp_keywords = list(preferences_model.saved_keywords) temp_keywords.remove(selection_text) preferences_model.saved_keywords = temp_keywords def on_preferences_dialog_response(self, dialog, response): """Close the preferences dialog.""" preferences_view = self.application.get_preferences_view() preferences_view['preferences_dialog'].hide() # PUBLIC METHODS def run(self): """Run the preferences dialog.""" preferences_model = self.application.get_preferences_model() preferences_view = self.application.get_preferences_view() + # Refresh unavailable scanners + unavailable_liststore = preferences_view['unavailable_tree_view'].get_model() + unavailable_liststore.clear() + + for unavailable_item in preferences_model.unavailable_scanners: + unavailable_liststore.append([unavailable_item]) + # Refresh blacklist blacklist_liststore = preferences_view['blacklist_tree_view'].get_model() blacklist_liststore.clear() for blacklist_item in preferences_model.blacklisted_scanners: blacklist_liststore.append([blacklist_item]) # Refresh keywords keywords_liststore = preferences_view['keywords_tree_view'].get_model() keywords_liststore.clear() for keyword in preferences_model.saved_keywords: keywords_liststore.append([keyword]) preferences_view.run() \ No newline at end of file diff --git a/gui/preferences_dialog.glade b/gui/preferences_dialog.glade index f2a945b..c5bf455 100644 --- a/gui/preferences_dialog.glade +++ b/gui/preferences_dialog.glade @@ -1,283 +1,313 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> -<!--Generated with glade3 3.4.5 on Sat Feb 21 22:48:17 2009 --> +<!--Generated with glade3 3.4.5 on Sun Feb 22 22:12:35 2009 --> <glade-interface> <widget class="GtkDialog" id="preferences_dialog"> <property name="border_width">5</property> <property name="title" translatable="yes">NoStaples Preferences</property> <property name="resizable">False</property> <property name="modal">True</property> <property name="window_position">GTK_WIN_POS_CENTER_ON_PARENT</property> <property name="destroy_with_parent">True</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property> <property name="skip_taskbar_hint">True</property> <property name="skip_pager_hint">True</property> <property name="has_separator">False</property> <signal name="response" handler="on_preferences_dialog_response"/> <child internal-child="vbox"> <widget class="GtkVBox" id="dialog-vbox5"> <property name="visible">True</property> <property name="spacing">12</property> <signal name="add" handler="on_preferences_dialog_close"/> <child> <widget class="GtkNotebook" id="notebook1"> <property name="visible">True</property> <property name="can_focus">True</property> <child> <widget class="GtkAlignment" id="alignment6"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox3"> <property name="visible">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="spacing">6</property> <child> <widget class="GtkHBox" id="hbox2"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkLabel" id="label4"> <property name="visible">True</property> <property name="label" translatable="yes">Preview Mode:</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkComboBox" id="preview_mode_combobox"> <property name="visible">True</property> <property name="items" translatable="yes"></property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkHBox" id="hbox1"> <property name="visible">True</property> <property name="spacing">12</property> <child> <widget class="GtkLabel" id="label5"> <property name="visible">True</property> <property name="label" translatable="yes">Thumbnail Size:</property> </widget> <packing> <property name="expand">False</property> </packing> </child> <child> <widget class="GtkComboBox" id="thumbnail_size_combobox"> <property name="visible">True</property> </widget> <packing> <property name="position">1</property> </packing> </child> </widget> <packing> + <property name="expand">False</property> <property name="position">1</property> </packing> </child> </widget> </child> </widget> </child> <child> <widget class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">View</property> </widget> <packing> <property name="type">tab</property> <property name="tab_fill">False</property> </packing> </child> <child> <widget class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="spacing">6</property> + <child> + <widget class="GtkLabel" id="label8"> + <property name="visible">True</property> + <property name="xalign">0</property> + <property name="label" translatable="yes">Unavailable devices:</property> + <property name="wrap_mode">PANGO_WRAP_WORD_CHAR</property> + </widget> + </child> + <child> + <widget class="GtkScrolledWindow" id="unavailable_scrolled_window"> + <property name="visible">True</property> + <property name="can_focus">True</property> + <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> + <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> + <property name="shadow_type">GTK_SHADOW_IN</property> + <child> + <placeholder/> + </child> + </widget> + <packing> + <property name="position">1</property> + </packing> + </child> <child> <widget class="GtkLabel" id="label7"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Blacklisted devices:</property> <property name="wrap_mode">PANGO_WRAP_WORD_CHAR</property> </widget> + <packing> + <property name="position">2</property> + </packing> </child> <child> <widget class="GtkScrolledWindow" id="blacklist_scrolled_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="shadow_type">GTK_SHADOW_IN</property> <child> <placeholder/> </child> </widget> <packing> - <property name="position">1</property> + <property name="position">3</property> </packing> </child> <child> <widget class="GtkButton" id="remove_from_blacklist_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="label" translatable="yes">Remove</property> <property name="response_id">0</property> <signal name="clicked" handler="on_remove_from_blacklist_button_clicked"/> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> - <property name="position">2</property> + <property name="position">4</property> </packing> </child> </widget> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkLabel" id="label3"> <property name="visible">True</property> <property name="label" translatable="yes">Devices</property> </widget> <packing> <property name="type">tab</property> <property name="position">1</property> <property name="tab_fill">False</property> </packing> </child> <child> <widget class="GtkAlignment" id="alignment2"> <property name="visible">True</property> <property name="top_padding">12</property> <property name="bottom_padding">12</property> <property name="left_padding">12</property> <property name="right_padding">12</property> <child> <widget class="GtkVBox" id="vbox2"> <property name="visible">True</property> <property name="spacing">6</property> <child> <widget class="GtkLabel" id="label6"> <property name="visible">True</property> <property name="xalign">0</property> <property name="label" translatable="yes">Keywords for autocompletion:</property> <property name="use_markup">True</property> <property name="wrap">True</property> </widget> + <packing> + <property name="expand">False</property> + </packing> </child> <child> <widget class="GtkScrolledWindow" id="keywords_scrolled_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="shadow_type">GTK_SHADOW_IN</property> <child> <placeholder/> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child> <widget class="GtkAlignment" id="alignment3"> <property name="visible">True</property> <child> <widget class="GtkButton" id="remove_from_keywords_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="label" translatable="yes">Remove</property> <property name="response_id">0</property> <signal name="clicked" handler="on_remove_from_keywords_button_clicked"/> </widget> </child> </widget> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> </widget> </child> </widget> <packing> <property name="position">2</property> </packing> </child> <child> <widget class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">Documents</property> </widget> <packing> <property name="type">tab</property> <property name="position">2</property> <property name="tab_fill">False</property> </packing> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <widget class="GtkHButtonBox" id="dialog-action_area5"> <property name="visible">True</property> <property name="layout_style">GTK_BUTTONBOX_END</property> <child> <placeholder/> </child> <child> <widget class="GtkButton" id="preferences_close_button"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property> <property name="label" translatable="yes">gtk-close</property> <property name="use_stock">True</property> <property name="response_id">0</property> <signal name="clicked" handler="on_preferences_close_button_clicked"/> </widget> <packing> <property name="expand">False</property> <property name="pack_type">GTK_PACK_END</property> <property name="position">1</property> </packing> </child> </widget> <packing> <property name="expand">False</property> <property name="pack_type">GTK_PACK_END</property> </packing> </child> </widget> </child> </widget> </glade-interface> diff --git a/models/preferences.py b/models/preferences.py index 4d4e7a4..9270cb4 100644 --- a/models/preferences.py +++ b/models/preferences.py @@ -1,86 +1,86 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the PreferencesModel, which manages user settings. """ import logging from gtkmvc.model import Model from nostaples import constants import nostaples.utils.properties class PreferencesModel(Model): """ Manages user settings. """ __properties__ = \ { 'preview_mode' : constants.DEFAULT_PREVIEW_MODE, 'thumbnail_size' : constants.DEFAULT_THUMBNAIL_SIZE, - 'unsupported_scanners' : [], # Not persisted + 'unavailable_scanners' : [], # Not persisted 'blacklisted_scanners' : [], # List of scanner display names 'saved_keywords' : '', } def __init__(self, application): """ Constructs the PreferencesModel. """ Model.__init__(self) self.application = application self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() self.preview_mode = state_manager.init_state( 'preview_mode', constants.DEFAULT_PREVIEW_MODE, nostaples.utils.properties.PropertyStateCallback(self, 'preview_mode')) self.thumbnail_size = state_manager.init_state( 'thumbnail_size', constants.DEFAULT_THUMBNAIL_SIZE, nostaples.utils.properties.PropertyStateCallback(self, 'thumbnail_size')) self.blacklisted_scanners = state_manager.init_state( 'blacklisted_scanners', constants.DEFAULT_BLACKLISTED_SCANNERS, nostaples.utils.properties.PropertyStateCallback(self, 'blacklisted_scanners')) self.saved_keywords = state_manager.init_state( 'saved_keywords', constants.DEFAULT_SAVED_KEYWORDS, nostaples.utils.properties.PropertyStateCallback(self, 'saved_keywords')) # PROPERTY SETTERS set_prop_preview_mode = nostaples.utils.properties.StatefulPropertySetter( 'preview_mode') set_prop_thumbnail_size = nostaples.utils.properties.StatefulPropertySetter( 'thumbnail_size') set_prop_blacklisted_scanners = nostaples.utils.properties.StatefulPropertySetter( 'blacklisted_scanners') set_prop_saved_keywords = nostaples.utils.properties.StatefulPropertySetter( 'saved_keywords') \ No newline at end of file diff --git a/views/preferences.py b/views/preferences.py index 21a6f60..fead3ca 100644 --- a/views/preferences.py +++ b/views/preferences.py @@ -1,120 +1,138 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the PreferencesView which exposes user settings through a dialog seperate from the main application window. """ import logging import os import gtk from gtkmvc.view import View from nostaples import constants from nostaples.utils.gui import read_combobox, setup_combobox class PreferencesView(View): """ Exposes user settings through a dialog seperate from the main application window. """ def __init__(self, application): """ Constructs the PreferencesView, including setting up controls that could not be configured in Glade. """ self.application = application preferences_controller = application.get_preferences_controller() preferences_dialog_glade = os.path.join( constants.GUI_DIRECTORY, 'preferences_dialog.glade') View.__init__( self, preferences_controller, preferences_dialog_glade, 'preferences_dialog', None, False) self.log = logging.getLogger(self.__class__.__name__) # Can not configure this via constructor do to the multiple # root windows in the Main View. self['preferences_dialog'].set_transient_for( application.get_main_view()['scan_window']) # These two combobox's are setup dynamically. Because of this they # must have their signal handlers connected manually. Otherwise # their signals will fire before the view creation is finished. setup_combobox( self['preview_mode_combobox'], constants.PREVIEW_MODES_LIST, application.get_preferences_model().preview_mode) self['preview_mode_combobox'].connect( 'changed', preferences_controller.on_preview_mode_combobox_changed) setup_combobox( self['thumbnail_size_combobox'], constants.THUMBNAIL_SIZE_LIST, application.get_preferences_model().thumbnail_size) self['thumbnail_size_combobox'].connect( 'changed', preferences_controller.on_thumbnail_size_combobox_changed) + # Setup the unavailable scanners tree view + unavailable_liststore = gtk.ListStore(str) + self['unavailable_tree_view'] = gtk.TreeView() + self['unavailable_tree_view'].set_model(unavailable_liststore) + self['unavailable_column'] = gtk.TreeViewColumn(None) + self['unavailable_cell'] = gtk.CellRendererText() + self['unavailable_tree_view'].append_column(self['unavailable_column']) + self['unavailable_column'].pack_start(self['unavailable_cell'], True) + self['unavailable_column'].add_attribute( + self['unavailable_cell'], 'text', 0) + self['unavailable_tree_view'].get_selection().set_mode( + gtk.SELECTION_NONE) + self['unavailable_tree_view'].set_headers_visible(False) + self['unavailable_tree_view'].set_property('can-focus', False) + + self['unavailable_scrolled_window'].add(self['unavailable_tree_view']) + self['unavailable_scrolled_window'].show_all() + # Setup the blacklist tree view blacklist_liststore = gtk.ListStore(str) self['blacklist_tree_view'] = gtk.TreeView() self['blacklist_tree_view'].set_model(blacklist_liststore) self['blacklist_column'] = gtk.TreeViewColumn(None) self['blacklist_cell'] = gtk.CellRendererText() self['blacklist_tree_view'].append_column(self['blacklist_column']) self['blacklist_column'].pack_start(self['blacklist_cell'], True) self['blacklist_column'].add_attribute(self['blacklist_cell'], 'text', 0) self['blacklist_tree_view'].get_selection().set_mode( gtk.SELECTION_SINGLE) self['blacklist_tree_view'].set_headers_visible(False) self['blacklist_tree_view'].set_property('can-focus', False) self['blacklist_scrolled_window'].add(self['blacklist_tree_view']) self['blacklist_scrolled_window'].show_all() # Setup the keywords tree view keywords_liststore = gtk.ListStore(str) self['keywords_tree_view'] = gtk.TreeView() self['keywords_tree_view'].set_model(keywords_liststore) self['keywords_column'] = gtk.TreeViewColumn(None) self['keywords_cell'] = gtk.CellRendererText() self['keywords_tree_view'].append_column(self['keywords_column']) self['keywords_column'].pack_start(self['keywords_cell'], True) self['keywords_column'].add_attribute(self['keywords_cell'], 'text', 0) self['keywords_tree_view'].get_selection().set_mode( gtk.SELECTION_SINGLE) self['keywords_tree_view'].set_headers_visible(False) self['keywords_tree_view'].set_property('can-focus', False) self['keywords_scrolled_window'].add(self['keywords_tree_view']) self['keywords_scrolled_window'].show_all() application.get_preferences_controller().register_view(self) self.log.debug('Created.') def run(self): """Run the modal preferences dialog.""" self['preferences_dialog'].run() \ No newline at end of file
onyxfish/nostaples
3466cc29cc8d284914c0492b796c411729446f46
Added comments elaborating on voodoo in previous commit.
diff --git a/controllers/main.py b/controllers/main.py index 9cc02e6..0c33a01 100644 --- a/controllers/main.py +++ b/controllers/main.py @@ -39,705 +39,705 @@ class MainController(Controller): Manages interaction between the L{MainModel} and L{MainView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the MainController, as well as necessary sub-controllers and services. """ self.application = application Controller.__init__(self, application.get_main_model()) application.get_document_model().register_observer(self) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ self.adapt('show_toolbar', 'show_toolbar_menu_item') self.adapt('show_statusbar', 'show_statusbar_menu_item') self.adapt('show_thumbnails', 'show_thumbnails_menu_item') self.adapt('show_adjustments', 'show_adjustments_menu_item') self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS # Menu Items def on_scan_window_destroy(self, window): """Exits the application.""" self.quit() def on_scan_menu_item_activate(self, menu_item): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_menu_item_activate(self, menu_item): """Refresh the list of connected scanners from SANE.""" self._update_available_scanners() def on_save_as_menu_item_activate(self, menu_item): """Saves the current document to a file.""" self.application.show_save_dialog() def on_delete_menu_item_activate(self, menu_item): self.application.get_document_controller().delete_selected() def on_preferences_menu_item_activate(self, menu_item): """Creates and displays a preferences dialog.""" self.application.show_preferences_dialog() def on_quit_menu_item_activate(self, menu_item): """Exits the application.""" self.quit() def on_zoom_in_menu_item_activate(self, menu_item): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_menu_item_activate(self, menu_item): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_menu_item_activate(self, menu_item): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_menu_item_activate(self, menu_item): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_available_scanner_menu_item_toggled(self, menu_item): """ Set the active scanner. TODO: Need a second scanner to properly test this... """ main_model = self.application.get_main_model() if menu_item.get_active(): for scanner in main_model.available_scanners: if scanner.display_name == menu_item.get_children()[0].get_text(): main_model.active_scanner = scanner return def on_valid_mode_menu_item_toggled(self, menu_item): """Sets the active scan mode.""" if menu_item.get_active(): self.application.get_main_model().active_mode = \ menu_item.get_children()[0].get_text() def on_valid_resolution_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_resolution = \ menu_item.get_children()[0].get_text() def on_go_first_menu_item_activate(self, menu_item): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_menu_item_activate(self, menu_item): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_menu_item_activate(self, menu_item): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_menu_item_activate(self, menu_item): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() def on_contents_menu_item_clicked(self, menu_item): """TODO""" pass def on_about_menu_item_activate(self, menu_item): """Show the about dialog.""" self.application.show_about_dialog() # Toolbar Buttons def on_scan_button_clicked(self, button): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_button_clicked(self, button): self._update_available_scanners() def on_save_as_button_clicked(self, button): """Saves the current document to a file.""" self.application.show_save_dialog() def on_zoom_in_button_clicked(self, button): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_button_clicked(self, button): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_button_clicked(self, button): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_button_clicked(self, button): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_go_first_button_clicked(self, button): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_button_clicked(self, button): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_button_clicked(self, button): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_button_clicked(self, button): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() # Progress Window INTERFACE CALLBACKS def on_progress_window_delete_event(self, window, event): """ Emulate clicking of the cancel/close button and then hide the window. """ main_view = self.application.get_main_view() self.on_scan_cancel_button_clicked(None) main_view['progress_window'].hide() return True def on_scan_cancel_button_clicked(self, button): """ Cancel the current scan or, if the scan is finished, close the progress window. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress: assert self.cancel_event self.cancel_event.set() else: main_view['progress_window'].hide() def on_scan_again_button_clicked(self, button): """Initiate a new scan from the progress window.""" self._scan() def on_quick_save_button_clicked(self, button): """ Show the save dialog. If the user completes a save then disable the quick save button until another page is scanned. """ main_view = self.application.get_main_view() document_model = self.application.get_document_model() self.application.show_save_dialog() if document_model.count == 0: main_view['quick_save_button'].set_sensitive(False) # MainModel PROPERTY CALLBACKS def property_show_toolbar_value_change(self, model, old_value, new_value): """Update the visibility of the toolbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_toolbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['main_toolbar'].show() else: main_view['main_toolbar'].hide() def property_show_statusbar_value_change(self, model, old_value, new_value): """Update the visibility of the statusbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_statusbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['status_view_docking_viewport'].show() else: main_view['status_view_docking_viewport'].hide() def property_show_thumbnails_value_change(self, model, old_value, new_value): """Update the visibility of the thumbnails.""" main_view = self.application.get_main_view() menu_item = main_view['show_thumbnails_menu_item'] menu_item.set_active(new_value) self.application.get_document_controller().toggle_thumbnails_visible(new_value) def property_show_adjustments_value_change(self, model, old_value, new_value): """Update the visibility of the adjustments controls.""" document_controller = self.application.get_document_controller() main_view = self.application.get_main_view() menu_item = main_view['show_adjustments_menu_item'] menu_item.set_active(new_value) document_controller.toggle_adjustments_visible(new_value) def property_active_scanner_value_change(self, model, old_value, new_value): """ Update the menu and valid scanner options to match the new device. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() for menu_item in main_view['scanner_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value.display_name: menu_item.set_active(True) break def property_active_mode_value_change(self, model, old_value, new_value): """Select the active mode from in the menu.""" main_view = self.application.get_main_view() for menu_item in main_view['scan_mode_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_resolution_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() for menu_item in main_view['scan_resolution_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_available_scanners_value_change(self, model, old_value, new_value): """ Update the menu of available scanners. """ main_view = self.application.get_main_view() self._clear_available_scanners_sub_menu() # Generate the new menu if len(new_value) == 0: menu_item = gtk.MenuItem('No Scanners Connected') menu_item.set_sensitive(False) main_view['scanner_sub_menu'].append(menu_item) else: first_item = None for i in range(len(new_value)): # The first menu item defines the group if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i].display_name) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i].display_name) main_view['scanner_sub_menu'].append(menu_item) main_view['scanner_sub_menu'].show_all() def property_valid_modes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan modes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_modes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Modes") menu_item.set_sensitive(False) main_view['scan_mode_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled) main_view['scan_mode_sub_menu'].append(menu_item) main_view['scan_mode_sub_menu'].show_all() def property_valid_resolutions_value_change(self, model, old_value, new_value): """ Updates the list of valid scan resolutions for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_resolutions_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Resolutions") menu_item.set_sensitive(False) main_view['scan_resolution_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled) main_view['scan_resolution_sub_menu'].append(menu_item) main_view['scan_resolution_sub_menu'].show_all() def property_scan_in_progress_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() def property_updating_available_scanners_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() # DocumentModel PROPERTY CALLBACKS def property_count_value_change(self, model, old_value, new_value): """Toggle available controls.""" self._toggle_document_controls() # THREAD CALLBACKS def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned): main_view = self.application.get_main_view() short_bytes_scanned = float(bytes_scanned) / 1000 short_total_bytes = float(scan_info.total_bytes) / 1000 main_view['scan_progressbar'].set_fraction( float(bytes_scanned) / scan_info.total_bytes) main_view['scan_progressbar'].set_text( 'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes)) # TODO: multi page scans main_view['progress_secondary_label'].set_markup( '<i>Scanning page.</i>') def on_scan_succeeded(self, scanning_thread, pil_image): """ Append the new page to the current document. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['scan_progressbar'].set_fraction(1) main_view['scan_progressbar'].set_text('Scan complete') main_view['progress_secondary_label'].set_markup( '<i>Adding page to document.</i>') gtk.gdk.flush() new_page = PageModel(self.application, pil_image, int(main_model.active_resolution)) self.application.get_document_model().append(new_page) main_view['progress_secondary_label'].set_markup( '<i>Page added.</i>') main_view['scan_again_button'].set_sensitive(True) main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_failed(self, scanning_thread, reason): """ Set that scan is complete. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['progress_secondary_label'].set_markup( '<i>%s</i>' % reason) main_view['scan_again_button'].set_sensitive(True) if self.application.get_document_model().count > 0: main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_aborted(self, scanning_thread, exc_info): """ Change display to indicate that scanning failed and convey the to the user the reason why the thread aborted. If the failure was from a SANE exception then give the user the option to blacklist the device. If not, then reraise the error and let the sys.excepthook deal with it. """ self.on_scan_failed(scanning_thread, 'An error occurred.') if isinstance(exc_info[1], saneme.SaneError): self.run_device_exception_dialog(exc_info) else: raise exc_info[0], exc_info[1], exc_info[2] def on_update_available_scanners_thread_finished(self, update_thread, scanner_list): """Set the new list of available scanners.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() status_controller = self.application.get_status_controller() # Remove scanners that do not support necessary options - preferences_model.unsupported_scanners = [] + preferences_model.unsupported_scanners = [] for scanner in scanner_list: if not scanner.has_option('mode') or \ not scanner.has_option('resolution'): preferences_model.unsupported_scanners.append(scanner.display_name) scanner_list.remove(scanner) # Remove blacklisted scanners scanner_list = \ [scanner for scanner in scanner_list if not \ scanner.display_name in preferences_model.blacklisted_scanners] main_model.available_scanners = scanner_list main_model.updating_available_scanners = False def on_update_available_scanners_thread_aborted(self, update_thread, exc_info): """ Change the display to indicate that no scanners are available and reraise the exception so that it can be caught by the sys.excepthook. There is no reason to handle these cases with a special dialog, if the application failed to even enumerate the available devices then no other action will be possible. This should be fantastically rare. """ self.on_update_available_scanners_thread_finished(update_thread, []) raise exc_info[0], exc_info[1], exc_info[2] # PUBLIC METHODS def quit(self): """Exits the application.""" self.log.debug('Quit.') gtk.main_quit() def run_device_exception_dialog(self, exc_info): """ Display an error dialog that provides the user with the option of blacklisting the device which caused the error. TODO: Move into MainView. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() preferences_model = self.application.get_preferences_model() response = main_view.run_device_exception_dialog(exc_info) if response == constants.RESPONSE_BLACKLIST_DEVICE: temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(exc_info[1].device.display_name) temp_blacklist.sort() preferences_model.blacklisted_scanners = temp_blacklist # PRIVATE METHODS def _clear_available_scanners_sub_menu(self): """Clear the menu of available scanners.""" main_view = self.application.get_main_view() for child in main_view['scanner_sub_menu'].get_children(): main_view['scanner_sub_menu'].remove(child) def _clear_scan_modes_sub_menu(self): """Clear the menu of valid scan modes.""" main_view = self.application.get_main_view() for child in main_view['scan_mode_sub_menu'].get_children(): main_view['scan_mode_sub_menu'].remove(child) def _clear_scan_resolutions_sub_menu(self): """Clear the menu of valid scan resolutions.""" main_view = self.application.get_main_view() for child in main_view['scan_resolution_sub_menu'].get_children(): main_view['scan_resolution_sub_menu'].remove(child) def _toggle_scan_controls(self): """Toggle whether or not the scan controls or accessible.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_scan_controls_sensitive(False) main_view.set_refresh_scanner_controls_sensitive(False) else: if main_model.active_scanner != None: main_view.set_scan_controls_sensitive(True) main_view.set_refresh_scanner_controls_sensitive(True) def _toggle_document_controls(self): """ Toggle available document controls based on the current scanner status and the number of scanned pages. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() # Disable all controls when the scanner is in use if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: count = self.application.get_document_model().count # Disable all controls if no pages are scanned if count == 0: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: # Enable most controls if any pages scanned main_view.set_file_controls_sensitive(True) main_view.set_delete_controls_sensitive(True) main_view.set_zoom_controls_sensitive(True) main_view.set_adjustment_controls_sensitive(True) # Only enable navigation if more than one page scanned if count > 1: main_view.set_navigation_controls_sensitive(True) else: main_view.set_navigation_controls_sensitive(False) def _update_status(self): """ Update the text of the statusbar based on the current state of the application. """ main_model = self.application.get_main_model() status_controller = self.application.get_status_controller() status_controller.pop(self.status_context) if main_model.scan_in_progress: status_controller.push(self.status_context, 'Scanning...') elif main_model.updating_available_scanners: status_controller.push(self.status_context, 'Querying hardware...') else: if main_model.active_scanner: status_controller.push(self.status_context, 'Ready with %s.' % main_model.active_scanner.display_name) else: status_controller.push(self.status_context, 'No scanner available.') def _scan(self): """Begin a scan.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() main_model.scan_in_progress = True scanning_thread = ScanningThread(main_model.active_scanner) scanning_thread.connect("progress", self.on_scan_progress) scanning_thread.connect("succeeded", self.on_scan_succeeded) scanning_thread.connect("failed", self.on_scan_failed) scanning_thread.connect("aborted", self.on_scan_aborted) self.cancel_event = scanning_thread.cancel_event main_view['progress_primary_label'].set_markup( '<big><b>%s</b></big>' % main_model.active_scanner.display_name) main_view['scan_progressbar'].set_fraction(0) main_view['scan_progressbar'].set_text('Waiting for data') main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>') mode = main_model.active_mode if main_model.active_mode else 'Not set' main_view['progress_mode_label'].set_markup(mode) dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set' main_view['progress_resolution_label'].set_markup(dpi) main_view['scan_again_button'].set_sensitive(False) main_view['quick_save_button'].set_sensitive(False) main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL) main_view['progress_window'].show_all() scanning_thread.start() def _update_available_scanners(self): """ Start a new update thread to query for available scanners. """ sane = self.application.get_sane() main_model = self.application.get_main_model() main_model.updating_available_scanners = True update_thread = UpdateAvailableScannersThread(sane) update_thread.connect("finished", self.on_update_available_scanners_thread_finished) update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted) update_thread.start() \ No newline at end of file diff --git a/models/main.py b/models/main.py index f7677c5..8afba06 100644 --- a/models/main.py +++ b/models/main.py @@ -1,308 +1,320 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.utils.properties import saneme class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # saneme.Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ - Write state. + Open the new scanner and write its name to the StateManager. + + Note: This and all other propertys setters related to scanner hardware + will force notifications to all observers by setting the old_value + parameter to None when calling notify_property_value_change(). This + has the effect of making changes in the active scanner or its available + options propagate down to the active mode and other dependent + properties. This way the GUI and the settings applied to the SANE + device are kept synchronized. """ main_controller = self.application.get_main_controller() # Ignore spurious updates old_value = self._prop_active_scanner # Close the old scanner if isinstance(old_value, saneme.Device): old_value.close() # Verify that the proper type is being set if value is not None: assert isinstance(value, saneme.Device) # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it can be opened without error. # This prevents problems with trying to store a Null # value in the state backend and also allows for smooth # transitions if a scanner is disconnected and reconnected. if value is not None: try: value.open() self.valid_modes = value.options['mode'].constraint self.valid_resolutions = \ [str(i) for i in value.options['resolution'].constraint] except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notification to all observers. self.notify_property_value_change( 'active_scanner', old_value, value) def set_prop_active_mode(self, value): """ - Write state. + Update the scanner options and write state to the StateManager. + See L{set_prop_active_scanner} for detailed comments. """ self._prop_active_mode = value if value is not None: # This catches the case where the value is being loaded from state # but a scanner has not yet been activated. if self.active_scanner: try: self.active_scanner.options['mode'].value = value except saneme.SaneReloadOptionsError: # TODO pass self.application.get_state_manager()['scan_mode'] = value self.notify_property_value_change( 'active_mode', None, value) def set_prop_active_resolution(self, value): """ - Write state. + Update the scanner options and write state to the StateManager. + See L{set_prop_active_scanner} for detailed comments. """ self._prop_active_resolution = value if value is not None: # This catches the case where the value is being loaded from state # but a scanner has not yet been activated. if self.active_scanner: try: self.active_scanner.options['resolution'].value = int(value) except saneme.SaneReloadOptionsError: # TODO pass self.application.get_state_manager()['scan_resolution'] = value self.notify_property_value_change( 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ Set the list of available scanners and update the active_scanner. + + See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() self._prop_available_scanners = value # Force notification self.notify_property_value_change( 'available_scanners', None, value) if len(value) == 0: self.active_scanner = None else: # Select the first available scanner if the previously # selected scanner is not in the new list if self._prop_active_scanner not in value: self.active_scanner = value[0] # Otherwise maintain current selection else: self.active_scanner = self.active_scanner def set_prop_valid_modes(self, value): """ - Set the list of valid scan modes, updating the active_mode - if it is no longer in the list. + Set the list of valid scan modes, update the active mode and write state + to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_modes = value self.notify_property_value_change( 'valid_modes', None, value) # Update the active mode if len(value) == 0: self.active_mode = None else: if self.active_mode not in value: self.active_mode = value[0] else: self.active_mode = self.active_mode def set_prop_valid_resolutions(self, value): """ - Set the list of valid scan resolutions, updating the - active_resolution if it is no longer in the list. + Set the list of valid scan resolutions, update the active resolution + and write state to the StateManager. See L{set_prop_available_scanners} for detailed comments. """ self._prop_valid_resolutions = value self.notify_property_value_change( 'valid_resolutions', None, value) # Update the active resolution if len(value) == 0: self.active_resolution = None else: if self.active_resolution not in value: self.active_resolution = value[0] else: self.active_resolution = self.active_resolution # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name(state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: state_manager['scan_resolution'] = self.active_resolution
onyxfish/nostaples
542ff19541ab2b0d81d8055d4f6e1384162324c5
Major code-flow revision so that scanner options could be set in advance of scanning.
diff --git a/controllers/main.py b/controllers/main.py index c76ff03..9cc02e6 100644 --- a/controllers/main.py +++ b/controllers/main.py @@ -1,795 +1,743 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the L{MainController}, which manages interaction between the L{MainModel} and L{MainView}. """ import commands import logging import os import re import threading import gobject import gtk from gtkmvc.controller import Controller from nostaples.models.page import PageModel from nostaples.utils.scanning import * import saneme class MainController(Controller): """ Manages interaction between the L{MainModel} and L{MainView}. """ # SETUP METHODS def __init__(self, application): """ Constructs the MainController, as well as necessary sub-controllers and services. """ self.application = application Controller.__init__(self, application.get_main_model()) application.get_document_model().register_observer(self) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ self.adapt('show_toolbar', 'show_toolbar_menu_item') self.adapt('show_statusbar', 'show_statusbar_menu_item') self.adapt('show_thumbnails', 'show_thumbnails_menu_item') self.adapt('show_adjustments', 'show_adjustments_menu_item') self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS # Menu Items def on_scan_window_destroy(self, window): """Exits the application.""" self.quit() def on_scan_menu_item_activate(self, menu_item): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_menu_item_activate(self, menu_item): """Refresh the list of connected scanners from SANE.""" self._update_available_scanners() def on_save_as_menu_item_activate(self, menu_item): """Saves the current document to a file.""" self.application.show_save_dialog() def on_delete_menu_item_activate(self, menu_item): self.application.get_document_controller().delete_selected() def on_preferences_menu_item_activate(self, menu_item): """Creates and displays a preferences dialog.""" self.application.show_preferences_dialog() def on_quit_menu_item_activate(self, menu_item): """Exits the application.""" self.quit() def on_zoom_in_menu_item_activate(self, menu_item): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_menu_item_activate(self, menu_item): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_menu_item_activate(self, menu_item): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_menu_item_activate(self, menu_item): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_available_scanner_menu_item_toggled(self, menu_item): """ Set the active scanner. TODO: Need a second scanner to properly test this... """ main_model = self.application.get_main_model() if menu_item.get_active(): for scanner in main_model.available_scanners: if scanner.display_name == menu_item.get_children()[0].get_text(): main_model.active_scanner = scanner return def on_valid_mode_menu_item_toggled(self, menu_item): """Sets the active scan mode.""" if menu_item.get_active(): self.application.get_main_model().active_mode = \ menu_item.get_children()[0].get_text() def on_valid_resolution_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_resolution = \ menu_item.get_children()[0].get_text() def on_go_first_menu_item_activate(self, menu_item): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_menu_item_activate(self, menu_item): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_menu_item_activate(self, menu_item): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_menu_item_activate(self, menu_item): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() def on_contents_menu_item_clicked(self, menu_item): """TODO""" pass def on_about_menu_item_activate(self, menu_item): """Show the about dialog.""" self.application.show_about_dialog() # Toolbar Buttons def on_scan_button_clicked(self, button): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_button_clicked(self, button): self._update_available_scanners() def on_save_as_button_clicked(self, button): """Saves the current document to a file.""" self.application.show_save_dialog() def on_zoom_in_button_clicked(self, button): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_button_clicked(self, button): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_button_clicked(self, button): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_button_clicked(self, button): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_go_first_button_clicked(self, button): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_button_clicked(self, button): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_button_clicked(self, button): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_button_clicked(self, button): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() # Progress Window INTERFACE CALLBACKS def on_progress_window_delete_event(self, window, event): """ Emulate clicking of the cancel/close button and then hide the window. """ main_view = self.application.get_main_view() self.on_scan_cancel_button_clicked(None) main_view['progress_window'].hide() return True def on_scan_cancel_button_clicked(self, button): """ Cancel the current scan or, if the scan is finished, close the progress window. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress: assert self.cancel_event self.cancel_event.set() else: main_view['progress_window'].hide() def on_scan_again_button_clicked(self, button): """Initiate a new scan from the progress window.""" self._scan() def on_quick_save_button_clicked(self, button): """ Show the save dialog. If the user completes a save then disable the quick save button until another page is scanned. """ main_view = self.application.get_main_view() document_model = self.application.get_document_model() self.application.show_save_dialog() if document_model.count == 0: main_view['quick_save_button'].set_sensitive(False) # MainModel PROPERTY CALLBACKS def property_show_toolbar_value_change(self, model, old_value, new_value): """Update the visibility of the toolbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_toolbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['main_toolbar'].show() else: main_view['main_toolbar'].hide() def property_show_statusbar_value_change(self, model, old_value, new_value): """Update the visibility of the statusbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_statusbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['status_view_docking_viewport'].show() else: main_view['status_view_docking_viewport'].hide() def property_show_thumbnails_value_change(self, model, old_value, new_value): """Update the visibility of the thumbnails.""" main_view = self.application.get_main_view() menu_item = main_view['show_thumbnails_menu_item'] menu_item.set_active(new_value) self.application.get_document_controller().toggle_thumbnails_visible(new_value) def property_show_adjustments_value_change(self, model, old_value, new_value): """Update the visibility of the adjustments controls.""" + document_controller = self.application.get_document_controller() main_view = self.application.get_main_view() menu_item = main_view['show_adjustments_menu_item'] menu_item.set_active(new_value) - self.application.get_document_controller().toggle_adjustments_visible(new_value) + document_controller.toggle_adjustments_visible(new_value) def property_active_scanner_value_change(self, model, old_value, new_value): """ Update the menu and valid scanner options to match the new device. """ + main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() for menu_item in main_view['scanner_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value.display_name: menu_item.set_active(True) break - self._update_scanner_options() - def property_active_mode_value_change(self, model, old_value, new_value): """Select the active mode from in the menu.""" main_view = self.application.get_main_view() for menu_item in main_view['scan_mode_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_resolution_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() for menu_item in main_view['scan_resolution_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_available_scanners_value_change(self, model, old_value, new_value): """ Update the menu of available scanners. """ main_view = self.application.get_main_view() self._clear_available_scanners_sub_menu() # Generate the new menu if len(new_value) == 0: menu_item = gtk.MenuItem('No Scanners Connected') menu_item.set_sensitive(False) main_view['scanner_sub_menu'].append(menu_item) else: first_item = None for i in range(len(new_value)): # The first menu item defines the group if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i].display_name) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i].display_name) main_view['scanner_sub_menu'].append(menu_item) main_view['scanner_sub_menu'].show_all() def property_valid_modes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan modes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_modes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Modes") menu_item.set_sensitive(False) main_view['scan_mode_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled) main_view['scan_mode_sub_menu'].append(menu_item) main_view['scan_mode_sub_menu'].show_all() def property_valid_resolutions_value_change(self, model, old_value, new_value): """ Updates the list of valid scan resolutions for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_resolutions_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Resolutions") menu_item.set_sensitive(False) main_view['scan_resolution_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled) main_view['scan_resolution_sub_menu'].append(menu_item) main_view['scan_resolution_sub_menu'].show_all() def property_scan_in_progress_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() def property_updating_available_scanners_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() - - def property_updating_scan_options_value_change(self, model, old_value, new_value): - """Disable or re-enable scan controls.""" - self._toggle_scan_controls() - self._toggle_document_controls() - self._update_status() # DocumentModel PROPERTY CALLBACKS def property_count_value_change(self, model, old_value, new_value): """Toggle available controls.""" self._toggle_document_controls() # THREAD CALLBACKS def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned): main_view = self.application.get_main_view() short_bytes_scanned = float(bytes_scanned) / 1000 short_total_bytes = float(scan_info.total_bytes) / 1000 main_view['scan_progressbar'].set_fraction( float(bytes_scanned) / scan_info.total_bytes) main_view['scan_progressbar'].set_text( 'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes)) # TODO: multi page scans main_view['progress_secondary_label'].set_markup( '<i>Scanning page.</i>') def on_scan_succeeded(self, scanning_thread, pil_image): """ Append the new page to the current document. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['scan_progressbar'].set_fraction(1) main_view['scan_progressbar'].set_text('Scan complete') main_view['progress_secondary_label'].set_markup( '<i>Adding page to document.</i>') gtk.gdk.flush() new_page = PageModel(self.application, pil_image, int(main_model.active_resolution)) self.application.get_document_model().append(new_page) main_view['progress_secondary_label'].set_markup( '<i>Page added.</i>') main_view['scan_again_button'].set_sensitive(True) main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_failed(self, scanning_thread, reason): """ Set that scan is complete. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['progress_secondary_label'].set_markup( '<i>%s</i>' % reason) main_view['scan_again_button'].set_sensitive(True) if self.application.get_document_model().count > 0: main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_aborted(self, scanning_thread, exc_info): """ Change display to indicate that scanning failed and convey the to the user the reason why the thread aborted. If the failure was from a SANE exception then give the user the option to blacklist the device. If not, then reraise the error and let the sys.excepthook deal with it. """ self.on_scan_failed(scanning_thread, 'An error occurred.') if isinstance(exc_info[1], saneme.SaneError): self.run_device_exception_dialog(exc_info) else: raise exc_info[0], exc_info[1], exc_info[2] def on_update_available_scanners_thread_finished(self, update_thread, scanner_list): """Set the new list of available scanners.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() status_controller = self.application.get_status_controller() # Remove scanners that do not support necessary options preferences_model.unsupported_scanners = [] for scanner in scanner_list: if not scanner.has_option('mode') or \ not scanner.has_option('resolution'): preferences_model.unsupported_scanners.append(scanner.display_name) scanner_list.remove(scanner) # Remove blacklisted scanners scanner_list = \ [scanner for scanner in scanner_list if not \ scanner.display_name in preferences_model.blacklisted_scanners] main_model.available_scanners = scanner_list main_model.updating_available_scanners = False def on_update_available_scanners_thread_aborted(self, update_thread, exc_info): """ Change the display to indicate that no scanners are available and reraise the exception so that it can be caught by the sys.excepthook. There is no reason to handle these cases with a special dialog, if the application failed to even enumerate the available devices then no other action will be possible. This should be fantastically rare. """ self.on_update_available_scanners_thread_finished(update_thread, []) raise exc_info[0], exc_info[1], exc_info[2] - - def on_update_scanner_options_thread_finished(self, update_thread, mode_list, resolution_list): - """ - Update the mode and resolution lists and rark that - the scanner is no longer in use. - """ - main_model = self.application.get_main_model() - status_controller = self.application.get_status_controller() - - main_model.valid_modes = mode_list - main_model.valid_resolutions = resolution_list - main_model.updating_scan_options = False - - def on_update_scanner_options_thread_aborted(self, update_thread, exc_info): - """ - Change display to indicate that updating the options failed and - convey the to the user the reason why the thread aborted. - - If the failure was from a SANE exception then give the - user the option to blacklist the device. If not, then - reraise the error and let the sys.excepthook deal with it. - """ - # TODO: If this fails the scanner icon will still stay lit, - # and when the user clicks it the app will error again since it - # will not have a valid mode/resolution. - self.on_update_scanner_options_thread_finished(update_thread, [], []) - - if isinstance(exc_info[1], saneme.SaneError): - self.run_device_exception_dialog(exc_info) - else: - raise exc_info[0], exc_info[1], exc_info[2] # PUBLIC METHODS def quit(self): """Exits the application.""" self.log.debug('Quit.') gtk.main_quit() def run_device_exception_dialog(self, exc_info): """ Display an error dialog that provides the user with the option of blacklisting the device which caused the error. TODO: Move into MainView. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() preferences_model = self.application.get_preferences_model() response = main_view.run_device_exception_dialog(exc_info) if response == constants.RESPONSE_BLACKLIST_DEVICE: temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(exc_info[1].device.display_name) temp_blacklist.sort() preferences_model.blacklisted_scanners = temp_blacklist # PRIVATE METHODS def _clear_available_scanners_sub_menu(self): """Clear the menu of available scanners.""" main_view = self.application.get_main_view() for child in main_view['scanner_sub_menu'].get_children(): main_view['scanner_sub_menu'].remove(child) def _clear_scan_modes_sub_menu(self): """Clear the menu of valid scan modes.""" main_view = self.application.get_main_view() for child in main_view['scan_mode_sub_menu'].get_children(): main_view['scan_mode_sub_menu'].remove(child) def _clear_scan_resolutions_sub_menu(self): """Clear the menu of valid scan resolutions.""" main_view = self.application.get_main_view() for child in main_view['scan_resolution_sub_menu'].get_children(): main_view['scan_resolution_sub_menu'].remove(child) def _toggle_scan_controls(self): """Toggle whether or not the scan controls or accessible.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() - if main_model.scan_in_progress or main_model.updating_available_scanners or \ - main_model.updating_scan_options: + if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_scan_controls_sensitive(False) main_view.set_refresh_scanner_controls_sensitive(False) else: if main_model.active_scanner != None: main_view.set_scan_controls_sensitive(True) main_view.set_refresh_scanner_controls_sensitive(True) def _toggle_document_controls(self): """ Toggle available document controls based on the current scanner status and the number of scanned pages. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() # Disable all controls when the scanner is in use - if main_model.scan_in_progress or main_model.updating_available_scanners or \ - main_model.updating_scan_options: + if main_model.scan_in_progress or main_model.updating_available_scanners: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: count = self.application.get_document_model().count # Disable all controls if no pages are scanned if count == 0: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: # Enable most controls if any pages scanned main_view.set_file_controls_sensitive(True) main_view.set_delete_controls_sensitive(True) main_view.set_zoom_controls_sensitive(True) main_view.set_adjustment_controls_sensitive(True) # Only enable navigation if more than one page scanned if count > 1: main_view.set_navigation_controls_sensitive(True) else: main_view.set_navigation_controls_sensitive(False) def _update_status(self): """ Update the text of the statusbar based on the current state of the application. """ main_model = self.application.get_main_model() status_controller = self.application.get_status_controller() status_controller.pop(self.status_context) if main_model.scan_in_progress: status_controller.push(self.status_context, 'Scanning...') elif main_model.updating_available_scanners: status_controller.push(self.status_context, 'Querying hardware...') - elif main_model.updating_scan_options: - status_controller.push(self.status_context, 'Querying options...') else: if main_model.active_scanner: status_controller.push(self.status_context, 'Ready with %s.' % main_model.active_scanner.display_name) else: status_controller.push(self.status_context, 'No scanner available.') def _scan(self): """Begin a scan.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() main_model.scan_in_progress = True - scanning_thread = ScanningThread( - main_model.active_scanner, main_model.active_mode, main_model.active_resolution) + scanning_thread = ScanningThread(main_model.active_scanner) scanning_thread.connect("progress", self.on_scan_progress) scanning_thread.connect("succeeded", self.on_scan_succeeded) scanning_thread.connect("failed", self.on_scan_failed) scanning_thread.connect("aborted", self.on_scan_aborted) self.cancel_event = scanning_thread.cancel_event main_view['progress_primary_label'].set_markup( '<big><b>%s</b></big>' % main_model.active_scanner.display_name) main_view['scan_progressbar'].set_fraction(0) main_view['scan_progressbar'].set_text('Waiting for data') main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>') mode = main_model.active_mode if main_model.active_mode else 'Not set' main_view['progress_mode_label'].set_markup(mode) dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set' main_view['progress_resolution_label'].set_markup(dpi) main_view['scan_again_button'].set_sensitive(False) main_view['quick_save_button'].set_sensitive(False) main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL) main_view['progress_window'].show_all() scanning_thread.start() def _update_available_scanners(self): """ Start a new update thread to query for available scanners. """ sane = self.application.get_sane() main_model = self.application.get_main_model() main_model.updating_available_scanners = True update_thread = UpdateAvailableScannersThread(sane) update_thread.connect("finished", self.on_update_available_scanners_thread_finished) update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted) - update_thread.start() - - def _update_scanner_options(self): - """Determine the valid options for the current scanner.""" - main_model = self.application.get_main_model() - - main_model.updating_scan_options = True - update_thread = UpdateScannerOptionsThread(main_model.active_scanner) - update_thread.connect("finished", self.on_update_scanner_options_thread_finished) - update_thread.connect("aborted", self.on_update_scanner_options_thread_aborted) update_thread.start() \ No newline at end of file diff --git a/models/main.py b/models/main.py index 8f51438..f7677c5 100644 --- a/models/main.py +++ b/models/main.py @@ -1,323 +1,308 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the MainModel, which manages general application data. """ import logging import sys from gtkmvc.model import Model from nostaples import constants import nostaples.utils.properties import saneme class MainModel(Model): """ Handles data all data not specifically handled by another Model (e.g. the state of the main application window). Note: active_scanner is a tuple in the format (display_name, sane_name). available_scanners is a list of such tuples. """ __properties__ = \ { 'show_toolbar' : True, 'show_statusbar' : True, 'show_thumbnails' : True, 'show_adjustments' : False, 'rotate_all_pages' : False, 'active_scanner' : None, # saneme.Device 'active_mode' : None, 'active_resolution' : None, 'available_scanners' : [], # [] of saneme.Device 'valid_modes' : [], 'valid_resolutions' : [], 'scan_in_progress' : False, 'updating_available_scanners' : False, 'updating_scan_options' : False, } def __init__(self, application): """ Constructs the MainModel, as well as necessary sub-models. """ self.application = application Model.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() sane = self.application.get_sane() self.show_toolbar = state_manager.init_state( 'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar')) self.show_statusbar = state_manager.init_state( 'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR, nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar')) self.show_thumbnails = state_manager.init_state( 'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS, nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails')) self.show_adjustments = state_manager.init_state( 'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS, nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments')) self.rotate_all_pages = state_manager.init_state( 'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES, nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages')) # The local representation of active_scanner is a # saneme.Device, but it is persisted by its name attribute only. try: self.active_scanner = sane.get_device_by_name( state_manager.init_state( 'active_scanner', constants.DEFAULT_ACTIVE_SCANNER, self.state_active_scanner_change)) except saneme.SaneNoSuchDeviceError: self.active_scanner = None self.active_mode = state_manager.init_state( 'scan_mode', constants.DEFAULT_SCAN_MODE, self.state_scan_mode_change) self.active_resolution = state_manager.init_state( 'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION, self.state_scan_resolution_change) # PROPERTY SETTERS set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter( 'show_toolbar') set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter( 'show_statusbar') set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter( 'show_thumbnails') set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter( 'show_adjustments') set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter( 'rotate_all_pages') def set_prop_active_scanner(self, value): """ Write state. - See L{set_prop_active_scanner} for detailed comments. """ main_controller = self.application.get_main_controller() # Ignore spurious updates old_value = self._prop_active_scanner - if old_value == value: - return # Close the old scanner - old_value.close() + if isinstance(old_value, saneme.Device): + old_value.close() + # Verify that the proper type is being set if value is not None: assert isinstance(value, saneme.Device) # Update the internal property variable self._prop_active_scanner = value # Only persist the state if the new value is not None # and it can be opened without error. # This prevents problems with trying to store a Null # value in the state backend and also allows for smooth # transitions if a scanner is disconnected and reconnected. if value is not None: try: value.open() + self.valid_modes = value.options['mode'].constraint + self.valid_resolutions = \ + [str(i) for i in value.options['resolution'].constraint] except saneme.SaneError: exc_info = sys.exc_info() main_controller.run_device_exception_dialog(exc_info) self.application.get_state_manager()['active_scanner'] = value.name # Emit the property change notification to all observers. self.notify_property_value_change( 'active_scanner', old_value, value) def set_prop_active_mode(self, value): """ Write state. See L{set_prop_active_scanner} for detailed comments. """ - old_value = self._prop_active_mode - if old_value == value: - return - self._prop_active_mode = value + self._prop_active_mode = value + if value is not None: - self.application.get_state_manager()['scan_mode'] = value + # This catches the case where the value is being loaded from state + # but a scanner has not yet been activated. + if self.active_scanner: + try: + self.active_scanner.options['mode'].value = value + except saneme.SaneReloadOptionsError: + # TODO + pass + + self.application.get_state_manager()['scan_mode'] = value + self.notify_property_value_change( - 'active_mode', old_value, value) + 'active_mode', None, value) def set_prop_active_resolution(self, value): """ Write state. See L{set_prop_active_scanner} for detailed comments. """ - old_value = self._prop_active_resolution - if old_value == value: - return self._prop_active_resolution = value + if value is not None: + # This catches the case where the value is being loaded from state + # but a scanner has not yet been activated. + if self.active_scanner: + try: + self.active_scanner.options['resolution'].value = int(value) + except saneme.SaneReloadOptionsError: + # TODO + pass + self.application.get_state_manager()['scan_resolution'] = value + self.notify_property_value_change( - 'active_resolution', old_value, value) + 'active_resolution', None, value) def set_prop_available_scanners(self, value): """ - Set the list of available scanners, updating the active_scanner - if it is no longer in the list. + Set the list of available scanners and update the active_scanner. """ main_controller = self.application.get_main_controller() - old_value = self._prop_available_scanners + self._prop_available_scanners = value + + # Force notification + self.notify_property_value_change( + 'available_scanners', None, value) if len(value) == 0: - self._prop_active_scanner = None + self.active_scanner = None else: # Select the first available scanner if the previously # selected scanner is not in the new list - # We avoid the active_scanner property setter so that - # The property notification callbacks will not be fired - # until after the menu has been updated. if self._prop_active_scanner not in value: - try: - value[0].open() - - self._prop_active_scanner = value[0] - self.application.get_state_manager()['active_scanner'] = \ - value[0].name - except saneme.SaneError: - exc_info = sys.exc_info() - main_controller.run_device_exception_dialog(exc_info) + self.active_scanner = value[0] # Otherwise maintain current selection else: - pass - - self._prop_available_scanners = value - - # This will only actually cause an update if - # old_value != value - self.notify_property_value_change( - 'available_scanners', old_value, value) - - # Force the scanner options to update, even if the active - # scanner did not change. This is necessary in case the - # current value was loaded from state, in which case the - # options will not yet have been loaded). - self.notify_property_value_change( - 'active_scanner', None, self._prop_active_scanner) + self.active_scanner = self.active_scanner def set_prop_valid_modes(self, value): """ Set the list of valid scan modes, updating the active_mode if it is no longer in the list. See L{set_prop_available_scanners} for detailed comments. """ - old_value = self._prop_valid_modes - - if len(value) == 0: - self._prop_active_mode = None - else: - if self._prop_active_mode not in value: - self._prop_active_mode = value[0] - self.application.get_state_manager()['scan_mode'] = value[0] - else: - pass - self._prop_valid_modes = value self.notify_property_value_change( - 'valid_modes', old_value, value) + 'valid_modes', None, value) - self.notify_property_value_change( - 'active_mode', None, self._prop_active_mode) + # Update the active mode + if len(value) == 0: + self.active_mode = None + else: + if self.active_mode not in value: + self.active_mode = value[0] + else: + self.active_mode = self.active_mode def set_prop_valid_resolutions(self, value): """ Set the list of valid scan resolutions, updating the active_resolution if it is no longer in the list. See L{set_prop_available_scanners} for detailed comments. """ - old_value = self._prop_valid_resolutions + self._prop_valid_resolutions = value + self.notify_property_value_change( + 'valid_resolutions', None, value) + + # Update the active resolution if len(value) == 0: - self._prop_active_resolution = None + self.active_resolution = None else: - if self._prop_active_resolution not in value: - self._prop_active_resolution = value[0] - self.application.get_state_manager()['scan_resolution'] = \ - value[0] + if self.active_resolution not in value: + self.active_resolution = value[0] else: - pass - - self._prop_valid_resolutions = value - - self.notify_property_value_change( - 'valid_resolutions', old_value, value) - - self.notify_property_value_change( - 'active_resolution', None, self._prop_active_resolution) + self.active_resolution = self.active_resolution # STATE CALLBACKS def state_active_scanner_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() sane = self.application.get_sane() if state_manager['active_scanner'] in self.available_scanners: self.active_scanner = sane.get_device_by_name(state_manager['active_scanner']) else: state_manager['active_scanner'] = self.active_scanner.name def state_scan_mode_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_mode'] in self.valid_modes: self.active_mode = state_manager['scan_mode'] else: state_manager['scan_mode'] = self.active_mode def state_scan_resolution_change(self): """Read state, validating the input.""" state_manager = self.application.get_state_manager() if state_manager['scan_resolution'] in self.valid_resolutions: self.active_resolution = state_manager['scan_resolution'] else: - state_manager['scan_resolution'] = self.active_resolution \ No newline at end of file + state_manager['scan_resolution'] = self.active_resolution diff --git a/utils/scanning.py b/utils/scanning.py index 7f5fab6..fbfaf4e 100644 --- a/utils/scanning.py +++ b/utils/scanning.py @@ -1,229 +1,173 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module contains those functions (in the form of Thread objects) that interface with scanning hardware via SANE. """ import commands import logging import os import re import sys import tempfile import threading import gobject from nostaples import constants import saneme class IdleObject(gobject.GObject): """ Override gobject.GObject to always emit signals in the main thread by emitting on an idle handler. This class is based on an example by John Stowers: U{http://www.johnstowers.co.nz/blog/index.php/tag/pygtk/} """ def __init__(self): gobject.GObject.__init__(self) def emit(self, *args): gobject.idle_add(gobject.GObject.emit, self, *args) def abort_on_exception(func): """ This function decorator wraps the run() method of a thread so that any exceptions in that thread will be logged and cause the threads 'abort' signal to be emitted with the exception as an argument. This way all exception handling can occur on the main thread. Note that the entire sys.exc_info() tuple is passed out, this allows the current traceback to be used in the other thread. """ def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception, e: thread_object = args[0] exc_info = sys.exc_info() thread_object.log.error('Exception type %s: %s' % (e.__class__.__name__, e.message)) thread_object.emit('aborted', exc_info) return wrapper class UpdateAvailableScannersThread(IdleObject, threading.Thread): """ Responsible for getting an updated list of available scanners and passing it back to the main thread. """ __gsignals__ = { 'finished': ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)), 'aborted': ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)), } def __init__(self, sane): """ Initialize the thread. """ IdleObject.__init__(self) threading.Thread.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.sane = sane self.log.debug('Created.') @abort_on_exception def run(self): """ Queries SANE for a list of connected scanners and updates the list of available scanners from the results. """ self.log.debug('Updating available scanners.') devices = self.sane.get_device_list() # NB: We callback with the lists so that they can updated on the main thread self.emit('finished', devices) class ScanningThread(IdleObject, threading.Thread): """ Responsible for scanning a page and emitting status callbacks on the main thread. This thread should treat its reference to the ScanningModel as read-only. That way we don't have to worry about making the Model thread-safe. """ __gsignals__ = { 'progress': ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_INT)), 'succeeded': ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)), 'failed': ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)), 'aborted': ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)), } - def __init__(self, sane_device, mode, resolution): + def __init__(self, sane_device): """ Initialize the thread and get a tempfile name that will house the scanned image. """ IdleObject.__init__(self) threading.Thread.__init__(self) self.log = logging.getLogger(self.__class__.__name__) self.sane_device = sane_device - self.mode = mode - self.resolution = resolution self.cancel_event = threading.Event() def progress_callback(self, scan_info, bytes_scanned): """ Pass the progress information on the the main thread and cancel the scan if the cancel event has been set. """ self.emit("progress", scan_info, bytes_scanned) if self.cancel_event.isSet(): return True else: return False @abort_on_exception def run(self): """ Set scanner options, scan a page and emit status callbacks. """ if not self.sane_device.is_open(): raise AssertionError('sane_device.is_open() returned false') - - self.log.debug('Setting device options.') - - try: - self.sane_device.options['mode'].value = self.mode - except saneme.SaneReloadOptionsError: - # TODO - pass - - try: - self.sane_device.options['resolution'].value = int(self.resolution) - except saneme.SaneReloadOptionsError: - # TODO - pass self.log.debug('Beginning scan.') pil_image = None pil_image = self.sane_device.scan(self.progress_callback) if self.cancel_event.isSet(): self.emit("failed", "Scan cancelled") else: if not pil_image: raise AssertionError('sane_device.scan() returned None') - self.emit('succeeded', pil_image) - -class UpdateScannerOptionsThread(IdleObject, threading.Thread): - """ - Responsible for getting an up-to-date list of valid scanner options - and passing it back to the main thread. - """ - __gsignals__ = { - 'finished': ( - gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)), - 'aborted': ( - gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)), - } - - def __init__(self, sane_device): - """ - Initialize the thread. - """ - IdleObject.__init__(self) - threading.Thread.__init__(self) - - self.log = logging.getLogger(self.__class__.__name__) - - self.sane_device = sane_device - - self.log.debug('Created.') - - @abort_on_exception - def run(self): - """ - Queries SANE for a list of available options for the specified scanner. - """ - assert self.sane_device.is_open() - - self.log.debug('Updating scanner options.') - - mode_list = self.sane_device.options['mode'].constraint - resolution_list = [str(i) for i in self.sane_device.options['resolution'].constraint] - - # NB: We callback with the lists so that they can updated on the main thread - self.emit('finished', mode_list, resolution_list) \ No newline at end of file + self.emit('succeeded', pil_image) \ No newline at end of file
onyxfish/nostaples
688e35dab06bcbfff7f6d74c825ab76b9db07c6d
Creating a Device now queries its options without calling open().
diff --git a/sane/saneme.py b/sane/saneme.py index 9ef4574..3b59113 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -1,753 +1,757 @@ #!/usr/bin/python #~ This file is part of SaneMe. #~ SaneMe is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ SaneMe is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with SaneMe. If not, see <http://www.gnu.org/licenses/>. """ This module contains the Pythonic implementation of the SANE API. The flat C functions have been wrapped in a set of objects and all ctypes of the underlying implmentation have been hidden from the user's view. This enumerations and definiations which are absolutely necessary to the end user have been redeclared. """ # TODO: document what exceptions can be thrown by each method, # including those that could bubble up from array import * import atexit import ctypes from types import * from PIL import Image from errors import * from saneh import * # Redeclare saneh enumerations which are visible to the application (OPTION_TYPE_BOOL, OPTION_TYPE_INT, OPTION_TYPE_FIXED, OPTION_TYPE_STRING, OPTION_TYPE_BUTTON, OPTION_TYPE_GROUP) = xrange(6) (OPTION_UNIT_NONE, OPTION_UNIT_PIXEL, OPTION_UNIT_BIT, OPTION_UNIT_MM, OPTION_UNIT_DPI, OPTION_UNIT_PERCENT, OPTION_UNIT_MICROSECOND) = xrange(7) (OPTION_CONSTRAINT_NONE, OPTION_CONSTRAINT_RANGE, OPTION_CONSTRAINT_INTEGER_LIST, OPTION_CONSTRAINT_STRING_LIST) = xrange(4) class SaneMe(object): """ The top-level object for interacting with the SANE API. Handles polling for devices. This object should only be instantiated once. """ _log = None _version = None # (major, minor, build) _devices = [] def __init__(self, log=None): """ Create the SANE object, perform setup, and register the cleanup function. @param log: an optional Python logging object to log to. """ self._log = log self._setup() atexit.register(self._shutdown) # Read only properties def __get_version(self): """Get the current installed version of SANE.""" return self._version version = property(__get_version) def _setup(self): """ Iniitalize SANE and retrieve the current installed version. """ version_code = SANE_Int() auth_callback = SANE_Auth_Callback(self._sane_auth_callback) status = sane_init(byref(version_code), auth_callback) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_init returned an invalid status: %i.' % status) self._version = (SANE_VERSION_MAJOR(version_code), SANE_VERSION_MINOR(version_code), SANE_VERSION_BUILD(version_code)) if self._log: self._log.debug('SANE version %s initalized.', self._version) def _sane_auth_callback(self, resource, username, password): """ TODO """ raise NotImplementedError( 'sane_auth_callback requested, but not yet implemented.') def _shutdown(self): """ Deinitialize SANE. This code would go in L{__del__}, but it is not guaranteed that method will be called and sane_exit must be called to release resources. To ensure this method is called it is registered with atexit. """ for device in self._devices: if device.is_open(): device.close() sane_exit() self._version = None if self._log: self._log.debug('SANE deinitialized.') # Public Methods def get_device_list(self): """ Poll for connected devices. This method may take several seconds to return. Note that SANE is exited and re-inited before querying for devices to workaround a limitation in SANE's USB driver which causes the device list to only be updated on init. This means that all settings applied to all devices will be B{lost} and must be restored by the calling application. This was found documented here: U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html} """ if not self._version: raise AssertionError('version was None') # See docstring for details on this voodoo self._shutdown() self._setup() cdevices = POINTER(POINTER(SANE_Device))() status = sane_get_devices(byref(cdevices), SANE_Bool(0)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_get_devices ran out of memory.') else: raise SaneUnknownError( 'sane_get_devices returned an invalid status: %i.' % status) device_count = 0 self._devices = [] while cdevices[device_count]: self._devices.append(Device(cdevices[device_count].contents)) device_count += 1 if self._log: self._log.debug('SANE queried, %i device(s) found.', device_count) return self._devices def get_device_by_name(self, name): """ Retrieve a L{Device} by name. Must be preceded by a call to L{get_device_list}. """ for device in self._devices: if device.name == name: return device raise SaneNoSuchDeviceError( 'The requested device does not exist.') class Device(object): """ This is the primary object for interacting with SANE. It represents a single device and handles enumeration of options, getting and setting of options, and starting and stopping of scanning jobs. """ _log = None _handle = None _name = '' _vendor = '' _model = '' _type = '' _display_name = '' _options = {} def __init__(self, ctypes_device, log=None): """ Sets the Devices properties from a ctypes SANE_Device and queries for its available options. """ self._log = log if type(ctypes_device.name) is not str: raise AssertionError( 'device name was %s, expected StringType' % type(ctypes_device.name)) if type(ctypes_device.vendor) is not str: raise AssertionError( 'device vendor was %s, expected StringType' % type(ctypes_device.vendor)) if type(ctypes_device.model) is not str: raise AssertionError( 'device model was %s, expected StringType' % type(ctypes_device.model)) if type(ctypes_device.type) is not str: raise AssertionError( 'device type was %s, expected StringType' % type(ctypes_device.type)) self._name = ctypes_device.name self._vendor = ctypes_device.vendor self._model = ctypes_device.model self._type = ctypes_device.type self._display_name = ' '.join([self._vendor, self._model]) + # Temporarily open the device to populate its options + self.open() + self.close() + # Read only properties def __get_name(self): """ Get the complete SANE identifier for this device, e.g. 'lexmark:libusb:002:006'. """ return self._name name = property(__get_name) def __get_vendor(self): """Get the manufacturer of this device, e.g. 'Lexmark'.""" return self._vendor vendor = property(__get_vendor) def __get_model(self): """Get the specific model of this device, e.g. 'X1100/rev. B2'.""" return self._model model = property(__get_model) def __get_type(self): """Get the type of this device, e.g. 'flatbed scanner'.""" return self._type type = property(__get_type) def __get_display_name(self): """ Get an appropriate name to use for displaying this device to a user, e.g. 'Lexmark X1100/rev. B2'.""" return self._display_name display_name = property(__get_display_name) def __get_options(self): """Get the dictionary of options that this device has.""" return self._options options = property(__get_options) # Internal methods def _update_options(self): """ Update the list of available options for this device. As these are immutable, this should only need to be called when the Device is first instantiated. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') option_value = pointer(c_int()) status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: raise SaneUnsupportedOperationError( 'sane_control_option reported that a value was outside the option\'s constraint.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) option_count = option_value.contents.value if self._log: self._log.debug('Device queried, %i option(s) found.', option_count) self._options.clear() i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) self._options[coption.contents.name] = Option(self, i, coption.contents) i = i + 1 # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Public methods def open(self): """ Open a new handle to this device. Must be called before any operations (including setting options) are performed on this device. """ if self._handle: raise AssertionError('device handle already exists.') self._handle = SANE_Handle() status = sane_open(self.name, byref(self._handle)) # If and exception will be thrown, nullify device handle # so is_open() will return false for the device. if status != SANE_STATUS_GOOD.value: self._handle = None if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_open reported that the device was busy.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) self._update_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) def has_option(self, option_name): """Return true if option_name is available for this scanner.""" return (option_name in self.options.keys()) def scan(self, progress_callback=None): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) elif sane_parameters.format == SANE_FRAME_RGB.value: pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capabilities = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number if type(ctypes_option.name) is not StringType: raise AssertionError( 'option name was %s, expected StringType.' % type(ctypes_option.name)) if type(ctypes_option.title) is not StringType: raise AssertionError( 'option title was %s, expected StringType.' % type(ctypes_option.title)) if type(ctypes_option.desc) is not StringType: raise AssertionError( 'option description was %s, expected StringType.' % type(ctypes_option.desc)) if type(ctypes_option.type) is not IntType: raise AssertionError( 'option type was %s, expected IntType.' % type(ctypes_option.type)) if type(ctypes_option.unit) is not IntType: raise AssertionError( 'option unit was %s, expected IntType.' % type(ctypes_option.unit)) if type(ctypes_option.size) is not IntType: raise AssertionError( 'option size was %s, expected IntType.' % type(ctypes_option.size)) if type(ctypes_option.cap) is not IntType: raise AssertionError( 'option cap was %s, expected IntType.' % type(ctypes_option.cap)) if type(ctypes_option.constraint_type) is not IntType: raise AssertionError( 'option constraint_type was %s, expected IntType.' % type(ctypes_option.constraint_type)) self._name = ctypes_option.name self._title = ctypes_option.title self._description = ctypes_option.desc self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: if type(ctypes_option.constraint.range) is not POINTER(SANE_Range): raise AssertionError('option\'s constraint range was not a pointer to a SANE_Range.') if type(ctypes_option.constraint.range.contents.min) is not IntType: raise AssertionError('option\'s constraint range min was not of IntType.') if type(ctypes_option.constraint.range.contents.max) is not IntType: raise AssertionError('option\'s constraint range max was not of IntType.') if type(ctypes_option.constraint.range.contents.quant) is not IntType: raise AssertionError('option\'s constraint range quant was not of IntType.') self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if type(ctypes_option.constraint.word_list) is not POINTER(SANE_Word): raise AssertionError('option\'s constraint range was not a pointer to a SANE_Word.') word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if type(ctypes_option.constraint.string_list) is not POINTER(SANE_String_Const): raise AssertionError('option\'s constraint range was not a pointer to a SANE_String_Const.') string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 # Read only properties def __get_name(self): """Get the short-form name of this option, e.g. 'mode'.""" return self._name name = property(__get_name) def __get_title(self): """Get the full name of this option, e.g. 'Scan mode'.""" return self._title title = property(__get_title) def __get_description(self): """, device=self Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' """ return self._description description = property(__get_description) def __get_type(self): return self._type type = property(__get_type) def __get_unit(self): return self._unit unit = property(__get_unit) def __get_capability(self): # TODO: break out into individual capabilities, rather than a bitset return self._capability capability = property(__get_capability) def __get_constraint_type(self): return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then this is a list of integers which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values.
onyxfish/nostaples
ae3c82c7a97950844fff62179769418857c15bf3
Fixing previous bad commit.
diff --git a/controllers/main.py b/controllers/main.py index 6c8faf0..c76ff03 100644 --- a/controllers/main.py +++ b/controllers/main.py @@ -45,751 +45,751 @@ class MainController(Controller): """ Constructs the MainController, as well as necessary sub-controllers and services. """ self.application = application Controller.__init__(self, application.get_main_model()) application.get_document_model().register_observer(self) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ self.adapt('show_toolbar', 'show_toolbar_menu_item') self.adapt('show_statusbar', 'show_statusbar_menu_item') self.adapt('show_thumbnails', 'show_thumbnails_menu_item') self.adapt('show_adjustments', 'show_adjustments_menu_item') self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS # Menu Items def on_scan_window_destroy(self, window): """Exits the application.""" self.quit() def on_scan_menu_item_activate(self, menu_item): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_menu_item_activate(self, menu_item): """Refresh the list of connected scanners from SANE.""" self._update_available_scanners() def on_save_as_menu_item_activate(self, menu_item): """Saves the current document to a file.""" self.application.show_save_dialog() def on_delete_menu_item_activate(self, menu_item): self.application.get_document_controller().delete_selected() def on_preferences_menu_item_activate(self, menu_item): """Creates and displays a preferences dialog.""" self.application.show_preferences_dialog() def on_quit_menu_item_activate(self, menu_item): """Exits the application.""" self.quit() def on_zoom_in_menu_item_activate(self, menu_item): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_menu_item_activate(self, menu_item): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_menu_item_activate(self, menu_item): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_menu_item_activate(self, menu_item): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_available_scanner_menu_item_toggled(self, menu_item): """ Set the active scanner. TODO: Need a second scanner to properly test this... """ main_model = self.application.get_main_model() if menu_item.get_active(): for scanner in main_model.available_scanners: if scanner.display_name == menu_item.get_children()[0].get_text(): main_model.active_scanner = scanner return def on_valid_mode_menu_item_toggled(self, menu_item): """Sets the active scan mode.""" if menu_item.get_active(): self.application.get_main_model().active_mode = \ menu_item.get_children()[0].get_text() def on_valid_resolution_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_resolution = \ menu_item.get_children()[0].get_text() def on_go_first_menu_item_activate(self, menu_item): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_menu_item_activate(self, menu_item): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_menu_item_activate(self, menu_item): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_menu_item_activate(self, menu_item): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() def on_contents_menu_item_clicked(self, menu_item): """TODO""" pass def on_about_menu_item_activate(self, menu_item): """Show the about dialog.""" self.application.show_about_dialog() # Toolbar Buttons def on_scan_button_clicked(self, button): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_button_clicked(self, button): self._update_available_scanners() def on_save_as_button_clicked(self, button): """Saves the current document to a file.""" self.application.show_save_dialog() def on_zoom_in_button_clicked(self, button): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_button_clicked(self, button): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_button_clicked(self, button): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_button_clicked(self, button): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_go_first_button_clicked(self, button): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_button_clicked(self, button): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_button_clicked(self, button): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_button_clicked(self, button): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() # Progress Window INTERFACE CALLBACKS def on_progress_window_delete_event(self, window, event): """ Emulate clicking of the cancel/close button and then hide the window. """ main_view = self.application.get_main_view() self.on_scan_cancel_button_clicked(None) main_view['progress_window'].hide() return True def on_scan_cancel_button_clicked(self, button): """ Cancel the current scan or, if the scan is finished, close the progress window. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress: assert self.cancel_event self.cancel_event.set() else: main_view['progress_window'].hide() def on_scan_again_button_clicked(self, button): """Initiate a new scan from the progress window.""" self._scan() def on_quick_save_button_clicked(self, button): """ Show the save dialog. If the user completes a save then disable the quick save button until another page is scanned. """ main_view = self.application.get_main_view() document_model = self.application.get_document_model() self.application.show_save_dialog() if document_model.count == 0: main_view['quick_save_button'].set_sensitive(False) # MainModel PROPERTY CALLBACKS def property_show_toolbar_value_change(self, model, old_value, new_value): """Update the visibility of the toolbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_toolbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['main_toolbar'].show() else: main_view['main_toolbar'].hide() def property_show_statusbar_value_change(self, model, old_value, new_value): """Update the visibility of the statusbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_statusbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['status_view_docking_viewport'].show() else: main_view['status_view_docking_viewport'].hide() def property_show_thumbnails_value_change(self, model, old_value, new_value): """Update the visibility of the thumbnails.""" main_view = self.application.get_main_view() menu_item = main_view['show_thumbnails_menu_item'] menu_item.set_active(new_value) self.application.get_document_controller().toggle_thumbnails_visible(new_value) def property_show_adjustments_value_change(self, model, old_value, new_value): """Update the visibility of the adjustments controls.""" main_view = self.application.get_main_view() menu_item = main_view['show_adjustments_menu_item'] menu_item.set_active(new_value) self.application.get_document_controller().toggle_adjustments_visible(new_value) def property_active_scanner_value_change(self, model, old_value, new_value): """ Update the menu and valid scanner options to match the new device. """ main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() for menu_item in main_view['scanner_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value.display_name: menu_item.set_active(True) break self._update_scanner_options() def property_active_mode_value_change(self, model, old_value, new_value): """Select the active mode from in the menu.""" main_view = self.application.get_main_view() for menu_item in main_view['scan_mode_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_resolution_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() for menu_item in main_view['scan_resolution_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_available_scanners_value_change(self, model, old_value, new_value): """ Update the menu of available scanners. """ main_view = self.application.get_main_view() self._clear_available_scanners_sub_menu() # Generate the new menu if len(new_value) == 0: menu_item = gtk.MenuItem('No Scanners Connected') menu_item.set_sensitive(False) main_view['scanner_sub_menu'].append(menu_item) else: first_item = None for i in range(len(new_value)): # The first menu item defines the group if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i].display_name) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i].display_name) main_view['scanner_sub_menu'].append(menu_item) main_view['scanner_sub_menu'].show_all() def property_valid_modes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan modes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_modes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Modes") menu_item.set_sensitive(False) main_view['scan_mode_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled) main_view['scan_mode_sub_menu'].append(menu_item) main_view['scan_mode_sub_menu'].show_all() def property_valid_resolutions_value_change(self, model, old_value, new_value): """ Updates the list of valid scan resolutions for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_resolutions_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Resolutions") menu_item.set_sensitive(False) main_view['scan_resolution_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled) main_view['scan_resolution_sub_menu'].append(menu_item) main_view['scan_resolution_sub_menu'].show_all() def property_scan_in_progress_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() def property_updating_available_scanners_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() def property_updating_scan_options_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() # DocumentModel PROPERTY CALLBACKS def property_count_value_change(self, model, old_value, new_value): """Toggle available controls.""" self._toggle_document_controls() # THREAD CALLBACKS def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned): main_view = self.application.get_main_view() short_bytes_scanned = float(bytes_scanned) / 1000 short_total_bytes = float(scan_info.total_bytes) / 1000 main_view['scan_progressbar'].set_fraction( float(bytes_scanned) / scan_info.total_bytes) main_view['scan_progressbar'].set_text( 'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes)) # TODO: multi page scans main_view['progress_secondary_label'].set_markup( '<i>Scanning page.</i>') def on_scan_succeeded(self, scanning_thread, pil_image): """ Append the new page to the current document. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['scan_progressbar'].set_fraction(1) main_view['scan_progressbar'].set_text('Scan complete') main_view['progress_secondary_label'].set_markup( '<i>Adding page to document.</i>') gtk.gdk.flush() new_page = PageModel(self.application, pil_image, int(main_model.active_resolution)) self.application.get_document_model().append(new_page) main_view['progress_secondary_label'].set_markup( '<i>Page added.</i>') main_view['scan_again_button'].set_sensitive(True) main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_failed(self, scanning_thread, reason): """ Set that scan is complete. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['progress_secondary_label'].set_markup( '<i>%s</i>' % reason) main_view['scan_again_button'].set_sensitive(True) if self.application.get_document_model().count > 0: main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_aborted(self, scanning_thread, exc_info): """ Change display to indicate that scanning failed and convey the to the user the reason why the thread aborted. If the failure was from a SANE exception then give the user the option to blacklist the device. If not, then reraise the error and let the sys.excepthook deal with it. """ self.on_scan_failed(scanning_thread, 'An error occurred.') if isinstance(exc_info[1], saneme.SaneError): self.run_device_exception_dialog(exc_info) else: raise exc_info[0], exc_info[1], exc_info[2] def on_update_available_scanners_thread_finished(self, update_thread, scanner_list): """Set the new list of available scanners.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() status_controller = self.application.get_status_controller() # Remove scanners that do not support necessary options - preferences_model.unsupported_scanners = [] - + preferences_model.unsupported_scanners = [] + for scanner in scanner_list: if not scanner.has_option('mode') or \ not scanner.has_option('resolution'): preferences_model.unsupported_scanners.append(scanner.display_name) scanner_list.remove(scanner) # Remove blacklisted scanners scanner_list = \ [scanner for scanner in scanner_list if not \ scanner.display_name in preferences_model.blacklisted_scanners] main_model.available_scanners = scanner_list main_model.updating_available_scanners = False def on_update_available_scanners_thread_aborted(self, update_thread, exc_info): """ Change the display to indicate that no scanners are available and reraise the exception so that it can be caught by the sys.excepthook. There is no reason to handle these cases with a special dialog, if the application failed to even enumerate the available devices then no other action will be possible. This should be fantastically rare. """ self.on_update_available_scanners_thread_finished(update_thread, []) raise exc_info[0], exc_info[1], exc_info[2] def on_update_scanner_options_thread_finished(self, update_thread, mode_list, resolution_list): """ Update the mode and resolution lists and rark that the scanner is no longer in use. """ main_model = self.application.get_main_model() status_controller = self.application.get_status_controller() main_model.valid_modes = mode_list main_model.valid_resolutions = resolution_list main_model.updating_scan_options = False def on_update_scanner_options_thread_aborted(self, update_thread, exc_info): """ Change display to indicate that updating the options failed and convey the to the user the reason why the thread aborted. If the failure was from a SANE exception then give the user the option to blacklist the device. If not, then reraise the error and let the sys.excepthook deal with it. """ # TODO: If this fails the scanner icon will still stay lit, # and when the user clicks it the app will error again since it # will not have a valid mode/resolution. self.on_update_scanner_options_thread_finished(update_thread, [], []) if isinstance(exc_info[1], saneme.SaneError): self.run_device_exception_dialog(exc_info) else: raise exc_info[0], exc_info[1], exc_info[2] # PUBLIC METHODS def quit(self): """Exits the application.""" self.log.debug('Quit.') gtk.main_quit() def run_device_exception_dialog(self, exc_info): """ Display an error dialog that provides the user with the option of blacklisting the device which caused the error. TODO: Move into MainView. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() preferences_model = self.application.get_preferences_model() response = main_view.run_device_exception_dialog(exc_info) if response == constants.RESPONSE_BLACKLIST_DEVICE: temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(exc_info[1].device.display_name) temp_blacklist.sort() preferences_model.blacklisted_scanners = temp_blacklist # PRIVATE METHODS def _clear_available_scanners_sub_menu(self): """Clear the menu of available scanners.""" main_view = self.application.get_main_view() for child in main_view['scanner_sub_menu'].get_children(): main_view['scanner_sub_menu'].remove(child) def _clear_scan_modes_sub_menu(self): """Clear the menu of valid scan modes.""" main_view = self.application.get_main_view() for child in main_view['scan_mode_sub_menu'].get_children(): main_view['scan_mode_sub_menu'].remove(child) def _clear_scan_resolutions_sub_menu(self): """Clear the menu of valid scan resolutions.""" main_view = self.application.get_main_view() for child in main_view['scan_resolution_sub_menu'].get_children(): main_view['scan_resolution_sub_menu'].remove(child) def _toggle_scan_controls(self): """Toggle whether or not the scan controls or accessible.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress or main_model.updating_available_scanners or \ main_model.updating_scan_options: main_view.set_scan_controls_sensitive(False) main_view.set_refresh_scanner_controls_sensitive(False) else: if main_model.active_scanner != None: main_view.set_scan_controls_sensitive(True) main_view.set_refresh_scanner_controls_sensitive(True) def _toggle_document_controls(self): """ Toggle available document controls based on the current scanner status and the number of scanned pages. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() # Disable all controls when the scanner is in use if main_model.scan_in_progress or main_model.updating_available_scanners or \ main_model.updating_scan_options: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: count = self.application.get_document_model().count # Disable all controls if no pages are scanned if count == 0: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: # Enable most controls if any pages scanned main_view.set_file_controls_sensitive(True) main_view.set_delete_controls_sensitive(True) main_view.set_zoom_controls_sensitive(True) main_view.set_adjustment_controls_sensitive(True) # Only enable navigation if more than one page scanned if count > 1: main_view.set_navigation_controls_sensitive(True) else: main_view.set_navigation_controls_sensitive(False) def _update_status(self): """ Update the text of the statusbar based on the current state of the application. """ main_model = self.application.get_main_model() status_controller = self.application.get_status_controller() status_controller.pop(self.status_context) if main_model.scan_in_progress: status_controller.push(self.status_context, 'Scanning...') elif main_model.updating_available_scanners: status_controller.push(self.status_context, 'Querying hardware...') elif main_model.updating_scan_options: status_controller.push(self.status_context, 'Querying options...') else: if main_model.active_scanner: status_controller.push(self.status_context, 'Ready with %s.' % main_model.active_scanner.display_name) else: status_controller.push(self.status_context, 'No scanner available.') def _scan(self): """Begin a scan.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() main_model.scan_in_progress = True scanning_thread = ScanningThread( main_model.active_scanner, main_model.active_mode, main_model.active_resolution) scanning_thread.connect("progress", self.on_scan_progress) scanning_thread.connect("succeeded", self.on_scan_succeeded) scanning_thread.connect("failed", self.on_scan_failed) scanning_thread.connect("aborted", self.on_scan_aborted) self.cancel_event = scanning_thread.cancel_event main_view['progress_primary_label'].set_markup( '<big><b>%s</b></big>' % main_model.active_scanner.display_name) main_view['scan_progressbar'].set_fraction(0) main_view['scan_progressbar'].set_text('Waiting for data') main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>') mode = main_model.active_mode if main_model.active_mode else 'Not set' main_view['progress_mode_label'].set_markup(mode) dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set' main_view['progress_resolution_label'].set_markup(dpi) main_view['scan_again_button'].set_sensitive(False) main_view['quick_save_button'].set_sensitive(False) main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL) main_view['progress_window'].show_all() scanning_thread.start() def _update_available_scanners(self): """ Start a new update thread to query for available scanners. """ sane = self.application.get_sane() main_model = self.application.get_main_model() main_model.updating_available_scanners = True update_thread = UpdateAvailableScannersThread(sane) update_thread.connect("finished", self.on_update_available_scanners_thread_finished) update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted) update_thread.start() def _update_scanner_options(self): """Determine the valid options for the current scanner.""" main_model = self.application.get_main_model() main_model.updating_scan_options = True update_thread = UpdateScannerOptionsThread(main_model.active_scanner) update_thread.connect("finished", self.on_update_scanner_options_thread_finished) update_thread.connect("aborted", self.on_update_scanner_options_thread_aborted) update_thread.start() \ No newline at end of file
onyxfish/nostaples
9c5bd3433d424bf6cf72a4bc25869e5f668c18f7
Added automatic recognition of unsupported devices (i.e. webcams).
diff --git a/controllers/main.py b/controllers/main.py index 2253f53..6c8faf0 100644 --- a/controllers/main.py +++ b/controllers/main.py @@ -44,743 +44,752 @@ class MainController(Controller): def __init__(self, application): """ Constructs the MainController, as well as necessary sub-controllers and services. """ self.application = application Controller.__init__(self, application.get_main_model()) application.get_document_model().register_observer(self) status_controller = application.get_status_controller() self.status_context = \ status_controller.get_context_id(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def register_view(self, view): """ Registers this controller with a view. """ Controller.register_view(self, view) self.log.debug('%s registered.', view.__class__.__name__) def register_adapters(self): """ Registers adapters for property/widget pairs that do not require complex processing. """ self.adapt('show_toolbar', 'show_toolbar_menu_item') self.adapt('show_statusbar', 'show_statusbar_menu_item') self.adapt('show_thumbnails', 'show_thumbnails_menu_item') self.adapt('show_adjustments', 'show_adjustments_menu_item') self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item') self.log.debug('Adapters registered.') # USER INTERFACE CALLBACKS # Menu Items def on_scan_window_destroy(self, window): """Exits the application.""" self.quit() def on_scan_menu_item_activate(self, menu_item): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_menu_item_activate(self, menu_item): """Refresh the list of connected scanners from SANE.""" self._update_available_scanners() def on_save_as_menu_item_activate(self, menu_item): """Saves the current document to a file.""" self.application.show_save_dialog() def on_delete_menu_item_activate(self, menu_item): self.application.get_document_controller().delete_selected() def on_preferences_menu_item_activate(self, menu_item): """Creates and displays a preferences dialog.""" self.application.show_preferences_dialog() def on_quit_menu_item_activate(self, menu_item): """Exits the application.""" self.quit() def on_zoom_in_menu_item_activate(self, menu_item): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_menu_item_activate(self, menu_item): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_menu_item_activate(self, menu_item): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_menu_item_activate(self, menu_item): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_menu_item_activate(self, menu_item): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_available_scanner_menu_item_toggled(self, menu_item): """ Set the active scanner. TODO: Need a second scanner to properly test this... """ main_model = self.application.get_main_model() if menu_item.get_active(): for scanner in main_model.available_scanners: if scanner.display_name == menu_item.get_children()[0].get_text(): main_model.active_scanner = scanner return def on_valid_mode_menu_item_toggled(self, menu_item): """Sets the active scan mode.""" if menu_item.get_active(): self.application.get_main_model().active_mode = \ menu_item.get_children()[0].get_text() def on_valid_resolution_menu_item_toggled(self, menu_item): """Sets the active scan resolution.""" if menu_item.get_active(): self.application.get_main_model().active_resolution = \ menu_item.get_children()[0].get_text() def on_go_first_menu_item_activate(self, menu_item): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_menu_item_activate(self, menu_item): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_menu_item_activate(self, menu_item): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_menu_item_activate(self, menu_item): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() def on_contents_menu_item_clicked(self, menu_item): """TODO""" pass def on_about_menu_item_activate(self, menu_item): """Show the about dialog.""" self.application.show_about_dialog() # Toolbar Buttons def on_scan_button_clicked(self, button): """Scan a page into the current document.""" self._scan() def on_refresh_available_scanners_button_clicked(self, button): self._update_available_scanners() def on_save_as_button_clicked(self, button): """Saves the current document to a file.""" self.application.show_save_dialog() def on_zoom_in_button_clicked(self, button): """Zooms the page preview in.""" self.application.get_page_controller().zoom_in() def on_zoom_out_button_clicked(self, button): """Zooms the page preview out.""" self.application.get_page_controller().zoom_out() def on_zoom_one_to_one_button_clicked(self, button): """Zooms the page preview to the true size of the scanned image.""" self.application.get_page_controller().zoom_one_to_one() def on_zoom_best_fit_button_clicked(self, button): """Zooms the page preview to best fit within the preview window.""" self.application.get_page_controller().zoom_best_fit() def on_rotate_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress clockwise.""" self.application.get_document_controller().rotate_clockwise( self.application.get_main_model().rotate_all_pages) def on_rotate_counter_clockwise_button_clicked(self, button): """Rotates the visible page ninety degress counter-clockwise.""" self.application.get_document_controller().rotate_counter_clockwise( self.application.get_main_model().rotate_all_pages) def on_go_first_button_clicked(self, button): """Selects the first scanned page.""" self.application.get_document_controller().goto_first_page() def on_go_previous_button_clicked(self, button): """Selects the scanned page before to the currently selected one.""" self.application.get_document_controller().goto_previous_page() def on_go_next_button_clicked(self, button): """Selects the scanned page after to the currently selected one.""" self.application.get_document_controller().goto_next_page() def on_go_last_button_clicked(self, button): """Selects the last scanned page.""" self.application.get_document_controller().goto_last_page() # Progress Window INTERFACE CALLBACKS def on_progress_window_delete_event(self, window, event): """ Emulate clicking of the cancel/close button and then hide the window. """ main_view = self.application.get_main_view() self.on_scan_cancel_button_clicked(None) main_view['progress_window'].hide() return True def on_scan_cancel_button_clicked(self, button): """ Cancel the current scan or, if the scan is finished, close the progress window. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress: assert self.cancel_event self.cancel_event.set() else: main_view['progress_window'].hide() def on_scan_again_button_clicked(self, button): """Initiate a new scan from the progress window.""" self._scan() def on_quick_save_button_clicked(self, button): """ Show the save dialog. If the user completes a save then disable the quick save button until another page is scanned. """ main_view = self.application.get_main_view() document_model = self.application.get_document_model() self.application.show_save_dialog() if document_model.count == 0: main_view['quick_save_button'].set_sensitive(False) # MainModel PROPERTY CALLBACKS def property_show_toolbar_value_change(self, model, old_value, new_value): """Update the visibility of the toolbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_toolbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['main_toolbar'].show() else: main_view['main_toolbar'].hide() def property_show_statusbar_value_change(self, model, old_value, new_value): """Update the visibility of the statusbar.""" main_view = self.application.get_main_view() menu_item = main_view['show_statusbar_menu_item'] menu_item.set_active(new_value) if new_value: main_view['status_view_docking_viewport'].show() else: main_view['status_view_docking_viewport'].hide() def property_show_thumbnails_value_change(self, model, old_value, new_value): """Update the visibility of the thumbnails.""" main_view = self.application.get_main_view() menu_item = main_view['show_thumbnails_menu_item'] menu_item.set_active(new_value) self.application.get_document_controller().toggle_thumbnails_visible(new_value) def property_show_adjustments_value_change(self, model, old_value, new_value): """Update the visibility of the adjustments controls.""" main_view = self.application.get_main_view() menu_item = main_view['show_adjustments_menu_item'] menu_item.set_active(new_value) self.application.get_document_controller().toggle_adjustments_visible(new_value) def property_active_scanner_value_change(self, model, old_value, new_value): """ Update the menu and valid scanner options to match the new device. """ main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() for menu_item in main_view['scanner_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value.display_name: menu_item.set_active(True) break self._update_scanner_options() def property_active_mode_value_change(self, model, old_value, new_value): """Select the active mode from in the menu.""" main_view = self.application.get_main_view() for menu_item in main_view['scan_mode_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_active_resolution_value_change(self, model, old_value, new_value): """Select the active resolution from in the menu.""" main_view = self.application.get_main_view() for menu_item in main_view['scan_resolution_sub_menu'].get_children(): if menu_item.get_children()[0].get_text() == new_value: menu_item.set_active(True) break def property_available_scanners_value_change(self, model, old_value, new_value): """ Update the menu of available scanners. """ main_view = self.application.get_main_view() self._clear_available_scanners_sub_menu() # Generate the new menu if len(new_value) == 0: menu_item = gtk.MenuItem('No Scanners Connected') menu_item.set_sensitive(False) main_view['scanner_sub_menu'].append(menu_item) else: first_item = None for i in range(len(new_value)): # The first menu item defines the group if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i].display_name) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i].display_name) main_view['scanner_sub_menu'].append(menu_item) main_view['scanner_sub_menu'].show_all() def property_valid_modes_value_change(self, model, old_value, new_value): """ Updates the list of valid scan modes for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_modes_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Modes") menu_item.set_sensitive(False) main_view['scan_mode_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled) main_view['scan_mode_sub_menu'].append(menu_item) main_view['scan_mode_sub_menu'].show_all() def property_valid_resolutions_value_change(self, model, old_value, new_value): """ Updates the list of valid scan resolutions for the current scanner. """ main_view = self.application.get_main_view() self._clear_scan_resolutions_sub_menu() if len(new_value) == 0: menu_item = gtk.MenuItem("No Scan Resolutions") menu_item.set_sensitive(False) main_view['scan_resolution_sub_menu'].append(menu_item) else: for i in range(len(new_value)): if i == 0: menu_item = gtk.RadioMenuItem( None, new_value[i]) first_item = menu_item else: menu_item = gtk.RadioMenuItem( first_item, new_value[i]) menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled) main_view['scan_resolution_sub_menu'].append(menu_item) main_view['scan_resolution_sub_menu'].show_all() def property_scan_in_progress_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() def property_updating_available_scanners_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() def property_updating_scan_options_value_change(self, model, old_value, new_value): """Disable or re-enable scan controls.""" self._toggle_scan_controls() self._toggle_document_controls() self._update_status() # DocumentModel PROPERTY CALLBACKS def property_count_value_change(self, model, old_value, new_value): """Toggle available controls.""" self._toggle_document_controls() # THREAD CALLBACKS def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned): main_view = self.application.get_main_view() short_bytes_scanned = float(bytes_scanned) / 1000 short_total_bytes = float(scan_info.total_bytes) / 1000 main_view['scan_progressbar'].set_fraction( float(bytes_scanned) / scan_info.total_bytes) main_view['scan_progressbar'].set_text( 'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes)) # TODO: multi page scans main_view['progress_secondary_label'].set_markup( '<i>Scanning page.</i>') def on_scan_succeeded(self, scanning_thread, pil_image): """ Append the new page to the current document. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['scan_progressbar'].set_fraction(1) main_view['scan_progressbar'].set_text('Scan complete') main_view['progress_secondary_label'].set_markup( '<i>Adding page to document.</i>') gtk.gdk.flush() new_page = PageModel(self.application, pil_image, int(main_model.active_resolution)) self.application.get_document_model().append(new_page) main_view['progress_secondary_label'].set_markup( '<i>Page added.</i>') main_view['scan_again_button'].set_sensitive(True) main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_failed(self, scanning_thread, reason): """ Set that scan is complete. TODO: update docstring """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() status_controller = self.application.get_status_controller() main_view['progress_secondary_label'].set_markup( '<i>%s</i>' % reason) main_view['scan_again_button'].set_sensitive(True) if self.application.get_document_model().count > 0: main_view['quick_save_button'].set_sensitive(True) main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE) main_model.scan_in_progress = False def on_scan_aborted(self, scanning_thread, exc_info): """ Change display to indicate that scanning failed and convey the to the user the reason why the thread aborted. If the failure was from a SANE exception then give the user the option to blacklist the device. If not, then reraise the error and let the sys.excepthook deal with it. """ self.on_scan_failed(scanning_thread, 'An error occurred.') if isinstance(exc_info[1], saneme.SaneError): self.run_device_exception_dialog(exc_info) else: raise exc_info[0], exc_info[1], exc_info[2] def on_update_available_scanners_thread_finished(self, update_thread, scanner_list): """Set the new list of available scanners.""" main_model = self.application.get_main_model() preferences_model = self.application.get_preferences_model() status_controller = self.application.get_status_controller() + # Remove scanners that do not support necessary options + preferences_model.unsupported_scanners = [] + + for scanner in scanner_list: + if not scanner.has_option('mode') or \ + not scanner.has_option('resolution'): + preferences_model.unsupported_scanners.append(scanner.display_name) + scanner_list.remove(scanner) + # Remove blacklisted scanners scanner_list = \ [scanner for scanner in scanner_list if not \ scanner.display_name in preferences_model.blacklisted_scanners] main_model.available_scanners = scanner_list main_model.updating_available_scanners = False def on_update_available_scanners_thread_aborted(self, update_thread, exc_info): """ Change the display to indicate that no scanners are available and reraise the exception so that it can be caught by the sys.excepthook. There is no reason to handle these cases with a special dialog, if the application failed to even enumerate the available devices then no other action will be possible. This should be fantastically rare. """ self.on_update_available_scanners_thread_finished(update_thread, []) raise exc_info[0], exc_info[1], exc_info[2] def on_update_scanner_options_thread_finished(self, update_thread, mode_list, resolution_list): """ Update the mode and resolution lists and rark that the scanner is no longer in use. """ main_model = self.application.get_main_model() status_controller = self.application.get_status_controller() main_model.valid_modes = mode_list main_model.valid_resolutions = resolution_list main_model.updating_scan_options = False def on_update_scanner_options_thread_aborted(self, update_thread, exc_info): """ Change display to indicate that updating the options failed and convey the to the user the reason why the thread aborted. If the failure was from a SANE exception then give the user the option to blacklist the device. If not, then reraise the error and let the sys.excepthook deal with it. """ # TODO: If this fails the scanner icon will still stay lit, # and when the user clicks it the app will error again since it # will not have a valid mode/resolution. self.on_update_scanner_options_thread_finished(update_thread, [], []) if isinstance(exc_info[1], saneme.SaneError): self.run_device_exception_dialog(exc_info) else: raise exc_info[0], exc_info[1], exc_info[2] # PUBLIC METHODS def quit(self): """Exits the application.""" self.log.debug('Quit.') gtk.main_quit() def run_device_exception_dialog(self, exc_info): """ Display an error dialog that provides the user with the option of blacklisting the device which caused the error. TODO: Move into MainView. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() preferences_model = self.application.get_preferences_model() response = main_view.run_device_exception_dialog(exc_info) if response == constants.RESPONSE_BLACKLIST_DEVICE: temp_blacklist = list(preferences_model.blacklisted_scanners) temp_blacklist.append(exc_info[1].device.display_name) temp_blacklist.sort() preferences_model.blacklisted_scanners = temp_blacklist # PRIVATE METHODS def _clear_available_scanners_sub_menu(self): """Clear the menu of available scanners.""" main_view = self.application.get_main_view() for child in main_view['scanner_sub_menu'].get_children(): main_view['scanner_sub_menu'].remove(child) def _clear_scan_modes_sub_menu(self): """Clear the menu of valid scan modes.""" main_view = self.application.get_main_view() for child in main_view['scan_mode_sub_menu'].get_children(): main_view['scan_mode_sub_menu'].remove(child) def _clear_scan_resolutions_sub_menu(self): """Clear the menu of valid scan resolutions.""" main_view = self.application.get_main_view() for child in main_view['scan_resolution_sub_menu'].get_children(): main_view['scan_resolution_sub_menu'].remove(child) def _toggle_scan_controls(self): """Toggle whether or not the scan controls or accessible.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() if main_model.scan_in_progress or main_model.updating_available_scanners or \ main_model.updating_scan_options: main_view.set_scan_controls_sensitive(False) main_view.set_refresh_scanner_controls_sensitive(False) else: if main_model.active_scanner != None: main_view.set_scan_controls_sensitive(True) main_view.set_refresh_scanner_controls_sensitive(True) def _toggle_document_controls(self): """ Toggle available document controls based on the current scanner status and the number of scanned pages. """ main_model = self.application.get_main_model() main_view = self.application.get_main_view() # Disable all controls when the scanner is in use if main_model.scan_in_progress or main_model.updating_available_scanners or \ main_model.updating_scan_options: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: count = self.application.get_document_model().count # Disable all controls if no pages are scanned if count == 0: main_view.set_file_controls_sensitive(False) main_view.set_delete_controls_sensitive(False) main_view.set_zoom_controls_sensitive(False) main_view.set_adjustment_controls_sensitive(False) main_view.set_navigation_controls_sensitive(False) else: # Enable most controls if any pages scanned main_view.set_file_controls_sensitive(True) main_view.set_delete_controls_sensitive(True) main_view.set_zoom_controls_sensitive(True) main_view.set_adjustment_controls_sensitive(True) # Only enable navigation if more than one page scanned if count > 1: main_view.set_navigation_controls_sensitive(True) else: main_view.set_navigation_controls_sensitive(False) def _update_status(self): """ Update the text of the statusbar based on the current state of the application. """ main_model = self.application.get_main_model() status_controller = self.application.get_status_controller() status_controller.pop(self.status_context) if main_model.scan_in_progress: status_controller.push(self.status_context, 'Scanning...') elif main_model.updating_available_scanners: status_controller.push(self.status_context, 'Querying hardware...') elif main_model.updating_scan_options: status_controller.push(self.status_context, 'Querying options...') else: if main_model.active_scanner: status_controller.push(self.status_context, 'Ready with %s.' % main_model.active_scanner.display_name) else: status_controller.push(self.status_context, 'No scanner available.') def _scan(self): """Begin a scan.""" main_model = self.application.get_main_model() main_view = self.application.get_main_view() main_model.scan_in_progress = True scanning_thread = ScanningThread( main_model.active_scanner, main_model.active_mode, main_model.active_resolution) scanning_thread.connect("progress", self.on_scan_progress) scanning_thread.connect("succeeded", self.on_scan_succeeded) scanning_thread.connect("failed", self.on_scan_failed) scanning_thread.connect("aborted", self.on_scan_aborted) self.cancel_event = scanning_thread.cancel_event main_view['progress_primary_label'].set_markup( '<big><b>%s</b></big>' % main_model.active_scanner.display_name) main_view['scan_progressbar'].set_fraction(0) main_view['scan_progressbar'].set_text('Waiting for data') main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>') mode = main_model.active_mode if main_model.active_mode else 'Not set' main_view['progress_mode_label'].set_markup(mode) dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set' main_view['progress_resolution_label'].set_markup(dpi) main_view['scan_again_button'].set_sensitive(False) main_view['quick_save_button'].set_sensitive(False) main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL) main_view['progress_window'].show_all() scanning_thread.start() def _update_available_scanners(self): """ Start a new update thread to query for available scanners. """ sane = self.application.get_sane() main_model = self.application.get_main_model() main_model.updating_available_scanners = True update_thread = UpdateAvailableScannersThread(sane) update_thread.connect("finished", self.on_update_available_scanners_thread_finished) update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted) update_thread.start() def _update_scanner_options(self): """Determine the valid options for the current scanner.""" main_model = self.application.get_main_model() main_model.updating_scan_options = True update_thread = UpdateScannerOptionsThread(main_model.active_scanner) update_thread.connect("finished", self.on_update_scanner_options_thread_finished) update_thread.connect("aborted", self.on_update_scanner_options_thread_aborted) update_thread.start() \ No newline at end of file diff --git a/models/preferences.py b/models/preferences.py index 51ba663..4d4e7a4 100644 --- a/models/preferences.py +++ b/models/preferences.py @@ -1,85 +1,86 @@ #!/usr/bin/python #~ This file is part of NoStaples. #~ NoStaples is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ NoStaples is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with NoStaples. If not, see <http://www.gnu.org/licenses/>. """ This module holds the PreferencesModel, which manages user settings. """ import logging from gtkmvc.model import Model from nostaples import constants import nostaples.utils.properties class PreferencesModel(Model): """ Manages user settings. """ __properties__ = \ { 'preview_mode' : constants.DEFAULT_PREVIEW_MODE, 'thumbnail_size' : constants.DEFAULT_THUMBNAIL_SIZE, + 'unsupported_scanners' : [], # Not persisted 'blacklisted_scanners' : [], # List of scanner display names 'saved_keywords' : '', } def __init__(self, application): """ Constructs the PreferencesModel. """ Model.__init__(self) self.application = application self.log = logging.getLogger(self.__class__.__name__) self.log.debug('Created.') def load_state(self): """ Load persisted state from the self.state_manager. """ state_manager = self.application.get_state_manager() self.preview_mode = state_manager.init_state( 'preview_mode', constants.DEFAULT_PREVIEW_MODE, nostaples.utils.properties.PropertyStateCallback(self, 'preview_mode')) self.thumbnail_size = state_manager.init_state( 'thumbnail_size', constants.DEFAULT_THUMBNAIL_SIZE, nostaples.utils.properties.PropertyStateCallback(self, 'thumbnail_size')) self.blacklisted_scanners = state_manager.init_state( 'blacklisted_scanners', constants.DEFAULT_BLACKLISTED_SCANNERS, nostaples.utils.properties.PropertyStateCallback(self, 'blacklisted_scanners')) self.saved_keywords = state_manager.init_state( 'saved_keywords', constants.DEFAULT_SAVED_KEYWORDS, nostaples.utils.properties.PropertyStateCallback(self, 'saved_keywords')) # PROPERTY SETTERS set_prop_preview_mode = nostaples.utils.properties.StatefulPropertySetter( 'preview_mode') set_prop_thumbnail_size = nostaples.utils.properties.StatefulPropertySetter( 'thumbnail_size') set_prop_blacklisted_scanners = nostaples.utils.properties.StatefulPropertySetter( 'blacklisted_scanners') set_prop_saved_keywords = nostaples.utils.properties.StatefulPropertySetter( 'saved_keywords') \ No newline at end of file
onyxfish/nostaples
8101f834717b75f83eda084d12f1b96081e4d4cd
Added has_option Device method.
diff --git a/sane/saneme.py b/sane/saneme.py index 1cbbaf7..9ef4574 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -1,944 +1,948 @@ #!/usr/bin/python #~ This file is part of SaneMe. #~ SaneMe is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ SaneMe is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with SaneMe. If not, see <http://www.gnu.org/licenses/>. """ This module contains the Pythonic implementation of the SANE API. The flat C functions have been wrapped in a set of objects and all ctypes of the underlying implmentation have been hidden from the user's view. This enumerations and definiations which are absolutely necessary to the end user have been redeclared. """ # TODO: document what exceptions can be thrown by each method, # including those that could bubble up from array import * import atexit import ctypes from types import * from PIL import Image from errors import * from saneh import * # Redeclare saneh enumerations which are visible to the application (OPTION_TYPE_BOOL, OPTION_TYPE_INT, OPTION_TYPE_FIXED, OPTION_TYPE_STRING, OPTION_TYPE_BUTTON, OPTION_TYPE_GROUP) = xrange(6) (OPTION_UNIT_NONE, OPTION_UNIT_PIXEL, OPTION_UNIT_BIT, OPTION_UNIT_MM, OPTION_UNIT_DPI, OPTION_UNIT_PERCENT, OPTION_UNIT_MICROSECOND) = xrange(7) (OPTION_CONSTRAINT_NONE, OPTION_CONSTRAINT_RANGE, OPTION_CONSTRAINT_INTEGER_LIST, OPTION_CONSTRAINT_STRING_LIST) = xrange(4) class SaneMe(object): """ The top-level object for interacting with the SANE API. Handles polling for devices. This object should only be instantiated once. """ _log = None _version = None # (major, minor, build) _devices = [] def __init__(self, log=None): """ Create the SANE object, perform setup, and register the cleanup function. @param log: an optional Python logging object to log to. """ self._log = log self._setup() atexit.register(self._shutdown) # Read only properties def __get_version(self): """Get the current installed version of SANE.""" return self._version version = property(__get_version) def _setup(self): """ Iniitalize SANE and retrieve the current installed version. """ version_code = SANE_Int() auth_callback = SANE_Auth_Callback(self._sane_auth_callback) status = sane_init(byref(version_code), auth_callback) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_init returned an invalid status: %i.' % status) self._version = (SANE_VERSION_MAJOR(version_code), SANE_VERSION_MINOR(version_code), SANE_VERSION_BUILD(version_code)) if self._log: self._log.debug('SANE version %s initalized.', self._version) def _sane_auth_callback(self, resource, username, password): """ TODO """ raise NotImplementedError( 'sane_auth_callback requested, but not yet implemented.') def _shutdown(self): """ Deinitialize SANE. This code would go in L{__del__}, but it is not guaranteed that method will be called and sane_exit must be called to release resources. To ensure this method is called it is registered with atexit. """ for device in self._devices: if device.is_open(): device.close() sane_exit() self._version = None if self._log: self._log.debug('SANE deinitialized.') # Public Methods def get_device_list(self): """ Poll for connected devices. This method may take several seconds to return. Note that SANE is exited and re-inited before querying for devices to workaround a limitation in SANE's USB driver which causes the device list to only be updated on init. This means that all settings applied to all devices will be B{lost} and must be restored by the calling application. This was found documented here: U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html} """ if not self._version: raise AssertionError('version was None') # See docstring for details on this voodoo self._shutdown() self._setup() cdevices = POINTER(POINTER(SANE_Device))() status = sane_get_devices(byref(cdevices), SANE_Bool(0)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_get_devices ran out of memory.') else: raise SaneUnknownError( 'sane_get_devices returned an invalid status: %i.' % status) device_count = 0 self._devices = [] while cdevices[device_count]: self._devices.append(Device(cdevices[device_count].contents)) device_count += 1 if self._log: self._log.debug('SANE queried, %i device(s) found.', device_count) return self._devices def get_device_by_name(self, name): """ Retrieve a L{Device} by name. Must be preceded by a call to L{get_device_list}. """ for device in self._devices: if device.name == name: return device raise SaneNoSuchDeviceError( 'The requested device does not exist.') class Device(object): """ This is the primary object for interacting with SANE. It represents a single device and handles enumeration of options, getting and setting of options, and starting and stopping of scanning jobs. """ _log = None _handle = None _name = '' _vendor = '' _model = '' _type = '' _display_name = '' _options = {} def __init__(self, ctypes_device, log=None): """ Sets the Devices properties from a ctypes SANE_Device and queries for its available options. """ self._log = log if type(ctypes_device.name) is not str: raise AssertionError( 'device name was %s, expected StringType' % type(ctypes_device.name)) if type(ctypes_device.vendor) is not str: raise AssertionError( 'device vendor was %s, expected StringType' % type(ctypes_device.vendor)) if type(ctypes_device.model) is not str: raise AssertionError( 'device model was %s, expected StringType' % type(ctypes_device.model)) if type(ctypes_device.type) is not str: raise AssertionError( 'device type was %s, expected StringType' % type(ctypes_device.type)) self._name = ctypes_device.name self._vendor = ctypes_device.vendor self._model = ctypes_device.model self._type = ctypes_device.type self._display_name = ' '.join([self._vendor, self._model]) # Read only properties def __get_name(self): """ Get the complete SANE identifier for this device, e.g. 'lexmark:libusb:002:006'. """ return self._name name = property(__get_name) def __get_vendor(self): """Get the manufacturer of this device, e.g. 'Lexmark'.""" return self._vendor vendor = property(__get_vendor) def __get_model(self): """Get the specific model of this device, e.g. 'X1100/rev. B2'.""" return self._model model = property(__get_model) def __get_type(self): """Get the type of this device, e.g. 'flatbed scanner'.""" return self._type type = property(__get_type) def __get_display_name(self): """ Get an appropriate name to use for displaying this device to a user, e.g. 'Lexmark X1100/rev. B2'.""" return self._display_name display_name = property(__get_display_name) def __get_options(self): """Get the dictionary of options that this device has.""" return self._options options = property(__get_options) # Internal methods def _update_options(self): """ Update the list of available options for this device. As these are immutable, this should only need to be called when the Device is first instantiated. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') option_value = pointer(c_int()) status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: raise SaneUnsupportedOperationError( 'sane_control_option reported that a value was outside the option\'s constraint.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) option_count = option_value.contents.value if self._log: self._log.debug('Device queried, %i option(s) found.', option_count) self._options.clear() i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) self._options[coption.contents.name] = Option(self, i, coption.contents) i = i + 1 # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Public methods def open(self): """ Open a new handle to this device. Must be called before any operations (including setting options) are performed on this device. """ if self._handle: raise AssertionError('device handle already exists.') self._handle = SANE_Handle() status = sane_open(self.name, byref(self._handle)) # If and exception will be thrown, nullify device handle # so is_open() will return false for the device. if status != SANE_STATUS_GOOD.value: self._handle = None if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_open reported that the device was busy.', device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( 'sane_open reported that the device name was invalid.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_open reported a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_open ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_open requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_open returned an invalid status: %i.' % status, device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) self._update_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) + def has_option(self, option_name): + """Return true if option_name is available for this scanner.""" + return (option_name in self.options.keys()) + def scan(self, progress_callback=None): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( 'sane_start reported cancelled status before it was set.', device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( 'sane_start reported the device was in use.', device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_start reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_start reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_start reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_start encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_start ran out of memory.', device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs raise SaneInvalidDataError( device=self) else: raise SaneUnknownError( 'sane_start returned an invalid status: %i.' % status, device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_get_parameters returned an invalid status: %i.' % status, device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( 'sane_read reported a paper jam.', device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( 'sane_read reported that the document feeder was empty.', device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( 'sane_read reported that the device cover was open.', device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_read encountered a communications error.', device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_read ran out of memory.', device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_read requires greater access to open the device.', device=self) else: raise SaneUnknownError( 'sane_read returned an invalid status: %i.' % status, device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) elif sane_parameters.format == SANE_FRAME_RGB.value: pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capabilities = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number if type(ctypes_option.name) is not StringType: raise AssertionError( 'option name was %s, expected StringType.' % type(ctypes_option.name)) if type(ctypes_option.title) is not StringType: raise AssertionError( 'option title was %s, expected StringType.' % type(ctypes_option.title)) if type(ctypes_option.desc) is not StringType: raise AssertionError( 'option description was %s, expected StringType.' % type(ctypes_option.desc)) if type(ctypes_option.type) is not IntType: raise AssertionError( 'option type was %s, expected IntType.' % type(ctypes_option.type)) if type(ctypes_option.unit) is not IntType: raise AssertionError( 'option unit was %s, expected IntType.' % type(ctypes_option.unit)) if type(ctypes_option.size) is not IntType: raise AssertionError( 'option size was %s, expected IntType.' % type(ctypes_option.size)) if type(ctypes_option.cap) is not IntType: raise AssertionError( 'option cap was %s, expected IntType.' % type(ctypes_option.cap)) if type(ctypes_option.constraint_type) is not IntType: raise AssertionError( 'option constraint_type was %s, expected IntType.' % type(ctypes_option.constraint_type)) self._name = ctypes_option.name self._title = ctypes_option.title self._description = ctypes_option.desc self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: if type(ctypes_option.constraint.range) is not POINTER(SANE_Range): raise AssertionError('option\'s constraint range was not a pointer to a SANE_Range.') if type(ctypes_option.constraint.range.contents.min) is not IntType: raise AssertionError('option\'s constraint range min was not of IntType.') if type(ctypes_option.constraint.range.contents.max) is not IntType: raise AssertionError('option\'s constraint range max was not of IntType.') if type(ctypes_option.constraint.range.contents.quant) is not IntType: raise AssertionError('option\'s constraint range quant was not of IntType.') self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if type(ctypes_option.constraint.word_list) is not POINTER(SANE_Word): raise AssertionError('option\'s constraint range was not a pointer to a SANE_Word.') word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if type(ctypes_option.constraint.string_list) is not POINTER(SANE_String_Const): raise AssertionError('option\'s constraint range was not a pointer to a SANE_String_Const.') string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 # Read only properties def __get_name(self): """Get the short-form name of this option, e.g. 'mode'.""" return self._name name = property(__get_name) def __get_title(self): """Get the full name of this option, e.g. 'Scan mode'.""" return self._title title = property(__get_title) def __get_description(self): """, device=self Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' """ return self._description description = property(__get_description) def __get_type(self): return self._type type = property(__get_type) def __get_unit(self): return self._unit unit = property(__get_unit) def __get_capability(self): # TODO: break out into individual capabilities, rather than a bitset return self._capability capability = property(__get_capability) def __get_constraint_type(self): return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then this is a list of integers which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """ Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option(handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i.' % status, device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value else: option_value = option_value.contents.value if self._log: self._log.debug( 'Option %s queried, its current value is %s.', self._name, option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: raise AssertionError( 'option set with %s, expected BooleanType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise AssertionError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise AssertionError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: raise AssertionError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: raise AssertionError( 'value for option is longer than max string size') c_value = c_char_p(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: if value < self._constraint[0]: raise AssertionError('value for option is less than min.') if value > self._constraint[1]: raise AssertionError('value for option is greater than max.') if value % self._constraint[2] != 0: raise AssertionError( 'value for option is not divisible by quant.') elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: raise AssertionError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: raise AssertionError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( 'sane_control_option reported a communications error.', device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_control_option ran out of memory.', device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( 'sane_control_option requires greater access to open the device.', device=self._device) else: raise SaneUnknownError( 'sane_control_option returned an invalid status: %i .' % status, device=self._device) if self._log: self._log.debug('Option %s set to value %s.', self._name, value) # See SANE API 4.3.7 if info_flags.value & SANE_INFO_RELOAD_OPTIONS: raise SaneReloadOptionsError() value = property(__get_value, __set_value) class ScanInfo(object): """ Contains the parameters and progress of a scan in progress. """ _width = 0 _height = 0 _depth = 0 _total_bytes = 0 def __init__(self, sane_parameters): """ Initialize the ScanInfo object from the sane_parameters. """ self._width = sane_parameters.pixels_per_line self._height = sane_parameters.lines self._depth = sane_parameters.depth self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines # Read only properties def __get_width(self): """Get the width of the current scan, in pixels.""" return self._width
onyxfish/nostaples
0e7be30c07f70f3436801bc349cc918fbd3a65fc
Added device parameter to raise statements for SANE device exceptions.
diff --git a/sane/saneme.py b/sane/saneme.py index 2a7e379..1cbbaf7 100644 --- a/sane/saneme.py +++ b/sane/saneme.py @@ -1,963 +1,1001 @@ #!/usr/bin/python #~ This file is part of SaneMe. #~ SaneMe is free software: you can redistribute it and/or modify #~ it under the terms of the GNU General Public License as published by #~ the Free Software Foundation, either version 3 of the License, or #~ (at your option) any later version. #~ SaneMe is distributed in the hope that it will be useful, #~ but WITHOUT ANY WARRANTY; without even the implied warranty of #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #~ GNU General Public License for more details. #~ You should have received a copy of the GNU General Public License #~ along with SaneMe. If not, see <http://www.gnu.org/licenses/>. """ This module contains the Pythonic implementation of the SANE API. The flat C functions have been wrapped in a set of objects and all ctypes of the underlying implmentation have been hidden from the user's view. This enumerations and definiations which are absolutely necessary to the end user have been redeclared. """ # TODO: document what exceptions can be thrown by each method, # including those that could bubble up from array import * import atexit import ctypes from types import * from PIL import Image from errors import * from saneh import * # Redeclare saneh enumerations which are visible to the application (OPTION_TYPE_BOOL, OPTION_TYPE_INT, OPTION_TYPE_FIXED, OPTION_TYPE_STRING, OPTION_TYPE_BUTTON, OPTION_TYPE_GROUP) = xrange(6) (OPTION_UNIT_NONE, OPTION_UNIT_PIXEL, OPTION_UNIT_BIT, OPTION_UNIT_MM, OPTION_UNIT_DPI, OPTION_UNIT_PERCENT, OPTION_UNIT_MICROSECOND) = xrange(7) (OPTION_CONSTRAINT_NONE, OPTION_CONSTRAINT_RANGE, OPTION_CONSTRAINT_INTEGER_LIST, OPTION_CONSTRAINT_STRING_LIST) = xrange(4) class SaneMe(object): """ The top-level object for interacting with the SANE API. Handles polling for devices. This object should only be instantiated once. """ _log = None _version = None # (major, minor, build) _devices = [] def __init__(self, log=None): """ Create the SANE object, perform setup, and register the cleanup function. @param log: an optional Python logging object to log to. """ self._log = log self._setup() atexit.register(self._shutdown) # Read only properties def __get_version(self): """Get the current installed version of SANE.""" return self._version version = property(__get_version) def _setup(self): """ Iniitalize SANE and retrieve the current installed version. """ version_code = SANE_Int() auth_callback = SANE_Auth_Callback(self._sane_auth_callback) status = sane_init(byref(version_code), auth_callback) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( 'sane_init returned an invalid status: %i.' % status) self._version = (SANE_VERSION_MAJOR(version_code), SANE_VERSION_MINOR(version_code), SANE_VERSION_BUILD(version_code)) if self._log: self._log.debug('SANE version %s initalized.', self._version) def _sane_auth_callback(self, resource, username, password): """ TODO """ raise NotImplementedError( 'sane_auth_callback requested, but not yet implemented.') def _shutdown(self): """ Deinitialize SANE. This code would go in L{__del__}, but it is not guaranteed that method will be called and sane_exit must be called to release resources. To ensure this method is called it is registered with atexit. """ for device in self._devices: if device.is_open(): device.close() sane_exit() self._version = None if self._log: self._log.debug('SANE deinitialized.') # Public Methods def get_device_list(self): """ Poll for connected devices. This method may take several seconds to return. Note that SANE is exited and re-inited before querying for devices to workaround a limitation in SANE's USB driver which causes the device list to only be updated on init. This means that all settings applied to all devices will be B{lost} and must be restored by the calling application. This was found documented here: U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html} """ if not self._version: raise AssertionError('version was None') # See docstring for details on this voodoo self._shutdown() self._setup() cdevices = POINTER(POINTER(SANE_Device))() status = sane_get_devices(byref(cdevices), SANE_Bool(0)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( 'sane_get_devices ran out of memory.') else: raise SaneUnknownError( 'sane_get_devices returned an invalid status: %i.' % status) device_count = 0 self._devices = [] while cdevices[device_count]: self._devices.append(Device(cdevices[device_count].contents)) device_count += 1 if self._log: self._log.debug('SANE queried, %i device(s) found.', device_count) return self._devices def get_device_by_name(self, name): """ Retrieve a L{Device} by name. Must be preceded by a call to L{get_device_list}. """ for device in self._devices: if device.name == name: return device raise SaneNoSuchDeviceError( 'The requested device does not exist.') class Device(object): """ This is the primary object for interacting with SANE. It represents a single device and handles enumeration of options, getting and setting of options, and starting and stopping of scanning jobs. """ _log = None _handle = None _name = '' _vendor = '' _model = '' _type = '' _display_name = '' _options = {} def __init__(self, ctypes_device, log=None): """ Sets the Devices properties from a ctypes SANE_Device and queries for its available options. """ self._log = log if type(ctypes_device.name) is not str: raise AssertionError( 'device name was %s, expected StringType' % type(ctypes_device.name)) if type(ctypes_device.vendor) is not str: raise AssertionError( 'device vendor was %s, expected StringType' % type(ctypes_device.vendor)) if type(ctypes_device.model) is not str: raise AssertionError( 'device model was %s, expected StringType' % type(ctypes_device.model)) if type(ctypes_device.type) is not str: raise AssertionError( 'device type was %s, expected StringType' % type(ctypes_device.type)) self._name = ctypes_device.name self._vendor = ctypes_device.vendor self._model = ctypes_device.model self._type = ctypes_device.type self._display_name = ' '.join([self._vendor, self._model]) # Read only properties def __get_name(self): """ Get the complete SANE identifier for this device, e.g. 'lexmark:libusb:002:006'. """ return self._name name = property(__get_name) def __get_vendor(self): """Get the manufacturer of this device, e.g. 'Lexmark'.""" return self._vendor vendor = property(__get_vendor) def __get_model(self): """Get the specific model of this device, e.g. 'X1100/rev. B2'.""" return self._model model = property(__get_model) def __get_type(self): """Get the type of this device, e.g. 'flatbed scanner'.""" return self._type type = property(__get_type) def __get_display_name(self): """ Get an appropriate name to use for displaying this device to a user, e.g. 'Lexmark X1100/rev. B2'.""" return self._display_name display_name = property(__get_display_name) def __get_options(self): """Get the dictionary of options that this device has.""" return self._options options = property(__get_options) # Internal methods def _update_options(self): """ Update the list of available options for this device. As these are immutable, this should only need to be called when the Device is first instantiated. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') option_value = pointer(c_int()) status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: raise SaneUnsupportedOperationError( - 'sane_control_option reported that a value was outside the option\'s constraint.') + 'sane_control_option reported that a value was outside the option\'s constraint.', + device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( - 'sane_open reported that the device name was invalid.') + 'sane_open reported that the device name was invalid.', + device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( - 'sane_open reported a communications error.') + 'sane_open reported a communications error.', + device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( - 'sane_open ran out of memory.') + 'sane_open ran out of memory.', + device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( - 'sane_open requires greater access to open the device.') + 'sane_open requires greater access to open the device.', + device=self) else: raise SaneUnknownError( - 'sane_open returned an invalid status: %i.' % status) + 'sane_open returned an invalid status: %i.' % status, + device=self) option_count = option_value.contents.value if self._log: self._log.debug('Device queried, %i option(s) found.', option_count) self._options.clear() i = 1 while(i < option_count - 1): coption = sane_get_option_descriptor(self._handle, i) self._options[coption.contents.name] = Option(self, i, coption.contents) i = i + 1 # Methods for use only by Options def _get_handle(self): """ Verify that the device is open and get the current open handle. To be called by Options of this device so that they may set themselves. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') return self._handle # Public methods def open(self): """ Open a new handle to this device. Must be called before any operations (including setting options) are performed on this device. """ if self._handle: raise AssertionError('device handle already exists.') self._handle = SANE_Handle() status = sane_open(self.name, byref(self._handle)) # If and exception will be thrown, nullify device handle # so is_open() will return false for the device. if status != SANE_STATUS_GOOD.value: self._handle = None if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( - 'sane_open reported that the device was busy.') + 'sane_open reported that the device was busy.', + device=self) elif status == SANE_STATUS_INVAL.value: raise SaneInvalidParameterError( - 'sane_open reported that the device name was invalid.') + 'sane_open reported that the device name was invalid.', + device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( - 'sane_open reported a communications error.') + 'sane_open reported a communications error.', + device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( - 'sane_open ran out of memory.') + 'sane_open ran out of memory.', + device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( - 'sane_open requires greater access to open the device.') + 'sane_open requires greater access to open the device.', + device=self) else: raise SaneUnknownError( - 'sane_open returned an invalid status: %i.' % status) + 'sane_open returned an invalid status: %i.' % status, + device=self) if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') if self._log: self._log.debug('Device %s open.', self._name) self._update_options() def is_open(self): """ Return true if there is an active handle to this device. """ return (self._handle is not None) def close(self): """ Close the current handle to this device. All changes made to its options will be lost. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') sane_close(self._handle) self._handle = None if self._log: self._log.debug('Device %s closed.', self._name) def scan(self, progress_callback=None): """ Scan a document using this device. TODO: handle ADF scans @param progress_callback: An optional callback that will be called each time data is read from the device. Has the format: cancel = progress_callback(sane_info, bytes_read) @return: A PIL image containing the scanned page. """ if not self._handle: raise AssertionError('device handle was None.') if self._handle == c_void_p(None): raise AssertionError('device handle was a null pointer.') # See SANE API 4.3.9 status = sane_start(self._handle) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_CANCELLED.value: raise AssertionError( - 'sane_start reported cancelled status before it was set.') + 'sane_start reported cancelled status before it was set.', + device=self) elif status == SANE_STATUS_DEVICE_BUSY.value: raise SaneDeviceBusyError( - 'sane_start reported the device was in use.') + 'sane_start reported the device was in use.', + device=self) elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( - 'sane_start reported a paper jam.') + 'sane_start reported a paper jam.', + device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( - 'sane_start reported that the document feeder was empty.') + 'sane_start reported that the document feeder was empty.', + device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( - 'sane_start reported that the device cover was open.') + 'sane_start reported that the device cover was open.', + device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( - 'sane_start encountered a communications error.') + 'sane_start encountered a communications error.', + device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( - 'sane_start ran out of memory.') + 'sane_start ran out of memory.', + device=self) elif status == SANE_STATUS_INVAL.value: #TODO - see docs - raise SaneInvalidDataError() + raise SaneInvalidDataError( + device=self) else: raise SaneUnknownError( - 'sane_start returned an invalid status: %i.' % status) + 'sane_start returned an invalid status: %i.' % status, + device=self) sane_parameters = SANE_Parameters() # See SANE API 4.3.8 status = sane_get_parameters(self._handle, byref(sane_parameters)) if status != SANE_STATUS_GOOD.value: raise SaneUnknownError( - 'sane_get_parameters returned an invalid status: %i.' % status) + 'sane_get_parameters returned an invalid status: %i.' % status, + device=self) scan_info = ScanInfo(sane_parameters) # This is the size used for the scan buffer in SANE's scanimage # utility. The precise reasoning for using 32kb is unclear. bytes_per_read = 32768 data_array = array('B') temp_array = (SANE_Byte * bytes_per_read)() actual_size = SANE_Int() cancel = False while True: # See SANE API 4.3.10 status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_EOF.value: break elif status == SANE_STATUS_CANCELLED.value: return None elif status == SANE_STATUS_JAMMED.value: raise SaneDeviceJammedError( - 'sane_read reported a paper jam.') + 'sane_read reported a paper jam.', + device=self) elif status == SANE_STATUS_NO_DOCS.value: raise SaneNoDocumentsError( - 'sane_read reported that the document feeder was empty.') + 'sane_read reported that the document feeder was empty.', + device=self) elif status == SANE_STATUS_COVER_OPEN.value: raise SaneCoverOpenError( - 'sane_read reported that the device cover was open.') + 'sane_read reported that the device cover was open.', + device=self) elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( - 'sane_read encountered a communications error.') + 'sane_read encountered a communications error.', + device=self) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( - 'sane_read ran out of memory.') + 'sane_read ran out of memory.', + device=self) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( - 'sane_read requires greater access to open the device.') + 'sane_read requires greater access to open the device.', + device=self) else: raise SaneUnknownError( - 'sane_read returned an invalid status: %i.' % status) + 'sane_read returned an invalid status: %i.' % status, + device=self) data_array.extend(temp_array[0:actual_size.value]) if progress_callback: cancel = progress_callback(scan_info, len(data_array)) if cancel: sane_cancel(self._handle) return None if cancel: raise AssertionError('cancel was true after scan completed.') sane_cancel(self._handle) if scan_info.total_bytes != len(data_array): raise AssertionError( 'length of scanned data did not match expected length.') if sane_parameters.format == SANE_FRAME_GRAY.value: pil_image = Image.frombuffer( 'L', (scan_info.width, scan_info.height), data_array, 'raw', 'L', 0, 1) elif sane_parameters.format == SANE_FRAME_RGB.value: pil_image = Image.frombuffer( 'RGB', (scan_info.width, scan_info.height), data_array, 'raw', 'RGB', 0, 1) else: # TODO raise NotImplementedError( 'Individual color frame scanned, but not yet supported.') return pil_image class Option(object): """ Represents a single option available for a device. Exposes a variety of information designed to make it easy for a GUI to render each arbitrary option in a user-friendly way. """ log = None _device = None _option_number = 0 _name = '' _title = '' _description = '' _type = 0 _unit = 0 _size = 0 _capabilities = 0 _constraint_type = 0 _constraint = None def __init__(self, device, option_number, ctypes_option, log=None): """ Construct the option from a given ctypes SANE_Option_Descriptor. Parse the necessary constraint information from the SANE_Constraint and SANE_Range structures. """ self._log = log self._device = device self._option_number = option_number if type(ctypes_option.name) is not StringType: raise AssertionError( 'option name was %s, expected StringType.' % type(ctypes_option.name)) if type(ctypes_option.title) is not StringType: raise AssertionError( 'option title was %s, expected StringType.' % type(ctypes_option.title)) if type(ctypes_option.desc) is not StringType: raise AssertionError( 'option description was %s, expected StringType.' % type(ctypes_option.desc)) if type(ctypes_option.type) is not IntType: raise AssertionError( 'option type was %s, expected IntType.' % type(ctypes_option.type)) if type(ctypes_option.unit) is not IntType: raise AssertionError( 'option unit was %s, expected IntType.' % type(ctypes_option.unit)) if type(ctypes_option.size) is not IntType: raise AssertionError( 'option size was %s, expected IntType.' % type(ctypes_option.size)) if type(ctypes_option.cap) is not IntType: raise AssertionError( 'option cap was %s, expected IntType.' % type(ctypes_option.cap)) if type(ctypes_option.constraint_type) is not IntType: raise AssertionError( 'option constraint_type was %s, expected IntType.' % type(ctypes_option.constraint_type)) self._name = ctypes_option.name self._title = ctypes_option.title self._description = ctypes_option.desc self._type = ctypes_option.type self._unit = ctypes_option.unit self._size = ctypes_option.size self._capability = ctypes_option.cap self._constraint_type = ctypes_option.constraint_type if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: if type(ctypes_option.constraint.range) is not POINTER(SANE_Range): raise AssertionError('option\'s constraint range was not a pointer to a SANE_Range.') if type(ctypes_option.constraint.range.contents.min) is not IntType: raise AssertionError('option\'s constraint range min was not of IntType.') if type(ctypes_option.constraint.range.contents.max) is not IntType: raise AssertionError('option\'s constraint range max was not of IntType.') if type(ctypes_option.constraint.range.contents.quant) is not IntType: raise AssertionError('option\'s constraint range quant was not of IntType.') self._constraint = ( ctypes_option.constraint.range.contents.min, ctypes_option.constraint.range.contents.max, ctypes_option.constraint.range.contents.quant) elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if type(ctypes_option.constraint.word_list) is not POINTER(SANE_Word): raise AssertionError('option\'s constraint range was not a pointer to a SANE_Word.') word_count = ctypes_option.constraint.word_list[0] self._constraint = [] i = 1 while(i < word_count): self._constraint.append(ctypes_option.constraint.word_list[i]) i = i + 1 elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if type(ctypes_option.constraint.string_list) is not POINTER(SANE_String_Const): raise AssertionError('option\'s constraint range was not a pointer to a SANE_String_Const.') string_count = 0 self._constraint = [] while ctypes_option.constraint.string_list[string_count]: self._constraint.append(ctypes_option.constraint.string_list[string_count]) string_count += 1 # Read only properties def __get_name(self): """Get the short-form name of this option, e.g. 'mode'.""" return self._name name = property(__get_name) def __get_title(self): """Get the full name of this option, e.g. 'Scan mode'.""" return self._title title = property(__get_title) def __get_description(self): - """ + """, + device=self Get the full description of this option, e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).' """ return self._description description = property(__get_description) def __get_type(self): return self._type type = property(__get_type) def __get_unit(self): return self._unit unit = property(__get_unit) def __get_capability(self): # TODO: break out into individual capabilities, rather than a bitset return self._capability capability = property(__get_capability) def __get_constraint_type(self): return self._constraint_type constraint_type = property(__get_constraint_type) def __get_constraint(self): """ Get the constraint for this option. If constraint_type is OPTION_CONSTRAINT_RANGE then this is a tuple containing the (minimum, maximum, step) for valid values. If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then this is a list of integers which are valid values. If constraint_type is OPTION_CONSTRAINT_STRING_LIST then this is a list of strings which are valid values. """ return self._constraint constraint = property(__get_constraint) def __get_value(self): """ Get the current value of this option. """ handle = self._device._get_handle() if self._type == SANE_TYPE_BOOL.value: option_value = pointer(SANE_Bool()) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 option_value = pointer(SANE_Int()) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 option_value = pointer(SANE_Fixed()) elif self._type == SANE_TYPE_STRING.value: # sane_control_option expects a mutable string buffer option_value = create_string_buffer(self._size) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') status = sane_control_option(handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported a value was invalid, but no value was being set.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( - 'sane_control_option reported a communications error.') + 'sane_control_option reported a communications error.', + device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( - 'sane_control_option ran out of memory.') + 'sane_control_option ran out of memory.', + device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( - 'sane_control_option requires greater access to open the device.') + 'sane_control_option requires greater access to open the device.', + device=self._device) else: raise SaneUnknownError( - 'sane_control_option returned an invalid status: %i.' % status) + 'sane_control_option returned an invalid status: %i.' % status, + device=self._device) if self._type == SANE_TYPE_STRING.value: option_value = option_value.value else: option_value = option_value.contents.value if self._log: self._log.debug( 'Option %s queried, its current value is %s.', self._name, option_value) return option_value def __set_value(self, value): """ Set the current value of this option. """ handle = self._device._get_handle() c_value = None # Type checking if self._type == SANE_TYPE_BOOL.value: if type(value) is not BooleanType: raise AssertionError( 'option set with %s, expected BooleanType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_INT.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise AssertionError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_FIXED.value: # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6 if type(value) is not IntType: raise AssertionError( 'option set with %s, expected IntType' % type(value)) c_value = pointer(c_int(value)) elif self._type == SANE_TYPE_STRING.value: if type(value) is not StringType: raise AssertionError( 'optionset with %s, expected StringType' % type(value)) if len(value) + 1 > self._size: raise AssertionError( 'value for option is longer than max string size') c_value = c_char_p(value) elif self._type == SANE_TYPE_BUTTON.value: raise TypeError('SANE_TYPE_BUTTON has no value.') elif self._type == SANE_TYPE_GROUP.value: raise TypeError('SANE_TYPE_GROUP has no value.') else: raise TypeError('Option is of unknown type.') # Constraint checking if self._constraint_type == SANE_CONSTRAINT_NONE.value: pass elif self._constraint_type == SANE_CONSTRAINT_RANGE.value: if value < self._constraint[0]: raise AssertionError('value for option is less than min.') if value > self._constraint[1]: raise AssertionError('value for option is greater than max.') if value % self._constraint[2] != 0: raise AssertionError( 'value for option is not divisible by quant.') elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value: if value not in self._constraint: raise AssertionError( 'value for option not in list of valid values.') elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value: if value not in self._constraint: raise AssertionError( 'value for option not in list of valid strings.') info_flags = SANE_Int() status = sane_control_option( handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags)) if status == SANE_STATUS_GOOD.value: pass elif status == SANE_STATUS_UNSUPPORTED.value: # Constraint checking ensures this should never happen raise AssertionError( 'sane_control_option reported that a value was outside the option\'s constraint.') elif status == SANE_STATUS_INVAL.value: raise AssertionError( 'sane_control_option reported that the value to be set was invalid, despite checks.') elif status == SANE_STATUS_IO_ERROR.value: raise SaneIOError( - 'sane_control_option reported a communications error.') + 'sane_control_option reported a communications error.', + device=self._device) elif status == SANE_STATUS_NO_MEM.value: raise SaneOutOfMemoryError( - 'sane_control_option ran out of memory.') + 'sane_control_option ran out of memory.', + device=self._device) elif status == SANE_STATUS_ACCESS_DENIED.value: raise SaneAccessDeniedError( - 'sane_control_option requires greater access to open the device.') + 'sane_control_option requires greater access to open the device.', + device=self._device) else: raise SaneUnknownError( - 'sane_control_option returned an invalid status: %i .' % status) + 'sane_control_option returned an invalid status: %i .' % status, + device=self._device) if self._log: self._log.debug('Option %s set to value %s.', self._name, value) # See SANE API 4.3.7 if info_flags.value & SANE_INFO_RELOAD_OPTIONS: raise SaneReloadOptionsError() value = property(__get_value, __set_value) class ScanInfo(object): """ Contains the parameters and progress of a scan in progress. """ _width = 0 _height = 0 _depth = 0 _total_bytes = 0 def __init__(self, sane_parameters): """ Initialize the ScanInfo object from the sane_parameters. """ self._width = sane_parameters.pixels_per_line self._height = sane_parameters.lines self._depth = sane_parameters.depth self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines # Read only properties def __get_width(self): """Get the width of the current scan, in pixels.""" return self._width width = property(__get_width) def __get_height(self): """Get the height of the current scan, in pixels.""" return self._height height = property(__get_height) def __get_depth(self): """Get the depth of the current scan, in bits.""" return self._depth depth = property(__get_depth) def __get_total_bytes(self): """Get the total number of bytes comprising this scan.""" return self._total_bytes total_bytes = property(__get_total_bytes) if __name__ == '__main__': def progress_callback(sane_info, bytes_read): #print float(bytes_read) / sane_info.total_bytes pass import logging log_format = FORMAT = "%(message)s" logging.basicConfig(level=logging.DEBUG, format=log_format) sane = SaneMe(logging.getLogger()) devices = sane.get_device_list() for dev in devices: print dev.name devices[0].open() print devices[0].options.keys() try: devices[0].options['mode'].value = 'Gray' except SaneReloadOptionsError: pass try: devices[0].options['resolution'].value = 75 except SaneReloadOptionsError: pass try: devices[0].options['preview'].value = False except SaneReloadOptionsError: pass devices[0].scan(progress_callback).save('out.bmp') devices[0].close() \ No newline at end of file