From da7f8a556c122a31daa11f434d67c8bb96cbd5ec Mon Sep 17 00:00:00 2001 From: Roland Wolf Date: Thu, 29 Jul 2010 13:51:27 +0200 Subject: moving over work from 28b49e42f5bddec2d62e957f158cb848da134db8 --- doc/src/tutorials/modelview.qdoc | 661 +++++++++++---------- .../tutorials/modelview/1_readonly/1_readonly.pro | 13 +- examples/tutorials/modelview/1_readonly/main.cpp | 9 +- .../tutorials/modelview/1_readonly/modelview.cpp | 54 -- .../tutorials/modelview/1_readonly/modelview.h | 61 -- .../tutorials/modelview/1_readonly/mymodel.cpp | 0 examples/tutorials/modelview/1_readonly/mymodel.h | 0 .../modelview/2_formatting/2_formatting.pro | 12 +- examples/tutorials/modelview/2_formatting/main.cpp | 12 +- .../tutorials/modelview/2_formatting/modelview.cpp | 52 -- .../tutorials/modelview/2_formatting/modelview.h | 57 -- .../tutorials/modelview/2_formatting/mymodel.cpp | 6 +- .../tutorials/modelview/2_formatting/mymodel.h | 0 .../modelview/3_changingmodel/3_changingmodel.pro | 12 +- .../tutorials/modelview/3_changingmodel/main.cpp | 0 .../modelview/3_changingmodel/modelview.cpp | 52 -- .../modelview/3_changingmodel/modelview.h | 57 -- .../modelview/3_changingmodel/mymodel.cpp | 0 .../tutorials/modelview/3_changingmodel/mymodel.h | 2 +- .../tutorials/modelview/4_headers/4_headers.pro | 14 +- examples/tutorials/modelview/4_headers/main.cpp | 0 .../tutorials/modelview/4_headers/modelview.cpp | 54 -- examples/tutorials/modelview/4_headers/modelview.h | 58 -- examples/tutorials/modelview/4_headers/mymodel.cpp | 0 examples/tutorials/modelview/4_headers/mymodel.h | 0 examples/tutorials/modelview/5_edit/5_edit.pro | 12 +- examples/tutorials/modelview/5_edit/main.cpp | 4 +- examples/tutorials/modelview/5_edit/modelview.cpp | 60 -- examples/tutorials/modelview/5_edit/modelview.h | 59 -- examples/tutorials/modelview/5_edit/mymodel.cpp | 40 +- examples/tutorials/modelview/5_edit/mymodel.h | 9 +- .../tutorials/modelview/6_treeview/6_treeview.pro | 12 +- examples/tutorials/modelview/6_treeview/main.cpp | 4 +- .../tutorials/modelview/6_treeview/modelview.cpp | 82 --- .../tutorials/modelview/6_treeview/modelview.h | 65 -- .../modelview/7_selections/7_selections.pro | 12 +- examples/tutorials/modelview/7_selections/main.cpp | 4 +- .../tutorials/modelview/7_selections/modelview.cpp | 107 ---- .../tutorials/modelview/7_selections/modelview.h | 64 -- examples/tutorials/modelview/modelview.pro | 10 +- 40 files changed, 485 insertions(+), 1245 deletions(-) mode change 100755 => 100644 doc/src/tutorials/modelview.qdoc mode change 100644 => 100755 examples/tutorials/modelview/1_readonly/1_readonly.pro mode change 100644 => 100755 examples/tutorials/modelview/1_readonly/main.cpp delete mode 100644 examples/tutorials/modelview/1_readonly/modelview.cpp delete mode 100644 examples/tutorials/modelview/1_readonly/modelview.h mode change 100644 => 100755 examples/tutorials/modelview/1_readonly/mymodel.cpp mode change 100644 => 100755 examples/tutorials/modelview/1_readonly/mymodel.h mode change 100644 => 100755 examples/tutorials/modelview/2_formatting/2_formatting.pro mode change 100644 => 100755 examples/tutorials/modelview/2_formatting/main.cpp delete mode 100644 examples/tutorials/modelview/2_formatting/modelview.cpp delete mode 100644 examples/tutorials/modelview/2_formatting/modelview.h mode change 100644 => 100755 examples/tutorials/modelview/2_formatting/mymodel.cpp mode change 100644 => 100755 examples/tutorials/modelview/2_formatting/mymodel.h mode change 100644 => 100755 examples/tutorials/modelview/3_changingmodel/3_changingmodel.pro mode change 100644 => 100755 examples/tutorials/modelview/3_changingmodel/main.cpp delete mode 100644 examples/tutorials/modelview/3_changingmodel/modelview.cpp delete mode 100644 examples/tutorials/modelview/3_changingmodel/modelview.h mode change 100644 => 100755 examples/tutorials/modelview/3_changingmodel/mymodel.cpp mode change 100644 => 100755 examples/tutorials/modelview/3_changingmodel/mymodel.h mode change 100644 => 100755 examples/tutorials/modelview/4_headers/4_headers.pro mode change 100644 => 100755 examples/tutorials/modelview/4_headers/main.cpp delete mode 100644 examples/tutorials/modelview/4_headers/modelview.cpp delete mode 100644 examples/tutorials/modelview/4_headers/modelview.h mode change 100644 => 100755 examples/tutorials/modelview/4_headers/mymodel.cpp mode change 100644 => 100755 examples/tutorials/modelview/4_headers/mymodel.h mode change 100644 => 100755 examples/tutorials/modelview/5_edit/5_edit.pro mode change 100644 => 100755 examples/tutorials/modelview/5_edit/main.cpp delete mode 100644 examples/tutorials/modelview/5_edit/modelview.cpp delete mode 100644 examples/tutorials/modelview/5_edit/modelview.h mode change 100644 => 100755 examples/tutorials/modelview/5_edit/mymodel.cpp mode change 100644 => 100755 examples/tutorials/modelview/5_edit/mymodel.h mode change 100644 => 100755 examples/tutorials/modelview/6_treeview/6_treeview.pro mode change 100644 => 100755 examples/tutorials/modelview/6_treeview/main.cpp delete mode 100644 examples/tutorials/modelview/6_treeview/modelview.cpp delete mode 100644 examples/tutorials/modelview/6_treeview/modelview.h mode change 100644 => 100755 examples/tutorials/modelview/7_selections/7_selections.pro mode change 100644 => 100755 examples/tutorials/modelview/7_selections/main.cpp delete mode 100644 examples/tutorials/modelview/7_selections/modelview.cpp delete mode 100644 examples/tutorials/modelview/7_selections/modelview.h mode change 100644 => 100755 examples/tutorials/modelview/modelview.pro diff --git a/doc/src/tutorials/modelview.qdoc b/doc/src/tutorials/modelview.qdoc old mode 100755 new mode 100644 index 98096a0..f771726 --- a/doc/src/tutorials/modelview.qdoc +++ b/doc/src/tutorials/modelview.qdoc @@ -34,46 +34,118 @@ \title Model/View Contents \brief An introduction to ModelView programming - This tutorial gives an introduction to ModelView programming using the Qt - cross-platform framework. + Every UI developer should know about ModelView programming and the goal of this tutorial is to provide you with an easily understandable introduction to this topic. - \image treeview.png +\raw HTML +
+\endraw +\raw HTML + + + + + + + +
+\endraw + +Table, list and tree widgets are components frequently used in GUIs. There are 2 different ways how these widgets can access their data. The traditional way involves widgets which include internal containers for storing data. This approach is very intuitive, however, in many non-trivial applications, it leads to data synchronization issues. The second approach is modelview programming, in which widgets do not maintain internal data containers. They access external data through a standardized interface and therefore avoid data dupplication. This may seem complicated at first, but once you take a closer look, it is not only easy to grasp, but the many benefits of modelview programming also become clearer. + +\raw HTML + +\endraw + +\raw HTML + + +
+\endraw + +\raw HTML +

Contents:

+\endraw + + \list 1 + \o \l{modelview-part1.html}{Introduction} + \o \l{modelview-part2.html}{Developing a Simple Model/View Application} + \o \l{modelview-part3.html}{Intermediate Topics} + \o \l{modelview-part4.html}{Good Sources of Additional Information} + \endlist + +\raw HTML +
+\endraw + + +\raw HTML +
+\endraw + \raw HTML +

+ \endraw \omit It doesn't cover everything; the emphasis is on teaching the programming philosophy of Model/View programming, and Qt's features are introduced as needed. Some commonly used features are never used in this tutorial. \endomit - In the process, we will learn about some basic technologies provided by Qt, - such as: + In the process, we will learn about some basic technologies provided by Qt, such as: \list \o The difference between standard and model/view widgets \o Adapters betweeen forms and models \o Developing a simple model/view application + \o Predefined models \o Intermediate topics such as: \list \o Tree views \o Selection - \o Predefined models \o Delegates \o Debugging with model test \endlist \endlist + - If you are completely new to Qt, please read \l{How to Learn Qt} if you - have not already done so. + \raw HTML +
+ \endraw + You will also learn whether your new application can be written easier with ModelView programming or if classic widgets will work just as well. + \raw HTML +
+ \endraw + This tutorial includes example code for you to edit and integrate into your project. The tutorial's source code is located in Qt's \c examples/tutorials/modelview directory. - The tutorial's source code is located in Qt's \c examples/tutorials/modelview - directory. + \raw HTML +
+ \endraw + For more detailed information you may also want to look at the \l {model-view-programming.html}{reference documentation} - \list 1 - \o \l{modelview-part1.html}{Introduction} - \o \l{modelview-part2.html}{Developing a Simple Model/View Application} - \o \l{modelview-part3.html}{Intermediate Topics} - \o \l{modelview-part4.html}{Good Sources of Additional Information} - \endlist + +\raw HTML +
+\endraw + + \raw HTML +

+ \endraw + + + + \image treeview.png + + +\raw HTML +
+\endraw + + + + \raw HTML +
+ \endraw + If you are completely new to Qt, please read \l{How to Learn Qt} if you have not already done so. */ @@ -84,13 +156,12 @@ \previouspage {modelview-index.html}{Model/View Contents} \nextpage {modelview-part2.html}{Developing a Simple Model/View Application} \title An Introduction to Model/View Programming - + \raw HTML +
+ \endraw \section1 1. Introduction - Model/View is a technology used to separate data from views in widgets that - handle data sets. Standard widgets are not designed for separating data - from views and this is why Qt 4 has two different types of widgets. Both - types of widgets look the same, but they interact with data differently. + Model/View is a technology used to separate data from views in widgets that handle data sets. Standard widgets are not designed for separating data from views and this is why Qt 4 has two different types of widgets. Both types of widgets look the same, but they interact with data differently. \table \row @@ -103,43 +174,22 @@ \section2 1.1 Standard Widgets - Let's have a closer look at a standard table widget. A table widget is a 2D - array of the data elements that the user can change. The table widget can - be integrated into a program flow by reading and writing the data elements - that the table widget provides. This method is very intuitive and useful in - many applications. + Let's have a closer look at a standard table widget. A table widget is a 2D array of the data elements that the user can change. The table widget can be integrated into a program flow by reading and writing the data elements that the table widget provides. This method is very intuitive and useful in many applications. - Displaying and editing a database table with a standard table widget can be - problematic. Two copies of the data have to be coordinated: one outside the - widget; one inside the widget. The developer needs to know where up-to-date - data is so the both copies contain the most recent data. The tight coupling - of presentation and data makes it harder to write unit tests. + Displaying and editing a database table with a standard table widget can be problematic. Two copies of the data have to be coordinated: one outside the widget; one inside the widget. The developer is responsible for synchronizing both versions. The tight coupling of presentation and data makes it harder to write unit tests. \section2 1.2 Model/View to the Rescue - Model/view stepped up to provide a solution that uses a more versatile - architecture. Model/view eliminates the data consistency problems that may - occur with standard widgets. Model/view also makes it easier to use more - than one view of the same data because one model can be passed on to many - views. The most important difference is that model/view widgets do not - store data behind the table cells. In fact, they operate directly from your - data. Since view classes do not know your data's structure, you need to - provide a wrapper to make your data conform to the QAbstractItemModel - interface. A view uses this interface to read from and write to your data - and any class that implements QAbstractItemModel is a model. Once the view - receives a pointer to a model, it will read and display its content and be - its editor. + Model/view stepped up to provide a solution that uses a more versatile architecture. Model/view eliminates the data consistency problems that may occur with standard widgets. Model/view also makes it easier to use more than one view of the same data because one model can be passed on to many views. The most important difference is that model/view widgets do not store data behind the table cells. In fact, they operate directly from your data. Since view classes do not know your data's structure, you need to provide a wrapper to make your data conform to the QAbstractItemModel interface. A view uses this interface to read from and write to your data. Any instance of a class that implements QAbstractItemModel is said to be a model. Once the view receives a pointer to a model, it will read and display its content and be its editor. \section2 1.3 Overview of the Model/View Widgets - Here is an overview of the model/view widgets and their corresponding - standard widgets. + Here is an overview of the model/view widgets and their corresponding standard widgets. \table \header \o Widget - \o Standard Widget (a convenience class with data in - the widget) + \o Standard Widget (an item based convenience class) \o Model/View View Class (for use with external data) \row \o \inlineimage listview.png @@ -167,23 +217,37 @@ Having adapters between forms and models can come in handy. - We often prefer editing data stored in tables (e.g. in database tables) in - forms rather than in tables. There is no direct model/view counterpart for - separating data and views for widgets that operate on one value instead of - a dataset, so we need an adapter in order to connect the form to the source - of data. + We can edit data stored in tables directly from within the table itself, but it's much more comfortable to edit data in text fields. There is no direct model/view counterpart that separates data and views for widgets that operate on one value (QLineEdit, QCheckBox ...) instead of a dataset, so we need an adapter in order to connect the form to the source of data. - \l QDataWidgetMapper is a great solution because it maps form widgets to a - table row and it makes it very easy to build forms for database tables. + \l QDataWidgetMapper is a great solution because it maps form widgets to a table row and makes it very easy to build forms for database tables. \image widgetmapper.png - - Another example of an adapter is QCompleter. Qt has QCompleter for - providing auto-completions in Qt widgets such as QComboBox and, as shown - below, QLineEdit. QCompleter uses a model as its data source, so QCompleter, - in itself, is a very handy adapter. + + Another example of an adapter is \l QCompleter. Qt has \l QCompleter for providing auto-completions in Qt widgets such as \l QComboBox and, as shown below, \l QLineEdit. \l QCompleter uses a model as its data source. \image qcompleter.png + + +\raw HTML +
+
+
+
+
+\endraw + +\raw HTML +

+previous page +

+\endraw + +\raw HTML +

+next page +

+\endraw + */ /*! @@ -198,165 +262,143 @@ \previouspage {modelview-part1.html}{Introduction} \nextpage {modelview-part3.html}{Intermediate Topics} \title Model/View Chapter 2 - A Simple Model/View Application - + \raw HTML +
+ \endraw \section1 2. A Simple Model/View Application + If you want to develop a model/view application, where should you start? We recommend starting with a simple example and extending it step-by-step. This makes understanding the architecture a lot easier. Trying to understand the model/view architecture in detail before invoking the IDE has proven to be less convenient for many developers. It is substantially easier to start with a simple model/view application that has demo data. Give it a try! Simply replace the data in the examples below with your own. - If you want to develop a model/view application, where should you start? We - recommend starting with a simple example and extending it step-by-step. - This makes understanding the architecture a lot easier. Trying to - understand the model/view architecture in detail before invoking the IDE - has proven to be less convenient for many developers. It is substantially - easier to start with a simple model/view application that has demo data. - Give it a try! Simply replace the data in the examples below with your own. - - Below are 7 very simple and independent applications that show different - sides of model/view programming. The source code can be found inside the - \c{examples/tutorials/modelview} directory. + Below are 7 very simple and independent applications that show different sides of model/view programming. The source code can be found inside the \c{examples/tutorials/modelview} directory. \section2 2.1 A Read Only Table - - We start with an application that uses a QTableView to show data. We will - add editing capabilities later. - + We start with an application that uses a QTableView to show data. We will add editing capabilities later. + \raw HTML +
+ \endraw + (file source: examples/tutorials/modelview/1_readonly/main.cpp) \snippet examples/tutorials/modelview/1_readonly/main.cpp Quoting ModelView Tutorial We have the usual \l {modelview-part2-main-cpp.html}{main()} function: - \snippet examples/tutorials/modelview/1_readonly/modelview.h Quoting ModelView Tutorial - - The application is a \l QMainWindow that holds a \l QTableView. - - \snippet examples/tutorials/modelview/1_readonly/modelview.cpp Quoting ModelView Tutorial - - Here is the interesting part: We use - \l{QTableView::setModel()}{tableView->setModel(new MyModel(this));} to - instantiate the Model and pass its pointer to \l {QTableView}{tableView()}. - \l{QTableView}{tableView} will invoke the methods of the pointer it has - received to find out two things: + \raw HTML +
+ \endraw + + Here is the interesting part: We create an instance of MyModel and use \l{QTableView::setModel()}{tableView.setModel( &myModel );} to pass a pointer of it to to \l {QTableView}{tableView}. \l{QTableView}{tableView} will invoke the methods of the pointer it has received to find out two things: \list \o How many rows and columns should be displayed \o What content should be printed into each cell. \endlist - The model needs some code to respond to this. + The model needs some code to respond to this. - We have a table data set, so let's start with QAbstractTableModel since it - is easier to use. + We have a table data set, so let's start with QAbstractTableModel since it is easier to use than the more general QAbstractItemModel. + + \raw HTML +
+ \endraw + (file source: examples/tutorials/modelview/1_readonly/mymodel.h) \snippet examples/tutorials/modelview/1_readonly/mymodel.h Quoting ModelView Tutorial QAbstractTableModel requires the implementation of three abstract methods. + \raw HTML +
+ \endraw + (file source: examples/tutorials/modelview/1_readonly/mymodel.cpp) \snippet examples/tutorials/modelview/1_readonly/mymodel.cpp Quoting ModelView Tutorial - The number of rows and columns is set by - \l{QAbstractItemModel::rowCount()}{MyModel::rowCount()} and - \l{QAbstractItemModel::columnCount()}{MyModel::columnCount()}. - When the view has to know what the cell's text is, it calls the method. - Row and column information is specified with parameter \c index and the - role is set to \l{Qt::ItemDataRole}{Qt::DisplayRole}. Other roles are - covered in the next section. In our example, the data that should be - displayed is generated. In a real application, \c MyModel would have a - member called \c MyData, which serves as the target for all reading and - writing operations. - - This small example demonstrates the passive nature of a model. The model - does not know when it will be used or which data is needed. It simply - provides data each time the view requests it. - - What happens when the model 's data needs to be changed? How does the view - know when data changes and needs to be read again? The model has to emit a - signal that indicates what range of cells has changed. This will be - demonstrated in section 2.3. + The number of rows and columns is provided by \l{QAbstractItemModel::rowCount()}{MyModel::rowCount()} and \l{QAbstractItemModel::columnCount()}{MyModel::columnCount()}. When the view has to know what the cell's text is, it calls the method \l{QAbstractItemModel::data()}{MyModel::data()}. Row and column information is specified with parameter \c index and the role is set to \l{Qt::ItemDataRole}{Qt::DisplayRole}. Other roles are covered in the next section. In our example, the data that should be displayed is generated. In a real application, \c MyModel would have a member called \c MyData, which serves as the target for all reading and writing operations. + + This small example demonstrates the passive nature of a model. The model does not know when it will be used or which data is needed. It simply provides data each time the view requests it. + + What happens when the model 's data needs to be changed? How does the view realize that data has changed and needs to be read again? The model has to emit a signal that indicates what range of cells has changed. This will be demonstrated in section 2.3. \section2 2.2 Extending the Read Only Example with Roles - In addition to controlling what text the view displays, the model also - controls the text's appearance. When we slightly change the model, we get - the following result: \image readonlytable_role.png + In addition to controlling what text the view displays, the model also controls the text's appearance. When we slightly change the model, we get the following result: \image readonlytable_role.png + + In fact, nothing except for the \l{QAbstractItemModel::}{data()} method needs to be changed to set fonts, background colour, alignment and a checkbox. Below is the \l{QAbstractItemModel::data()}{data()} method that produces the result shown above. The difference is that this time we use parameter int role to return different pieces of information depending on its value. - In fact, nothing except for the \l{QAbstractItemModel::}{data()} - method needs to be changed to set fonts, background colour, alignment and a - checkbox. - Here is the \l{QAbstractItemModel::data()}{data()} method that produces the - result shown above: + \raw HTML +
+ \endraw + (file source: examples/tutorials/modelview/2_formatting/mymodel.cpp) \snippet examples/tutorials/modelview/2_formatting/mymodel.cpp Quoting ModelView Tutorial - Each formatting property will be requested from the model with a separate - call to the \l{QAbstractItemModel::data()}{data()} method. The \c role - parameter is used to let the model know which property is being requested: + Each formatting property will be requested from the model with a separate call to the \l{QAbstractItemModel::data()}{data()} method. The \c role parameter is used to let the model know which property is being requested: \table \header - \o Role (enum Qt::ItemDataRole ) + \o \l{Qt::ItemDataRole}{enum Qt::ItemDataRole} \o Meaning \o Type \row - \o \l{Qt::ItemDataRole}{Qt::DisplayRole} + \o \l{Qt::ItemDataRole}{}Qt::DisplayRole \o text \o QString \row - \o Qt::FontRole + \o \l{Qt::ItemDataRole}{Qt::FontRole} \o font \o QFont \row - \o Qt::BackgroundRole + \o \l{Qt::ItemDataRole}{BackgroundRole} \o brush for the background of the cell \o QBrush \row - \o Qt::TextAlignmentRole + \o \l{Qt::ItemDataRole}{Qt::TextAlignmentRole} \o text alignment - \o enum Qt::AlignmentFlag - \row - \o {1, 3} Qt::CheckStateRole - \o {1, 3} suppresses checkboxes with \l{QVariant}{QVariant()}, - sets checkboxes with Qt::Checked or Qt::Unchecked - \o {1, 3} \l{Qt::ItemDataRole}{enum Qt::ItemDataRole} + \o \l{Qt::AlignmentFlag-enum}{enum Qt::AlignmentFlag} + \row + \o {1, 3} \l{Qt::ItemDataRole}{Qt::CheckStateRole} + \o {1, 3} suppresses checkboxes with \l{QVariant}{QVariant()}, + + sets checkboxes with \l{Qt::CheckState-enum}{Qt::Checked} + + or \l{Qt::CheckState-enum}{Qt::Unchecked} + \o {1, 3} \l{Qt::ItemDataRole}{enum Qt::ItemDataRole} \endtable - Refer to the Qt namespace documentation to learn more about the - Qt::ItemDataRole enum's capabilities. - - Now we need to determine how using a seperated model impacts the - application's performance, so let's trace how often the view calls the - \l{QAbstractItemModel::}{data()} method. In order to track how often - the view calls the model, we have put a debug statement in the - \l{QAbstractItemModel::}{data()} method, which logs onto stdio. In - our small example, \l{QAbstractItemModel::}{data()} will be called 42 - times. - Each time you hover the cursor over the field, - \l{QAbstractItemModel::}{data()} will be called again \mdash 7 times for - each cell. That's why it is important to make sure that your data is - available when \l{QAbstractItemModel::}{data()} is invoked and expensive - lookup operations are cached. + Refer to the Qt namespace documentation to learn more about the \l{Qt::ItemDataRole}{Qt::ItemDataRole} enum's capabilities. + + Now we need to determine how using a separated model impacts the application's performance, so let's trace how often the view calls the \l{QAbstractItemModel::}{data()} method. In order to track how often the view calls the model, we have put a debug statement in the \l{QAbstractItemModel::}{data()} method, which logs onto stdio. In our small example, \l{QAbstractItemModel::}{data()} will be called 42 times. + Each time you hover the cursor over the field, \l{QAbstractItemModel::}{data()} will be called again \mdash 7 times for each cell. That's why it is important to make sure that your data is available when \l{QAbstractItemModel::}{data()} is invoked and expensive lookup operations are cached. \section2 2.3 A Clock inside a Table Cell \image clock.png - We still have a read only table, but this time the content changes every - second because we are showing the current time. + We still have a read only table, but this time the content changes every second because we are showing the current time. + + \raw HTML +
+ \endraw + (file source: examples/tutorials/modelview/3_changingmodel/mymodel.cpp) \snippet examples/tutorials/modelview/3_changingmodel/mymodel.cpp quoting mymodel_QVariant - Something is missing to make the clock tick. We need to tell the view every - second that the time has changed and that it needs to be read again. We do - this with a timer. In the constructor, we set its interval to 1 second and - connect its timeout signal. + Something is missing to make the clock tick. We need to tell the view every second that the time has changed and that it needs to be read again. We do this with a timer. In the constructor, we set its interval to 1 second and connect its timeout signal. + + \raw HTML +
+ \endraw + (file source: examples/tutorials/modelview/3_changingmodel/mymodel.cpp) \snippet examples/tutorials/modelview/3_changingmodel/mymodel.cpp quoting mymodel_a Here is the corresponding slot: + + \raw HTML +
+ \endraw + (file source: examples/tutorials/modelview/3_changingmodel/mymodel.cpp) \snippet examples/tutorials/modelview/3_changingmodel/mymodel.cpp quoting mymodel_b - We ask the view to read the data in the top left cell again by emitting the - \l{QAbstractItemModel::}{dataChanged()} signal. Note that we did not - explicitly connect the \l{QAbstractItemModel::}{dataChanged()} signal to - the view. This happened automatically when we called - \l{QTableView::}{setModel()}. + We ask the view to read the data in the top left cell again by emitting the \l{QAbstractItemModel::}{dataChanged()} signal. Note that we did not explicitly connect the \l{QAbstractItemModel::}{dataChanged()} signal to the view. This happened automatically when we called \l{QTableView::}{setModel()}. \section2 2.4 Setting up Headers for Columns and Rows @@ -366,52 +408,75 @@ The header content, however, is set via the model, so we reimplement the \l{QAbstractItemModel::headerData()}{headerData()} method: - \snippet examples/tutorials/modelview/4_headers/mymodel.cpp quoting mymodel_c + \raw HTML +
+ \endraw + (file source: examples/tutorials/modelview/4_headers/mymodel.cpp) + \snippet examples/tutorials/modelview/4_headers/mymodel.cpp quoting mymodel_c + Note that method \l{QAbstractItemModel::headerData()}{headerData()} also has a parameter role which has the same meaning as in \l{QAbstractItemModel::data()}{MyModel::data()}. \section2 2.5 The Minimal Editing Example - In this example, we are going to build an application that automatically - populates a window title with content by repeating values entered into - table cells. + In this example, we are going to build an application that automatically populates a window title with content by repeating values entered into table cells. To be able to access the window title easily we put the QTableView in a QMainWindow. - The model decides whether editing capabilities are available . We only have - to modify the model in order for the available editing capabilities to be - enabled. This is done by reimplementing the following virtual methods: - \l{QAbstractItemModel::}{setData()} and \l{QAbstractItemModel::}{flags()}. + The model decides whether editing capabilities are available . We only have to modify the model in order for the available editing capabilities to be enabled. This is done by reimplementing the following virtual methods: \l{QAbstractItemModel::}{setData()} and \l{QAbstractItemModel::}{flags()}. - \snippet examples/tutorials/modelview/5_edit/mymodel.h Quoting ModelView Tutorial - We use \c QStringList m_gridData to store our data. This makes - \c m_gridData the core of MyModel. The rest of \c MyModel acts like a - wrapper and adapts \c m_gridData to the QAbstractItemModel interface. We - have also introduced the \c editCompleted() signal, - which makes it possible to transfer the modified text to the window title. - \snippet examples/tutorials/modelview/5_edit/mymodel.cpp quoting mymodel_d + \raw HTML +
+ \endraw + (file source: examples/tutorials/modelview/5_edit/mymodel.h) + \snippet examples/tutorials/modelview/5_edit/mymodel.h Quoting ModelView Tutorial - In the constructor, we fill \c QStringList gridData with 6 items (one item - for every field in the table): + We use \c the two-dimensional array QString m_gridData to store our data. This makes \c m_gridData the core of MyModel. The rest of \c MyModel acts like a wrapper and adapts \c m_gridData to the QAbstractItemModel interface. We have also introduced the \c editCompleted() signal, which makes it possible to transfer the modified text to the window title. + \raw HTML +
+ \endraw + (file source: examples/tutorials/modelview/5_edit/mymodel.cpp) \snippet examples/tutorials/modelview/5_edit/mymodel.cpp quoting mymodel_e - \l{QAbstractItemModel::setData()}{setData()} will be called each time the - user edits a cell. The \c index parameter tells us which field has been - edited and \c value provides the result of the editing process. The role - will always be set to \c Qt::EditRole because our cells only contain text. - If a checkbox were present and user permissions are set to allow the - checkbox to be selected, calls would also be made with the role set to - \c Qt::CheckStateRole. + \l{QAbstractItemModel::setData()}{setData()} will be called each time the user edits a cell. The \c index parameter tells us which field has been edited and \c value provides the result of the editing process. The role will always be set to \c Qt::EditRole because our cells only contain text. If a checkbox were present and user permissions are set to allow the checkbox to be selected, calls would also be made with the role set to \c Qt::CheckStateRole. + + + \raw HTML +
+ \endraw + (file source: examples/tutorials/modelview/5_edit/mymodel.cpp) \snippet examples/tutorials/modelview/5_edit/mymodel.cpp quoting mymodel_f - Various properties of a cell can be adjusted with - \l{QAbstractItemModel::flags()}{flags()}. Returning - \c Qt::ItemIsEditable | \c Qt::ItemIsEnabled is enough to show an editor - that a cell has been selected. If editing one cell modifies more data than - the data in that particular cell, the model must emit a - \l{QAbstractItemModel::}{dataChanged()} signal in order for the data that - has been changed to be read. + Various properties of a cell can be adjusted with \l{QAbstractItemModel::flags()}{flags()}. + + \raw HTML +

Returning Qt::ItemIsEditable | Qt::ItemIsEnabled is enough to show an editor that a cell has been selected.

+ \endraw + If editing one cell modifies more data than the data in that particular cell, the model must emit a \l{QAbstractItemModel::dataChanged()}{dataChanged()} signal in order for the data that has been changed to be read. + + + +\raw HTML +
+
+
+
+
+\endraw + +\raw HTML +

+previous page +

+\endraw + +\raw HTML +

+next page +

+\endraw + */ /*! @@ -420,21 +485,20 @@ \previouspage {modelview-part2.html}{Developing a Simple Model/View Application} \nextpage {modelview-part4.html}{Good Sources of Additional Information} \title Model/View Chapter 3 - Intermediate Topics - +\raw HTML +
+\endraw \section1 3. Intermediate Topics - +\raw HTML +
+\endraw \section2 3.1 TreeView - You can convert the example above into an application with a tree view. - Simply replace QTableView with QTreeView, which results in a read/write - tree. No changes have to be made to the model. The tree won't have any - hierarchies because there aren't any hierarchies in the model itself. + You can convert the example above into an application with a tree view. Simply replace QTableView with QTreeView, which results in a read/write tree. No changes have to be made to the model. The tree won't have any hierarchies because there aren't any hierarchies in the model itself. \image dummy_tree.png - QListView, QTableView and QTreeView all use a model abstraction, which is a - merged list, table and tree. This makes it possible to use several different - types of view classes from the same model. + QListView, QTableView and QTreeView all use a model abstraction, which is a merged list, table and tree. This makes it possible to use several different types of view classes from the same model. \image list_table_tree.png @@ -442,21 +506,17 @@ \image example_model.png - We want to present a real tree. We have wrapped our data in the examples - above in order to make a model. This time we use QStandardItemModel, which - is a container for hierarchical data that also implements - QAbstractItemModel. To show a tree, QStandardItemModel must be populated - with \l{QStandardItem}{QStandardItems}, which are able to hold all the - standard properties of items like text, fonts, checkboxes or brushes. - \image tree_2_with_algorithm.png + We want to present a real tree. We have wrapped our data in the examples above in order to make a model. This time we use QStandardItemModel, which is a container for hierarchical data that also implements QAbstractItemModel. To show a tree, QStandardItemModel must be populated with \l{QStandardItem}{QStandardItems}, which are able to hold all the standard properties of items like text, fonts, checkboxes or brushes. \image tree_2_with_algorithm.png + + + \raw HTML +
+ \endraw + (file source: examples/tutorials/modelview/6_treeview/mainwindow.cpp) - \snippet examples/tutorials/modelview/6_treeview/modelview.cpp Quoting ModelView Tutorial + \snippet examples/tutorials/modelview/6_treeview/mainwindow.cpp Quoting ModelView Tutorial - We simply instantiate a QStandardItemModel and add a couple of - \l{QStandardItem}{QStandardItems} to the constructor. We can then make a - hierarchical data structure because a QStandardItem can hold other - \l{QStandardItem}{QStandardItems}. Nodes are collapsed and expanded within - the view. + We simply instantiate a QStandardItemModel and add a couple of \l{QStandardItem}{QStandardItems} to the constructor. We can then make a hierarchical data structure because a QStandardItem can hold other \l{QStandardItem}{QStandardItems}. Nodes are collapsed and expanded within the view. \section2 3.2 Working with Selections @@ -466,38 +526,29 @@ So let's create a couple of items: - \snippet examples/tutorials/modelview/7_selections/modelview.cpp quoting modelview_a - Views manage selections within a separate selection model, which can be - retrieved with the \l{QAbstractItemView::}{selectionModel()} - method. We retrieve the selection Model in order to connect a slot to its - \l{QAbstractItemView::}{selectionChanged()} signal. + \raw HTML +
+

(file source: examples/tutorials/modelview/7_selections/mainwindow.cpp)

+ \endraw + \snippet examples/tutorials/modelview/7_selections/mainwindow.cpp quoting modelview_a + + Views manage selections within a separate selection model, which can be retrieved with the \l{QAbstractItemView::}{selectionModel()} method. We retrieve the selection Model in order to connect a slot to its \l{QAbstractItemView::}{selectionChanged()} signal. + - \snippet examples/tutorials/modelview/7_selections/modelview.cpp quoting modelview_b + \raw HTML +
+

(file source: examples/tutorials/modelview/7_selections/mainwindow.cpp)

+ \endraw + \snippet examples/tutorials/modelview/7_selections/mainwindow.cpp quoting modelview_b - We get the model index that corresponds to the selection by calling - \l{QItemSelectionModel::currentIndex()}{treeView->selectionModel()->currentIndex()} - and we get the the field's string by using the model index. Then we just - calculate the item's \c hierarchyLevel. Top level items do not have - parents and the \l{QAbstractItemModel::}{parent()} method will return a - default constructed \l{QModelIndex}{QModelIndex()}. This is why we use the - \l{QAbstractItemModel::}{parent()} method to iterate to the top level while - counting the steps performed during iteration. + We get the model index that corresponds to the selection by calling \l{QItemSelectionModel::currentIndex()}{treeView->selectionModel()->currentIndex()} and we get the the field's string by using the model index. Then we just calculate the item's \c hierarchyLevel. Top level items do not have parents and the \l{QAbstractItemModel::}{parent()} method will return a default constructed \l{QModelIndex}{QModelIndex()}. This is why we use the \l{QAbstractItemModel::}{parent()} method to iterate to the top level while counting the steps performed during iteration. - The selection model (as shown above) can be retrieved, but it can also be - set with \l{QAbstractItemView}{QAbstractItemView::setSelectionModel}. This - is how it's possible to have 3 view classes with synchronised selections - because only one instance of a selection model is used. The instance of a - selection model is retrieved from the first view class with - \l{QAbstractItemView::}{selectionModel()} and the result is assigned to the - second and third view class with \l{QAbstractItemView::}{setSelectionModel()}. + The selection model (as shown above) can be retrieved, but it can also be set with \l{QAbstractItemView}{QAbstractItemView::setSelectionModel}. This is how it's possible to have 3 view classes with synchronised selections because only one instance of a selection model is used. To share a selection model between 3 views use \l{QAbstractItemView::}{selectionModel()} and assign the result to the second and third view class with \l{QAbstractItemView::}{setSelectionModel()}. \section2 3.3 Predefined Models - The typical way to use model/view is to wrap specific data to make it - usable with view classes. Qt, however, also provides predefined models for - common underlying data structures. If one of the available data structures - is suitable for your application, a predefined model can be a good choice. + The typical way to use model/view is to wrap specific data to make it usable with view classes. Qt, however, also provides predefined models for common underlying data structures. If one of the available data structures is suitable for your application, a predefined model can be a good choice. \table \row @@ -527,23 +578,14 @@ \section2 3.4 Delegates - In all examples so far, data is presented as text or a checkbox in a cell - and is edited as text or a checkbox. The component that provides these - presentation and editing services is called a \e delegate. We are only just - beginning to work with the delegate because the view uses a default - delegate. But imagine that we want to have a different editor.(e.g. a - slider or a drop down list) Or imagine that we want to present data as - graphics. Let's take a look at an example called - \l{Star Delegate Example}{Star Delegate}, in which stars are used to show - a rating: + In all examples so far, data is presented as text or a checkbox in a cell and is edited as text or a checkbox. The component that provides these presentation and editing services is called a \e delegate. We are only just beginning to work with the delegate because the view uses a default delegate. But imagine that we want to have a different editor.(e.g. a slider or a drop down list) Or imagine that we want to present data as graphics. Let's take a look at an example called \l{Star Delegate Example}{Star Delegate}, in which stars are used to show a rating: + \raw HTML +

+ (Star Delegate Example)

+ \endraw \image stardelegate.png - The view has a method that replaces the default delegate and installs a - custom delegate. This method is called - \l{QAbstractItemView::}{setItemDelegate()}. A new delegate can be written - by creating a class that inherits from QStyledItemDelegate. In order to - write a delegate that displays stars and has no input capabilities, we only - need to overwrite 2 methods. + The view has a method that replaces the default delegate and installs a custom delegate. This method is called \l{QAbstractItemView::}{setItemDelegate()}. A new delegate can be written by creating a class that inherits from QStyledItemDelegate. In order to write a delegate that displays stars and has no input capabilities, we only need to overwrite 2 methods. \code class StarDelegate : public QStyledItemDelegate @@ -558,36 +600,31 @@ }; \endcode - \l{QStyledItemDelegate::}{paint()} draws stars depending on the content - of the underlying data. The data can be looked up with parameter - \l{QModelIndex::data()}{index.data()}. - \l{QAbstractItemDelegate::}{sizeHint()} specifies each star's dimensions - so the the cell will provide enough height and width to accommodate the - stars. + \l{QStyledItemDelegate::}{paint()} draws stars depending on the content of the underlying data. The data can be looked up with parameter \l{QModelIndex::data()}{index.data()}. \l{QAbstractItemDelegate::}{sizeHint()} specifies each star's dimensions so the the cell will provide enough height and width to accommodate the stars. + + Writing custom delegates is the right choice if you want to show your data with a custom graphical representation inside the grid of the view class. If you want to leave the grid, you would not use a custom delegate but a custom view class. + +Other references to delegates in Qt Documentation: +\raw HTML +

+Spin Box Delegate Example
+QAbstractItemDelegate Class Reference
+QSqlRelationalDelegate Class Reference
+QStyledItemDelegate Class Reference
+QItemDelegate Class Reference
+

+

+\endraw + - Writing custom delegates is the right choice if you want to show your data - with a custom graphical representation inside the grid of the view class. - If you want to leave the grid, you can write a custom view class. \section2 3.5 Debugging with ModelTest - The passive nature of models provides new challenges for programmers. - Inconsistencies in the model can cause the application to crash. Since the - model is hit by numerous calls from the view, it is hard to find out which - call has crashed the application and which operation has introduced the - problem. + The passive nature of models provides new challenges for programmers. Inconsistencies in the model can cause the application to crash. Since the model is hit by numerous calls from the view, it is hard to find out which call has crashed the application and which operation has introduced the problem. - Qt provides software called - \l{http://labs.qt.nokia.com/page/Projects/Itemview/Modeltest}{ModelTest}, - which checks models while your programming is running. Every time the model - is changed, ModelTest scans the model and reports errors with an assert. - This is especially important for tree models, since their hierarchical - nature leaves many possibilities for subtle inconsistencies. + Qt provides software called \l{http://labs.qt.nokia.com/page/Projects/Itemview/Modeltest}{ModelTest}, which checks models while your programming is running. Every time the model is changed, ModelTest scans the model and reports errors with an assert. This is especially important for tree models, since their hierarchical nature leaves many possibilities for subtle inconsistencies. - Unlike view classes, ModelTest uses out of range indexes to test the model. - This means your application may crash with ModelTest even if it runs - perfectly without it. So you also need to handle all of the indexes that - are out of range when using ModelTest. + Unlike view classes, ModelTest uses out of range indexes to test the model. This means your application may crash with ModelTest even if it runs perfectly without it. So you also need to handle all of the indexes that are out of range when using ModelTest. \section2 3.6 Model/View NG @@ -601,25 +638,23 @@ \endraw - Model/View was introduced in Qt 4.0 and is a frequently used technology. - Feedback from developers and new development trends have shown that there - is a need to further develop the model/view technology. Therefore a - research project originated at Nokia is looking into ways to go beyond the - current implementation. - - One limitation of model/view is that view classes are basically all fixed - grids. It is possible, but really hard to make a list view with icons - placed on a curve; or cells expanding on mouse over events to show - additional information. - In order to achieve graphically rich view experiences, Model/View NG will - use QGraphicsView to render elements. Nodel/View NG also aims to make - model/view programming more intuitive. One way to achieve this is to have - separate models for lists, tables and trees. The current model abstraction - is complex because it is capable of representing a list, a table or a tree. - - Model/View NG is a research project. You are welcome to checkout the source - code, monitor progress and take part in discussions at the following - address: \l{http://labs.qt.nokia.com/page/Projects/Itemview/ItemviewsNG} + Model/View was introduced in Qt 4.0 and is a frequently used technology. Feedback from developers and new development trends have shown that there is a need to further develop the model/view technology. Therefore a research project originated at Nokia is looking into ways to go beyond the current implementation. + \raw HTML +

+ \endraw + One limitation of model/view is that view classes are basically all fixed grids. It is possible, but really hard to make a list view with icons placed on a curve; or cells expanding on mouse over events to show additional information. In order to achieve graphically rich view experiences, Model/View NG will use QGraphicsView to render elements. Nodel/View NG also aims to make model/view programming more intuitive. One way to achieve this is to have separate models for lists, tables and trees. The current model abstraction is complex because it is capable of representing a list, a table or a tree. + \raw HTML +

+ \endraw + Model/View NG is a research project. You are welcome to checkout the source code, monitor progress and take part in discussions at the following address: \l{http://labs.qt.nokia.com/page/Projects/Itemview/ItemviewsNG} + + + + +\raw HTML +

+\endraw + \raw HTML @@ -630,6 +665,26 @@ \raw HTML \endraw + +\raw HTML +
+
+
+
+\endraw + + +\raw HTML +

+previous page +

+\endraw + +\raw HTML +

+last page +

+\endraw */ /*! @@ -637,9 +692,13 @@ \contentspage {modelview-index.html}{Model/View Contents} \previouspage {modelview-part3.html}{Intermediate Topics} \title Model/View Chapter 4 - Good Sources of Additional Information - +\raw HTML +
+\endraw \section1 4. Good Sources of Additional Information - +\raw HTML +
+\endraw \section2 4.1 Books Model/View programming is covered quite extensively in the documentation of @@ -657,12 +716,9 @@ \o \bold{Foundations of Qt Development} / Johan Thelin, \e{Apress}, ISBN 1-59059-831-8. \endlist - More information about these books is available on the - \l{Books about Qt Programming}{Qt Web site}. + More information about these books is available on the \l{Books about Qt Programming}{Qt Web site}. - The following list provides an overview of example programs contained in the - books above. Some of them make very good templates for developing similar - applications. + The following list provides an overview of example programs contained in the books above. Some of them make very good templates for developing similar applications. \table \header @@ -921,9 +977,7 @@ \o comprehensive custom delegate example. \endtable - \l{Qt Demonstrations}{Demonstrations} are similar to examples except - that no walkthrough is provided for the code. Demonstrations are also - sometimes more feature rich. + \l{Qt Demonstrations}{Demonstrations} are similar to examples except that no walkthrough is provided for the code lines. Demonstrations are also sometimes more feature rich. ( \l demos.html ) \list \o The \bold Interview demonstration shows the same model and @@ -933,6 +987,5 @@ each item according to the type of data it contains. \endlist - A \l{Model/View Programming}{reference document} for model/view technology - is also available. + A \l{Model/View Programming}{reference document} for model/view technology is also available. */ diff --git a/examples/tutorials/modelview/1_readonly/1_readonly.pro b/examples/tutorials/modelview/1_readonly/1_readonly.pro old mode 100644 new mode 100755 index 1162d5a..3ecebc2 --- a/examples/tutorials/modelview/1_readonly/1_readonly.pro +++ b/examples/tutorials/modelview/1_readonly/1_readonly.pro @@ -3,8 +3,15 @@ TARGET = mv_readonly TEMPLATE = app SOURCES += main.cpp \ - modelview.cpp \ mymodel.cpp -HEADERS += modelview.h \ - mymodel.h +HEADERS += mymodel.h + + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/tutorials/modelview/1_readonly +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS 1_readonly.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/tutorials/modelview/1_readonly +INSTALLS += target sources + +symbian: include($$QT_SOURCE_TREE/examples/symbianpkgrules.pri) diff --git a/examples/tutorials/modelview/1_readonly/main.cpp b/examples/tutorials/modelview/1_readonly/main.cpp old mode 100644 new mode 100755 index fb4726a..2143854 --- a/examples/tutorials/modelview/1_readonly/main.cpp +++ b/examples/tutorials/modelview/1_readonly/main.cpp @@ -41,13 +41,16 @@ //! [Quoting ModelView Tutorial] // main.cpp #include -#include "modelview.h" +#include +#include "mymodel.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); - ModelView w; - w.show(); + QTableView tableView; + MyModel myModel(0); + tableView.setModel( &myModel ); + tableView.show(); return a.exec(); } //! [Quoting ModelView Tutorial] diff --git a/examples/tutorials/modelview/1_readonly/modelview.cpp b/examples/tutorials/modelview/1_readonly/modelview.cpp deleted file mode 100644 index 91a97bf..0000000 --- a/examples/tutorials/modelview/1_readonly/modelview.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//! [Quoting ModelView Tutorial] -// modelview.cpp -#include -#include "modelview.h" -#include "mymodel.h" - -ModelView::ModelView(QWidget *parent) - : QMainWindow(parent) -{ - tableView = new QTableView(this); - setCentralWidget(tableView); - tableView->setModel(new MyModel(this)); -} -//! [Quoting ModelView Tutorial] diff --git a/examples/tutorials/modelview/1_readonly/modelview.h b/examples/tutorials/modelview/1_readonly/modelview.h deleted file mode 100644 index cc14d90..0000000 --- a/examples/tutorials/modelview/1_readonly/modelview.h +++ /dev/null @@ -1,61 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef MODELVIEW_H -#define MODELVIEW_H - -//! [Quoting ModelView Tutorial] -// modelview.h -#include - -QT_FORWARD_DECLARE_CLASS(QTableView) - -class ModelView : public QMainWindow -{ - Q_OBJECT -private: - QTableView *tableView; -public: - ModelView(QWidget *parent = 0); - -}; -//! [Quoting ModelView Tutorial] - -#endif // MODELVIEW_H diff --git a/examples/tutorials/modelview/1_readonly/mymodel.cpp b/examples/tutorials/modelview/1_readonly/mymodel.cpp old mode 100644 new mode 100755 diff --git a/examples/tutorials/modelview/1_readonly/mymodel.h b/examples/tutorials/modelview/1_readonly/mymodel.h old mode 100644 new mode 100755 diff --git a/examples/tutorials/modelview/2_formatting/2_formatting.pro b/examples/tutorials/modelview/2_formatting/2_formatting.pro old mode 100644 new mode 100755 index 7e70d81..c6ad27c --- a/examples/tutorials/modelview/2_formatting/2_formatting.pro +++ b/examples/tutorials/modelview/2_formatting/2_formatting.pro @@ -3,8 +3,14 @@ TARGET = mv_formatting TEMPLATE = app SOURCES += main.cpp \ - modelview.cpp \ mymodel.cpp -HEADERS += modelview.h \ - mymodel.h +HEADERS += mymodel.h + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/tutorials/modelview/2_formatting +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS 2_formatting.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/tutorials/modelview/2_formatting +INSTALLS += target sources + +symbian: include($$QT_SOURCE_TREE/examples/symbianpkgrules.pri) diff --git a/examples/tutorials/modelview/2_formatting/main.cpp b/examples/tutorials/modelview/2_formatting/main.cpp old mode 100644 new mode 100755 index 7be212e..2143854 --- a/examples/tutorials/modelview/2_formatting/main.cpp +++ b/examples/tutorials/modelview/2_formatting/main.cpp @@ -38,13 +38,19 @@ ** ****************************************************************************/ +//! [Quoting ModelView Tutorial] +// main.cpp #include -#include "modelview.h" +#include +#include "mymodel.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); - ModelView w; - w.show(); + QTableView tableView; + MyModel myModel(0); + tableView.setModel( &myModel ); + tableView.show(); return a.exec(); } +//! [Quoting ModelView Tutorial] diff --git a/examples/tutorials/modelview/2_formatting/modelview.cpp b/examples/tutorials/modelview/2_formatting/modelview.cpp deleted file mode 100644 index 9a5ce64..0000000 --- a/examples/tutorials/modelview/2_formatting/modelview.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "modelview.h" -#include "mymodel.h" - -ModelView::ModelView(QWidget *parent) - : QMainWindow(parent) -{ - tableView = new QTableView(this); - setCentralWidget(tableView); - tableView->setModel(new MyModel(this)); -} - diff --git a/examples/tutorials/modelview/2_formatting/modelview.h b/examples/tutorials/modelview/2_formatting/modelview.h deleted file mode 100644 index b2943ac..0000000 --- a/examples/tutorials/modelview/2_formatting/modelview.h +++ /dev/null @@ -1,57 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef MODELVIEW_H -#define MODELVIEW_H - -#include - -QT_FORWARD_DECLARE_CLASS(QTableView) - -class ModelView : public QMainWindow -{ - Q_OBJECT -private: - QTableView *tableView; -public: - ModelView(QWidget *parent = 0); -}; - -#endif // MODELVIEW_H diff --git a/examples/tutorials/modelview/2_formatting/mymodel.cpp b/examples/tutorials/modelview/2_formatting/mymodel.cpp old mode 100644 new mode 100755 index f7ff504..3e13ff4 --- a/examples/tutorials/modelview/2_formatting/mymodel.cpp +++ b/examples/tutorials/modelview/2_formatting/mymodel.cpp @@ -43,8 +43,6 @@ #include "mymodel.h" #include -//! [Quoting ModelView Tutorial] -// mymodel.cpp MyModel::MyModel(QObject *parent) :QAbstractTableModel(parent) { @@ -60,6 +58,8 @@ int MyModel::columnCount(const QModelIndex & /*parent */) const return 3; } +//! [Quoting ModelView Tutorial] +// mymodel.cpp QVariant MyModel::data(const QModelIndex &index, int role) const { int row = index.row(); @@ -89,7 +89,7 @@ QVariant MyModel::data(const QModelIndex &index, int role) const if (row == 1 && col == 2) //change background only for cell(1,2) { - QBrush redBackground = QBrush(Qt::red); + QBrush redBackground(QColor(Qt::red)); return redBackground; } break; diff --git a/examples/tutorials/modelview/2_formatting/mymodel.h b/examples/tutorials/modelview/2_formatting/mymodel.h old mode 100644 new mode 100755 diff --git a/examples/tutorials/modelview/3_changingmodel/3_changingmodel.pro b/examples/tutorials/modelview/3_changingmodel/3_changingmodel.pro old mode 100644 new mode 100755 index d61ee4c..e977731 --- a/examples/tutorials/modelview/3_changingmodel/3_changingmodel.pro +++ b/examples/tutorials/modelview/3_changingmodel/3_changingmodel.pro @@ -3,8 +3,14 @@ TARGET = mv_changingmodel TEMPLATE = app SOURCES += main.cpp \ - modelview.cpp \ mymodel.cpp -HEADERS += modelview.h \ - mymodel.h +HEADERS += mymodel.h + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/tutorials/modelview/3_changingmodel +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS 3_changingmodel.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/tutorials/modelview/3_changingmodel +INSTALLS += target sources + +symbian: include($$QT_SOURCE_TREE/examples/symbianpkgrules.pri) diff --git a/examples/tutorials/modelview/3_changingmodel/main.cpp b/examples/tutorials/modelview/3_changingmodel/main.cpp old mode 100644 new mode 100755 diff --git a/examples/tutorials/modelview/3_changingmodel/modelview.cpp b/examples/tutorials/modelview/3_changingmodel/modelview.cpp deleted file mode 100644 index 9a5ce64..0000000 --- a/examples/tutorials/modelview/3_changingmodel/modelview.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "modelview.h" -#include "mymodel.h" - -ModelView::ModelView(QWidget *parent) - : QMainWindow(parent) -{ - tableView = new QTableView(this); - setCentralWidget(tableView); - tableView->setModel(new MyModel(this)); -} - diff --git a/examples/tutorials/modelview/3_changingmodel/modelview.h b/examples/tutorials/modelview/3_changingmodel/modelview.h deleted file mode 100644 index b2943ac..0000000 --- a/examples/tutorials/modelview/3_changingmodel/modelview.h +++ /dev/null @@ -1,57 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef MODELVIEW_H -#define MODELVIEW_H - -#include - -QT_FORWARD_DECLARE_CLASS(QTableView) - -class ModelView : public QMainWindow -{ - Q_OBJECT -private: - QTableView *tableView; -public: - ModelView(QWidget *parent = 0); -}; - -#endif // MODELVIEW_H diff --git a/examples/tutorials/modelview/3_changingmodel/mymodel.cpp b/examples/tutorials/modelview/3_changingmodel/mymodel.cpp old mode 100644 new mode 100755 diff --git a/examples/tutorials/modelview/3_changingmodel/mymodel.h b/examples/tutorials/modelview/3_changingmodel/mymodel.h old mode 100644 new mode 100755 index 01ad88d..47b026e --- a/examples/tutorials/modelview/3_changingmodel/mymodel.h +++ b/examples/tutorials/modelview/3_changingmodel/mymodel.h @@ -43,7 +43,7 @@ #include -QT_FORWARD_DECLARE_CLASS(QTimer) +class QTimer; // forward declaration class MyModel : public QAbstractTableModel { diff --git a/examples/tutorials/modelview/4_headers/4_headers.pro b/examples/tutorials/modelview/4_headers/4_headers.pro old mode 100644 new mode 100755 index d6f8d23..f6c60b2 --- a/examples/tutorials/modelview/4_headers/4_headers.pro +++ b/examples/tutorials/modelview/4_headers/4_headers.pro @@ -2,9 +2,15 @@ TARGET = mv_headers TEMPLATE = app -SOURCES += main.cpp \ - modelview.cpp \ +SOURCES += main.cpp \ mymodel.cpp -HEADERS += modelview.h \ - mymodel.h +HEADERS += mymodel.h + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/tutorials/modelview/4_headers +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS 4_headers.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/tutorials/modelview/4_headers +INSTALLS += target sources + +symbian: include($$QT_SOURCE_TREE/examples/symbianpkgrules.pri) diff --git a/examples/tutorials/modelview/4_headers/main.cpp b/examples/tutorials/modelview/4_headers/main.cpp old mode 100644 new mode 100755 diff --git a/examples/tutorials/modelview/4_headers/modelview.cpp b/examples/tutorials/modelview/4_headers/modelview.cpp deleted file mode 100644 index 449dbbc..0000000 --- a/examples/tutorials/modelview/4_headers/modelview.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include "modelview.h" -#include "mymodel.h" - -ModelView::ModelView(QWidget *parent) - : QMainWindow(parent) -{ - tableView = new QTableView(this); - setCentralWidget(tableView); - tableView->setModel(new MyModel(this)); - tableView->verticalHeader()->hide(); -} - diff --git a/examples/tutorials/modelview/4_headers/modelview.h b/examples/tutorials/modelview/4_headers/modelview.h deleted file mode 100644 index 03f99c0..0000000 --- a/examples/tutorials/modelview/4_headers/modelview.h +++ /dev/null @@ -1,58 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef MODELVIEW_H -#define MODELVIEW_H - -#include - -QT_FORWARD_DECLARE_CLASS(QTableView) - -class ModelView : public QMainWindow -{ - Q_OBJECT -private: - QTableView *tableView; -public: - ModelView(QWidget *parent = 0); - -}; - -#endif // MODELVIEW_H diff --git a/examples/tutorials/modelview/4_headers/mymodel.cpp b/examples/tutorials/modelview/4_headers/mymodel.cpp old mode 100644 new mode 100755 diff --git a/examples/tutorials/modelview/4_headers/mymodel.h b/examples/tutorials/modelview/4_headers/mymodel.h old mode 100644 new mode 100755 diff --git a/examples/tutorials/modelview/5_edit/5_edit.pro b/examples/tutorials/modelview/5_edit/5_edit.pro old mode 100644 new mode 100755 index e18c596..2ef343f --- a/examples/tutorials/modelview/5_edit/5_edit.pro +++ b/examples/tutorials/modelview/5_edit/5_edit.pro @@ -3,8 +3,16 @@ TARGET = mv_edit TEMPLATE = app SOURCES += main.cpp \ - modelview.cpp \ + mainwindow.cpp \ mymodel.cpp -HEADERS += modelview.h \ +HEADERS += mainwindow.h \ mymodel.h + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/tutorials/modelview/5_edit +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS 5_edit.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/tutorials/modelview/5_edit +INSTALLS += target sources + +symbian: include($$QT_SOURCE_TREE/examples/symbianpkgrules.pri) diff --git a/examples/tutorials/modelview/5_edit/main.cpp b/examples/tutorials/modelview/5_edit/main.cpp old mode 100644 new mode 100755 index 7be212e..59e82ef --- a/examples/tutorials/modelview/5_edit/main.cpp +++ b/examples/tutorials/modelview/5_edit/main.cpp @@ -39,12 +39,12 @@ ****************************************************************************/ #include -#include "modelview.h" +#include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); - ModelView w; + MainWindow w; w.show(); return a.exec(); } diff --git a/examples/tutorials/modelview/5_edit/modelview.cpp b/examples/tutorials/modelview/5_edit/modelview.cpp deleted file mode 100644 index a6c6ef5..0000000 --- a/examples/tutorials/modelview/5_edit/modelview.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "modelview.h" -#include "mymodel.h" - -ModelView::ModelView(QWidget *parent) - : QMainWindow(parent) -{ - tableView = new QTableView(this); - setCentralWidget(tableView); - QAbstractTableModel *myModel = new MyModel(this); - tableView->setModel(myModel); - - //transfer changes to the model to the window title - connect(myModel, SIGNAL(editCompleted(const QString &)), this, SLOT(setWindowTitle(const QString &))); -} - -void ModelView::showWindowTitle(const QString & title) -{ -setWindowTitle(title); -} diff --git a/examples/tutorials/modelview/5_edit/modelview.h b/examples/tutorials/modelview/5_edit/modelview.h deleted file mode 100644 index 069107b..0000000 --- a/examples/tutorials/modelview/5_edit/modelview.h +++ /dev/null @@ -1,59 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef MODELVIEW_H -#define MODELVIEW_H - -#include - -QT_FORWARD_DECLARE_CLASS(QTableView) - -class ModelView : public QMainWindow -{ - Q_OBJECT -private: - QTableView *tableView; -public: - ModelView(QWidget *parent = 0); -public slots: - void showWindowTitle(const QString & title); -}; - -#endif // MODELVIEW_H diff --git a/examples/tutorials/modelview/5_edit/mymodel.cpp b/examples/tutorials/modelview/5_edit/mymodel.cpp old mode 100644 new mode 100755 index 67181ca..e2fd391 --- a/examples/tutorials/modelview/5_edit/mymodel.cpp +++ b/examples/tutorials/modelview/5_edit/mymodel.cpp @@ -38,62 +38,64 @@ ** ****************************************************************************/ -//! [quoting mymodel_d] + #include "mymodel.h" -const int COLS= 3; -const int ROWS= 2; MyModel::MyModel(QObject *parent) :QAbstractTableModel(parent) { - //gridData needs to have 6 element, one for each table cell - m_gridData << "1/1" << "1/2" << "1/3" << "2/1" << "2/2" << "2/3" ; } -//! [quoting mymodel_d] -//! [quoting mymodel_e] +//----------------------------------------------------------------- int MyModel::rowCount(const QModelIndex & /*parent*/) const { return ROWS; } +//----------------------------------------------------------------- int MyModel::columnCount(const QModelIndex & /*parent*/) const { return COLS; } +//----------------------------------------------------------------- QVariant MyModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { - return m_gridData[modelIndexToOffset(index)]; + return m_gridData[index.row()][index.column()]; } return QVariant(); } -//! [quoting mymodel_e] //----------------------------------------------------------------- - -//! [quoting mymodel_f] +//! [quoting mymodel_e] bool MyModel::setData(const QModelIndex & index, const QVariant & value, int role) { if (role == Qt::EditRole) { - m_gridData[modelIndexToOffset(index)] = value.toString(); - emit editCompleted(m_gridData.join(" | ")); + //save value from editor to member m_gridData + m_gridData[index.row()][index.column()] = value.toString(); + //for presentation purposes only: build and emit a joined string + QString result; + for(int row= 0; row < ROWS; row++) + { + for(int col= 0; col < COLS; col++) + { + result += m_gridData[row][col] + " "; + } + } + emit editCompleted( result ); } return true; } +//! [quoting mymodel_e] +//----------------------------------------------------------------- +//! [quoting mymodel_f] Qt::ItemFlags MyModel::flags(const QModelIndex & /*index*/) const { return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled ; } - -//convert row and column information to array offset -int MyModel::modelIndexToOffset(const QModelIndex & index) const -{ - return index.row()*COLS + index.column(); -} //! [quoting mymodel_f] diff --git a/examples/tutorials/modelview/5_edit/mymodel.h b/examples/tutorials/modelview/5_edit/mymodel.h old mode 100644 new mode 100755 index 0d2a1b8..574808e --- a/examples/tutorials/modelview/5_edit/mymodel.h +++ b/examples/tutorials/modelview/5_edit/mymodel.h @@ -44,7 +44,11 @@ //! [Quoting ModelView Tutorial] // mymodel.h #include -#include +#include + +const int COLS= 3; +const int ROWS= 2; + class MyModel : public QAbstractTableModel { @@ -57,8 +61,7 @@ public: bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole); Qt::ItemFlags flags(const QModelIndex & index) const ; private: - QStringList m_gridData; //holds text entered into QTableView - int modelIndexToOffset(const QModelIndex & index) const; + QString m_gridData[ROWS][COLS]; //holds text entered into QTableView signals: void editCompleted(const QString &); }; diff --git a/examples/tutorials/modelview/6_treeview/6_treeview.pro b/examples/tutorials/modelview/6_treeview/6_treeview.pro old mode 100644 new mode 100755 index 6d078be..e79ef20 --- a/examples/tutorials/modelview/6_treeview/6_treeview.pro +++ b/examples/tutorials/modelview/6_treeview/6_treeview.pro @@ -1,5 +1,13 @@ TARGET = mv_tree TEMPLATE = app SOURCES += main.cpp \ - modelview.cpp -HEADERS += modelview.h + mainwindow.cpp +HEADERS += mainwindow.h + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/tutorials/modelview/6_treeview +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS 6_treeview.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/tutorials/modelview/6_treeview +INSTALLS += target sources + +symbian: include($$QT_SOURCE_TREE/examples/symbianpkgrules.pri) diff --git a/examples/tutorials/modelview/6_treeview/main.cpp b/examples/tutorials/modelview/6_treeview/main.cpp old mode 100644 new mode 100755 index 7be212e..59e82ef --- a/examples/tutorials/modelview/6_treeview/main.cpp +++ b/examples/tutorials/modelview/6_treeview/main.cpp @@ -39,12 +39,12 @@ ****************************************************************************/ #include -#include "modelview.h" +#include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); - ModelView w; + MainWindow w; w.show(); return a.exec(); } diff --git a/examples/tutorials/modelview/6_treeview/modelview.cpp b/examples/tutorials/modelview/6_treeview/modelview.cpp deleted file mode 100644 index 772dbdd..0000000 --- a/examples/tutorials/modelview/6_treeview/modelview.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//! [Quoting ModelView Tutorial] -// modelview.cpp -#include -#include -#include -#include "modelview.h" - - -const int ROWS = 2; -const int COLUMNS = 3; - -ModelView::ModelView(QWidget *parent) - : QMainWindow(parent) -{ - treeView = new QTreeView(this); - setCentralWidget(treeView); - standardModel = new QStandardItemModel ; - - QList preparedColumn =prepareColumn("first", "second", "third"); - QStandardItem *item = standardModel->invisibleRootItem(); - // adding a row to the invisible root item produces a root element - item->appendRow(preparedColumn); - - QList secondRow =prepareColumn("111", "222", "333"); - // adding a row to an item starts a subtree - preparedColumn.first()->appendRow(secondRow); - - treeView->setModel(standardModel); - treeView->expandAll(); -} - -QList ModelView::prepareColumn(const QString &first, - const QString &second, - const QString &third) -{ - QList colItems; - colItems << new QStandardItem(first); - colItems << new QStandardItem(second); - colItems << new QStandardItem(third); - return colItems; -} -//! [Quoting ModelView Tutorial] diff --git a/examples/tutorials/modelview/6_treeview/modelview.h b/examples/tutorials/modelview/6_treeview/modelview.h deleted file mode 100644 index 55f3470..0000000 --- a/examples/tutorials/modelview/6_treeview/modelview.h +++ /dev/null @@ -1,65 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef MODELVIEW_H -#define MODELVIEW_H - -#include - -QT_BEGIN_NAMESPACE -class QTreeView; //forward declaration -class QStandardItemModel; -class QStandardItem; -QT_END_NAMESPACE - -class ModelView : public QMainWindow -{ - Q_OBJECT -private: - QTreeView *treeView; - QStandardItemModel *standardModel; - QList prepareColumn(const QString &first, - const QString &second, - const QString &third); -public: - ModelView(QWidget *parent = 0); -}; - -#endif // MODELVIEW_H diff --git a/examples/tutorials/modelview/7_selections/7_selections.pro b/examples/tutorials/modelview/7_selections/7_selections.pro old mode 100644 new mode 100755 index 952641c6..6945bf7 --- a/examples/tutorials/modelview/7_selections/7_selections.pro +++ b/examples/tutorials/modelview/7_selections/7_selections.pro @@ -1,5 +1,13 @@ TARGET = mv_selections TEMPLATE = app SOURCES += main.cpp \ - modelview.cpp -HEADERS += modelview.h + mainwindow.cpp +HEADERS += mainwindow.h + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/tutorials/modelview/7_selections +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS 7_selections.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/tutorials/modelview/7_selections +INSTALLS += target sources + +symbian: include($$QT_SOURCE_TREE/examples/symbianpkgrules.pri) diff --git a/examples/tutorials/modelview/7_selections/main.cpp b/examples/tutorials/modelview/7_selections/main.cpp old mode 100644 new mode 100755 index 7be212e..59e82ef --- a/examples/tutorials/modelview/7_selections/main.cpp +++ b/examples/tutorials/modelview/7_selections/main.cpp @@ -39,12 +39,12 @@ ****************************************************************************/ #include -#include "modelview.h" +#include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); - ModelView w; + MainWindow w; w.show(); return a.exec(); } diff --git a/examples/tutorials/modelview/7_selections/modelview.cpp b/examples/tutorials/modelview/7_selections/modelview.cpp deleted file mode 100644 index 3b373c6..0000000 --- a/examples/tutorials/modelview/7_selections/modelview.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//! [quoting modelview_a] -#include -#include -#include -#include "modelview.h" - -ModelView::ModelView(QWidget *parent) - : QMainWindow(parent) -{ - treeView = new QTreeView(this); - setCentralWidget(treeView); - standardModel = new QStandardItemModel ; - QStandardItem *rootNode = standardModel->invisibleRootItem(); - - - //defining a couple of items - QStandardItem *americaItem = new QStandardItem("America"); - QStandardItem *mexicoItem = new QStandardItem("Canada"); - QStandardItem *usaItem = new QStandardItem("USA"); - QStandardItem *bostonItem = new QStandardItem("Boston"); - QStandardItem *europeItem = new QStandardItem("Europe"); - QStandardItem *italyItem = new QStandardItem("Italy"); - QStandardItem *romeItem = new QStandardItem("Rome"); - QStandardItem *veronaItem = new QStandardItem("Verona"); - - //building up the hierarchy - rootNode-> appendRow(americaItem); - rootNode-> appendRow(europeItem); - americaItem-> appendRow(mexicoItem); - americaItem-> appendRow(usaItem); - usaItem-> appendRow(bostonItem); - europeItem-> appendRow(italyItem); - italyItem-> appendRow(romeItem); - italyItem-> appendRow(veronaItem); - - //register the model - treeView->setModel(standardModel); - treeView->expandAll(); - - //selection changes shall trigger a slot - QItemSelectionModel *selectionModel= treeView->selectionModel(); - connect(selectionModel, SIGNAL(selectionChanged (const QItemSelection &, const QItemSelection &)), - this, SLOT(selectionChangedSlot(const QItemSelection &, const QItemSelection &))); -} -//! [quoting modelview_a] - -//------------------------------------------------------------------------------------ - -//! [quoting modelview_b] -void ModelView::selectionChangedSlot(const QItemSelection & /*newSelection*/, const QItemSelection & /*oldSelection*/) -{ - const QModelIndex index = treeView->selectionModel()->currentIndex(); - QString selectedText = index.data(Qt::DisplayRole).toString(); - int hierarchyLevel=1; - QModelIndex seekRoot = index; - while(seekRoot.parent() != QModelIndex()) - { - seekRoot = seekRoot.parent(); - hierarchyLevel++; - } - QString showString = QString("%1, Level %2").arg(selectedText) - .arg(hierarchyLevel); - setWindowTitle(showString); -} -//! [quoting modelview_b] - - diff --git a/examples/tutorials/modelview/7_selections/modelview.h b/examples/tutorials/modelview/7_selections/modelview.h deleted file mode 100644 index d20797e..0000000 --- a/examples/tutorials/modelview/7_selections/modelview.h +++ /dev/null @@ -1,64 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef MODELVIEW_H -#define MODELVIEW_H - -#include - -QT_BEGIN_NAMESPACE -class QTreeView; //forward declaration -class QStandardItemModel; -class QItemSelection; -QT_END_NAMESPACE - -class ModelView : public QMainWindow -{ - Q_OBJECT -private: - QTreeView *treeView; - QStandardItemModel *standardModel; -private slots: - void selectionChangedSlot(const QItemSelection & newSelection, const QItemSelection & oldSelection); -public: - ModelView(QWidget *parent = 0); -}; - -#endif // MODELVIEW_H diff --git a/examples/tutorials/modelview/modelview.pro b/examples/tutorials/modelview/modelview.pro old mode 100644 new mode 100755 index 7f684ba..50f5c3a --- a/examples/tutorials/modelview/modelview.pro +++ b/examples/tutorials/modelview/modelview.pro @@ -1,5 +1,4 @@ -TEMPLATE = subdirs - +TEMPLATE = subdirs SUBDIRS = 1_readonly \ 2_formatting \ 3_changingmodel \ @@ -8,3 +7,10 @@ SUBDIRS = 1_readonly \ 6_treeview \ 7_selections +# install +target.path = $$[QT_INSTALL_EXAMPLES]/tutorials/modelview +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS modelview.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/tutorials/modelview +INSTALLS += target sources + +symbian: include($$QT_SOURCE_TREE/examples/symbianpkgrules.pri) -- cgit v0.12 From aa7af0612b13717a449075e0bfb30d618f66436a Mon Sep 17 00:00:00 2001 From: Michael D Scull Date: Thu, 29 Jul 2010 15:56:52 +0200 Subject: problem: 2 images that were in raw html tables appeared smaller in konqueror for some reason - solution: fixed width for right columns in 2 raw html tables --- doc/src/tutorials/modelview.qdoc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/src/tutorials/modelview.qdoc b/doc/src/tutorials/modelview.qdoc index f771726..82e0c85 100644 --- a/doc/src/tutorials/modelview.qdoc +++ b/doc/src/tutorials/modelview.qdoc @@ -123,7 +123,7 @@ Table, list and tree widgets are components frequently used in GUIs. There are 2 \raw HTML - + \endraw \raw HTML @@ -657,10 +657,10 @@ Other references to delegates in Qt Documentation: \raw HTML - + \endraw - \inlineimage path.png + \image path.png \raw HTML -- cgit v0.12 From eec71645f7e0e41786f01c09e30817d898ff3cc0 Mon Sep 17 00:00:00 2001 From: Roland Wolf Date: Fri, 30 Jul 2010 11:05:40 +0200 Subject: added missing files --- examples/tutorials/modelview/5_edit/mainwindow.cpp | 60 ++++++++++++++++++++++ examples/tutorials/modelview/5_edit/mainwindow.h | 59 +++++++++++++++++++++ 2 files changed, 119 insertions(+) create mode 100755 examples/tutorials/modelview/5_edit/mainwindow.cpp create mode 100755 examples/tutorials/modelview/5_edit/mainwindow.h diff --git a/examples/tutorials/modelview/5_edit/mainwindow.cpp b/examples/tutorials/modelview/5_edit/mainwindow.cpp new file mode 100755 index 0000000..542f3d6 --- /dev/null +++ b/examples/tutorials/modelview/5_edit/mainwindow.cpp @@ -0,0 +1,60 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "mainwindow.h" +#include "mymodel.h" + +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) +{ + tableView = new QTableView(this); + setCentralWidget(tableView); + QAbstractTableModel *myModel = new MyModel(this); + tableView->setModel(myModel); + + //transfer changes to the model to the window title + connect(myModel, SIGNAL(editCompleted(const QString &)), this, SLOT(setWindowTitle(const QString &))); +} + +void MainWindow::showWindowTitle(const QString & title) +{ +setWindowTitle(title); +} diff --git a/examples/tutorials/modelview/5_edit/mainwindow.h b/examples/tutorials/modelview/5_edit/mainwindow.h new file mode 100755 index 0000000..1d49f47 --- /dev/null +++ b/examples/tutorials/modelview/5_edit/mainwindow.h @@ -0,0 +1,59 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include + +class QTableView; //forward declaration + +class MainWindow : public QMainWindow +{ + Q_OBJECT +private: + QTableView *tableView; +public: + MainWindow(QWidget *parent = 0); +public slots: + void showWindowTitle(const QString & title); +}; + +#endif // MAINWINDOW_H -- cgit v0.12 From 5148f9e02483598d7e916845ccd0712e5e24f45d Mon Sep 17 00:00:00 2001 From: Roland Wolf Date: Fri, 30 Jul 2010 11:08:32 +0200 Subject: added missing files --- .../tutorials/modelview/6_treeview/mainwindow.cpp | 82 ++++++++++++++++ .../tutorials/modelview/6_treeview/mainwindow.h | 64 ++++++++++++ .../modelview/7_selections/mainwindow.cpp | 109 +++++++++++++++++++++ .../tutorials/modelview/7_selections/mainwindow.h | 63 ++++++++++++ 4 files changed, 318 insertions(+) create mode 100755 examples/tutorials/modelview/6_treeview/mainwindow.cpp create mode 100755 examples/tutorials/modelview/6_treeview/mainwindow.h create mode 100755 examples/tutorials/modelview/7_selections/mainwindow.cpp create mode 100755 examples/tutorials/modelview/7_selections/mainwindow.h diff --git a/examples/tutorials/modelview/6_treeview/mainwindow.cpp b/examples/tutorials/modelview/6_treeview/mainwindow.cpp new file mode 100755 index 0000000..a105232 --- /dev/null +++ b/examples/tutorials/modelview/6_treeview/mainwindow.cpp @@ -0,0 +1,82 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//! [Quoting ModelView Tutorial] +// modelview.cpp +#include +#include +#include +#include "mainwindow.h" + + +const int ROWS = 2; +const int COLUMNS = 3; + +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) +{ + treeView = new QTreeView(this); + setCentralWidget(treeView); + standardModel = new QStandardItemModel ; + + QList preparedRow =prepareRow("first", "second", "third"); + QStandardItem *item = standardModel->invisibleRootItem(); + // adding a row to the invisible root item produces a root element + item->appendRow(preparedRow); + + QList secondRow =prepareRow("111", "222", "333"); + // adding a row to an item starts a subtree + preparedRow.first()->appendRow(secondRow); + + treeView->setModel(standardModel); + treeView->expandAll(); +} + +QList MainWindow::prepareRow(const QString &first, + const QString &second, + const QString &third) +{ + QList rowItems; + rowItems << new QStandardItem(first); + rowItems << new QStandardItem(second); + rowItems << new QStandardItem(third); + return rowItems; +} +//! [Quoting ModelView Tutorial] diff --git a/examples/tutorials/modelview/6_treeview/mainwindow.h b/examples/tutorials/modelview/6_treeview/mainwindow.h new file mode 100755 index 0000000..fb8de79 --- /dev/null +++ b/examples/tutorials/modelview/6_treeview/mainwindow.h @@ -0,0 +1,64 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include + +class QTreeView; //forward declaration +class QStandardItemModel; +class QStandardItem; + + +class MainWindow : public QMainWindow +{ + Q_OBJECT +private: + QTreeView *treeView; + QStandardItemModel *standardModel; + QList prepareRow( const QString &first, + const QString &second, + const QString &third ); +public: + MainWindow(QWidget *parent = 0); +}; + +#endif // MAINWINDOW_H diff --git a/examples/tutorials/modelview/7_selections/mainwindow.cpp b/examples/tutorials/modelview/7_selections/mainwindow.cpp new file mode 100755 index 0000000..cb09633 --- /dev/null +++ b/examples/tutorials/modelview/7_selections/mainwindow.cpp @@ -0,0 +1,109 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//! [quoting modelview_a] +#include +#include +#include +#include "mainwindow.h" + +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) +{ + treeView = new QTreeView(this); + setCentralWidget(treeView); + standardModel = new QStandardItemModel ; + QStandardItem *rootNode = standardModel->invisibleRootItem(); + + + //defining a couple of items + QStandardItem *americaItem = new QStandardItem("America"); + QStandardItem *mexicoItem = new QStandardItem("Canada"); + QStandardItem *usaItem = new QStandardItem("USA"); + QStandardItem *bostonItem = new QStandardItem("Boston"); + QStandardItem *europeItem = new QStandardItem("Europe"); + QStandardItem *italyItem = new QStandardItem("Italy"); + QStandardItem *romeItem = new QStandardItem("Rome"); + QStandardItem *veronaItem = new QStandardItem("Verona"); + + //building up the hierarchy + rootNode-> appendRow(americaItem); + rootNode-> appendRow(europeItem); + americaItem-> appendRow(mexicoItem); + americaItem-> appendRow(usaItem); + usaItem-> appendRow(bostonItem); + europeItem-> appendRow(italyItem); + italyItem-> appendRow(romeItem); + italyItem-> appendRow(veronaItem); + + //register the model + treeView->setModel(standardModel); + treeView->expandAll(); + + //selection changes shall trigger a slot + QItemSelectionModel *selectionModel= treeView->selectionModel(); + connect(selectionModel, SIGNAL(selectionChanged (const QItemSelection &, const QItemSelection &)), + this, SLOT(selectionChangedSlot(const QItemSelection &, const QItemSelection &))); +} +//! [quoting modelview_a] + +//------------------------------------------------------------------------------------ + +//! [quoting modelview_b] +void MainWindow::selectionChangedSlot(const QItemSelection & /*newSelection*/, const QItemSelection & /*oldSelection*/) +{ + //get the text of the selected item + const QModelIndex index = treeView->selectionModel()->currentIndex(); + QString selectedText = index.data(Qt::DisplayRole).toString(); + //find out the hierarchy level of the selected item + int hierarchyLevel=1; + QModelIndex seekRoot = index; + while(seekRoot.parent() != QModelIndex()) + { + seekRoot = seekRoot.parent(); + hierarchyLevel++; + } + QString showString = QString("%1, Level %2").arg(selectedText) + .arg(hierarchyLevel); + setWindowTitle(showString); +} +//! [quoting modelview_b] + + diff --git a/examples/tutorials/modelview/7_selections/mainwindow.h b/examples/tutorials/modelview/7_selections/mainwindow.h new file mode 100755 index 0000000..f2defb5 --- /dev/null +++ b/examples/tutorials/modelview/7_selections/mainwindow.h @@ -0,0 +1,63 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include + +class QTreeView; //forward declaration +class QStandardItemModel; +class QItemSelection; + + +class MainWindow : public QMainWindow +{ + Q_OBJECT +private: + QTreeView *treeView; + QStandardItemModel *standardModel; +private slots: + void selectionChangedSlot(const QItemSelection & newSelection, const QItemSelection & oldSelection); +public: + MainWindow(QWidget *parent = 0); +}; + +#endif // MAINWINDOW_H -- cgit v0.12 From 2299cc27db5e40fe43c6b46d5560fe65bc9e6da5 Mon Sep 17 00:00:00 2001 From: Roland Wolf Date: Fri, 30 Jul 2010 13:17:02 +0200 Subject: fixed compilation problem --- examples/tutorials/modelview/3_changingmodel/main.cpp | 9 ++++++--- examples/tutorials/modelview/4_headers/main.cpp | 11 +++++++---- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/examples/tutorials/modelview/3_changingmodel/main.cpp b/examples/tutorials/modelview/3_changingmodel/main.cpp index 7be212e..3b6061a 100755 --- a/examples/tutorials/modelview/3_changingmodel/main.cpp +++ b/examples/tutorials/modelview/3_changingmodel/main.cpp @@ -39,12 +39,15 @@ ****************************************************************************/ #include -#include "modelview.h" +#include +#include "mymodel.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); - ModelView w; - w.show(); + QTableView tableView; + MyModel myModel(0); + tableView.setModel( &myModel ); + tableView.show(); return a.exec(); } diff --git a/examples/tutorials/modelview/4_headers/main.cpp b/examples/tutorials/modelview/4_headers/main.cpp index 7be212e..5f5d05f 100755 --- a/examples/tutorials/modelview/4_headers/main.cpp +++ b/examples/tutorials/modelview/4_headers/main.cpp @@ -39,12 +39,15 @@ ****************************************************************************/ #include -#include "modelview.h" +#include +#include "mymodel.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); - ModelView w; - w.show(); + QTableView tableView; + MyModel myModel(0); + tableView.setModel( &myModel ); + tableView.show(); return a.exec(); -} +} \ No newline at end of file -- cgit v0.12 From e566660e222ea194c97c19c26dcb69b5d29ea90c Mon Sep 17 00:00:00 2001 From: Lorn Potter Date: Tue, 24 Aug 2010 13:49:31 +1000 Subject: add ofono support and fix crashes ofono support is needed to know what kind of cellular networks are available. --- src/plugins/bearer/connman/connman.pro | 2 + src/plugins/bearer/connman/qconnmanengine.cpp | 162 ++-- src/plugins/bearer/connman/qconnmanengine.h | 3 +- .../bearer/connman/qconnmanservice_linux.cpp | 9 +- .../bearer/connman/qconnmanservice_linux_p.h | 1 + src/plugins/bearer/connman/qofonoservice_linux.cpp | 940 +++++++++++++++++++++ src/plugins/bearer/connman/qofonoservice_linux_p.h | 332 ++++++++ 7 files changed, 1393 insertions(+), 56 deletions(-) create mode 100644 src/plugins/bearer/connman/qofonoservice_linux.cpp create mode 100644 src/plugins/bearer/connman/qofonoservice_linux_p.h diff --git a/src/plugins/bearer/connman/connman.pro b/src/plugins/bearer/connman/connman.pro index 4be752b..dec408c 100644 --- a/src/plugins/bearer/connman/connman.pro +++ b/src/plugins/bearer/connman/connman.pro @@ -4,12 +4,14 @@ include(../../qpluginbase.pri) QT = core network dbus HEADERS += qconnmanservice_linux_p.h \ + qofonoservice_linux_p.h \ qconnmanengine.h \ ../qnetworksession_impl.h \ ../qbearerengine_impl.h SOURCES += main.cpp \ qconnmanservice_linux.cpp \ + qofonoservice_linux.cpp \ qconnmanengine.cpp \ ../qnetworksession_impl.cpp diff --git a/src/plugins/bearer/connman/qconnmanengine.cpp b/src/plugins/bearer/connman/qconnmanengine.cpp index 341f7cd..a8b8911 100644 --- a/src/plugins/bearer/connman/qconnmanengine.cpp +++ b/src/plugins/bearer/connman/qconnmanengine.cpp @@ -41,6 +41,7 @@ #include "qconnmanengine.h" #include "qconnmanservice_linux_p.h" +#include "qofonoservice_linux_p.h" #include "../qnetworksession_impl.h" #include @@ -109,7 +110,6 @@ void QConnmanEngine::initialize() QList QConnmanEngine::getConfigurations() { QMutexLocker locker(&mutex); - // foundConfigurations.clear(); getNetworkListing(); QList fetchedConfigurations; QNetworkConfigurationPrivate* cpPriv = 0; @@ -131,7 +131,6 @@ QList QConnmanEngine::getConfigurations() delete config; } return fetchedConfigurations; -// return foundConfigurations; } void QConnmanEngine::getNetworkListing() @@ -149,7 +148,6 @@ void QConnmanEngine::getNetworkListing() } } - void QConnmanEngine::doRequestUpdate() { connmanManager->requestScan(""); @@ -184,11 +182,24 @@ void QConnmanEngine::connectToId(const QString &id) void QConnmanEngine::disconnectFromId(const QString &id) { QMutexLocker locker(&mutex); - QConnmanServiceInterface serv(serviceFromId(id)); + QString servicePath = serviceFromId(id); + QConnmanServiceInterface serv(servicePath); if(!serv.isValid()) { emit connectionError(id, DisconnectionError); } else { - serv.disconnect(); + if(serv.getType() != "cellular") { + serv.disconnect(); + } else { + QOfonoManagerInterface ofonoManager(0); + QString modemPath = ofonoManager.currentModem().path(); + QOfonoDataConnectionManagerInterface dc(modemPath,0); + foreach(const QDBusObjectPath dcPath,dc.getPrimaryContexts()) { + if(dcPath.path().contains(servicePath.section("_",-1))) { + QOfonoPrimaryDataContextInterface primaryContext(dcPath.path(),0); + primaryContext.setActive(false); + } + } + } } } @@ -324,7 +335,6 @@ QString QConnmanEngine::getServiceForNetwork(const QString &netPath) return QString(); } - void QConnmanEngine::propertyChangedContext(const QString &path,const QString &item, const QDBusVariant &value) { Q_UNUSED(path); @@ -376,7 +386,7 @@ void QConnmanEngine::servicePropertyChangedContext(const QString &path,const QSt } } -void QConnmanEngine::networkPropertyChangedContext(const QString &path,const QString &item, const QDBusVariant &value) +void QConnmanEngine::networkPropertyChangedContext(const QString &/*path*/,const QString &/*item*/, const QDBusVariant &/*value*/) { QMutexLocker locker(&mutex); } @@ -388,7 +398,6 @@ void QConnmanEngine::devicePropertyChangedContext(const QString &devpath,const Q QConnmanNetworkInterface network(devpath, this); - QDBusArgument arg = qvariant_cast(value.variant()); QStringList remainingNetworks = qdbus_cast(arg); QString devicetype; @@ -502,10 +511,18 @@ QNetworkConfiguration::StateFlags QConnmanEngine::getStateForService(const QStri QMutexLocker locker(&mutex); QConnmanServiceInterface serv(service); QNetworkConfiguration::StateFlags flag = QNetworkConfiguration::Defined; - if(serv.isFavorite()) { - flag = ( flag | QNetworkConfiguration::Discovered); + if( serv.getType() == "cellular") { + if(serv.isSetupRequired()) { + flag = ( flag | QNetworkConfiguration::Defined); + } else { + flag = ( flag | QNetworkConfiguration::Discovered); + } } else { - flag = QNetworkConfiguration::Undefined; + if(serv.isFavorite()) { + flag = ( flag | QNetworkConfiguration::Discovered); + } else { + flag = QNetworkConfiguration::Undefined; + } } if(serv.getState() == "ready" || serv.getState() == "online") { @@ -524,8 +541,7 @@ QNetworkConfiguration::BearerType QConnmanEngine::typeToBearer(const QString &ty if (type == "bluetooth") return QNetworkConfiguration::BearerBluetooth; if (type == "cellular") { - return QNetworkConfiguration::Bearer2G; - // not handled: CDMA2000 HSPA + return ofonoTechToBearerType(type); } if (type == "wimax") return QNetworkConfiguration::BearerWiMAX; @@ -536,6 +552,51 @@ QNetworkConfiguration::BearerType QConnmanEngine::typeToBearer(const QString &ty return QNetworkConfiguration::BearerUnknown; } +QNetworkConfiguration::BearerType QConnmanEngine::ofonoTechToBearerType(const QString &/*type*/) +{ + QOfonoManagerInterface ofonoManager(this); + QOfonoNetworkRegistrationInterface ofonoNetwork(ofonoManager.currentModem().path(),this); + + if(ofonoNetwork.isValid()) { + foreach(const QDBusObjectPath op,ofonoNetwork.getOperators() ) { + QOfonoNetworkOperatorInterface opIface(op.path(),this); + + foreach(const QString opTech, opIface.getTechnologies()) { + + if(opTech == "gsm") { + return QNetworkConfiguration::Bearer2G; + } + if(opTech == "edge"){ + return QNetworkConfiguration::BearerCDMA2000; //wrong, I know + } + if(opTech == "umts"){ + return QNetworkConfiguration::BearerWCDMA; + } + if(opTech == "hspa"){ + return QNetworkConfiguration::BearerHSPA; + } + if(opTech == "lte"){ + return QNetworkConfiguration::BearerWiMAX; //not exact + } + } + } + } + return QNetworkConfiguration::BearerUnknown; +} + +bool QConnmanEngine::isRoamingAllowed(const QString &context) +{ + QOfonoManagerInterface ofonoManager(this); + QString modemPath = ofonoManager.currentModem().path(); + QOfonoDataConnectionManagerInterface dc(modemPath,this); + foreach(const QDBusObjectPath dcPath,dc.getPrimaryContexts()) { + if(dcPath.path().contains(context.section("_",-1))) { + return dc.isRoamingAllowed(); + } + } + return false; +} + void QConnmanEngine::removeConfiguration(const QString &id) { QMutexLocker locker(&mutex); @@ -564,7 +625,6 @@ void QConnmanEngine::removeConfiguration(const QString &id) void QConnmanEngine::addServiceConfiguration(const QString &servicePath) { - QMutexLocker locker(&mutex); QConnmanServiceInterface *serv; serv = new QConnmanServiceInterface(servicePath); @@ -589,36 +649,31 @@ void QConnmanEngine::addServiceConfiguration(const QString &servicePath) QString networkName = serv->getName(); - if(serv->getType() == "cellular") { - networkName = serv->getAPN(); - if(networkName.isEmpty()) { - networkName = serv->getName(); - } - } - - cpPriv->name = networkName; - cpPriv->isValid = true; - cpPriv->id = id; - cpPriv->type = QNetworkConfiguration::InternetAccessPoint; - - const QString connectionType = serv->getType(); if (connectionType == "ethernet") { cpPriv->bearerType = QNetworkConfiguration::BearerEthernet; } else if (connectionType == "wifi") { cpPriv->bearerType = QNetworkConfiguration::BearerWLAN; } else if (connectionType == "cellular") { - const QString mode = serv->getMode(); - if (mode == "gprs" || mode == "edge") - cpPriv->bearerType = QNetworkConfiguration::Bearer2G; - else if (mode == "umts") - cpPriv->bearerType = QNetworkConfiguration::BearerWCDMA; + cpPriv->bearerType = ofonoTechToBearerType("cellular"); + if(servicePath.isEmpty()) { + networkName = serv->getAPN(); + if(networkName.isEmpty()) { + networkName = serv->getName(); + } + } + cpPriv->roamingSupported = isRoamingAllowed(servicePath); } else if (connectionType == "wimax") { cpPriv->bearerType = QNetworkConfiguration::BearerWiMAX; } else { cpPriv->bearerType = QNetworkConfiguration::BearerUnknown; } + cpPriv->name = networkName; + cpPriv->isValid = true; + cpPriv->id = id; + cpPriv->type = QNetworkConfiguration::InternetAccessPoint; + if(serv->getSecurity() == "none") { cpPriv->purpose = QNetworkConfiguration::PublicPurpose; } else { @@ -635,7 +690,6 @@ void QConnmanEngine::addServiceConfiguration(const QString &servicePath) foundConfigurations.append(cpPriv); configInterfaces[cpPriv->id] = device.getInterface(); - locker.unlock(); emit configurationAdded(ptr); locker.relock(); @@ -646,7 +700,6 @@ void QConnmanEngine::addServiceConfiguration(const QString &servicePath) void QConnmanEngine::addNetworkConfiguration(const QString &networkPath) { QMutexLocker locker(&mutex); - if(networkPath.isNull()) return; @@ -662,10 +715,9 @@ void QConnmanEngine::addNetworkConfiguration(const QString &networkPath) id = QString::number(qHash(networkPath)); } else { id = QString::number(qHash(servicePath)); - serv = new QConnmanServiceInterface(servicePath,this); - connect(serv,SIGNAL(propertyChangedContext(QString,QString,QDBusVariant)), - this,SLOT(servicePropertyChangedContext(QString,QString, QDBusVariant))); - + serv = new QConnmanServiceInterface(servicePath,this); + connect(serv,SIGNAL(propertyChangedContext(QString,QString,QDBusVariant)), + this,SLOT(servicePropertyChangedContext(QString,QString, QDBusVariant))); } if (!id.isEmpty() && !accessPointConfigurations.contains(id)) { @@ -684,7 +736,6 @@ void QConnmanEngine::addNetworkConfiguration(const QString &networkPath) if(networkName.isEmpty()) networkName = "Hidden Network"; - QNetworkConfiguration::BearerType bearerType; if(servicePath.isEmpty()) { @@ -693,21 +744,14 @@ void QConnmanEngine::addNetworkConfiguration(const QString &networkPath) QConnmanDeviceInterface device(devicePath,this); bearerType = typeToBearer(device.getType()); } else { - bearerType = typeToBearer(serv->getType()); - } - - if (bearerType == QNetworkConfiguration::Bearer2G) { - QString mode = serv->getMode(); - if (mode == "gprs" || mode == "edge") { - bearerType = QNetworkConfiguration::Bearer2G; - } else if (mode == "umts") { - bearerType = QNetworkConfiguration::BearerWCDMA; - } - if(servicePath.isEmpty()) { - networkName = serv->getAPN(); - if(networkName.isEmpty()) { + if(serv->getType() == "cellular") { + bearerType = ofonoTechToBearerType("cellular"); + if(servicePath.isEmpty()) { networkName = serv->getName(); } + cpPriv->roamingSupported = isRoamingAllowed(servicePath); + } else { + bearerType = typeToBearer(serv->getType()); } } @@ -775,7 +819,19 @@ void QConnmanConnectThread::run() if(!serv.isValid()) { emit connectionError(identifier, QBearerEngineImpl::InterfaceLookupError); } else { - serv.connect(); + if(serv.getType() != "cellular") { + serv.connect(); + } else { + QOfonoManagerInterface ofonoManager(0); + QString modemPath = ofonoManager.currentModem().path(); + QOfonoDataConnectionManagerInterface dc(modemPath,0); + foreach(const QDBusObjectPath dcPath,dc.getPrimaryContexts()) { + if(dcPath.path().contains(servicePath.section("_",-1))) { + QOfonoPrimaryDataContextInterface primaryContext(dcPath.path(),0); + primaryContext.setActive(true); + } + } + } } } diff --git a/src/plugins/bearer/connman/qconnmanengine.h b/src/plugins/bearer/connman/qconnmanengine.h index 2ee6da5..569bbc7 100644 --- a/src/plugins/bearer/connman/qconnmanengine.h +++ b/src/plugins/bearer/connman/qconnmanengine.h @@ -137,7 +137,8 @@ private: QMap deviceMap; //tech path, device path QMap serviceNetworks; //service, network - + QNetworkConfiguration::BearerType ofonoTechToBearerType(const QString &type); + bool isRoamingAllowed(const QString &context); protected: bool requiresPolling() const; QConnmanConnectThread *connThread; diff --git a/src/plugins/bearer/connman/qconnmanservice_linux.cpp b/src/plugins/bearer/connman/qconnmanservice_linux.cpp index 3722c43..549a07a 100644 --- a/src/plugins/bearer/connman/qconnmanservice_linux.cpp +++ b/src/plugins/bearer/connman/qconnmanservice_linux.cpp @@ -984,12 +984,17 @@ QConnmanCounterInterface::~QConnmanCounterInterface() quint32 QConnmanCounterInterface::getReceivedByteCount() { -return 0; + return 0; } quint32 QConnmanCounterInterface::getTransmittedByteCount() { -return 0; + return 0; +} + +quint64 QConnmanCounterInterface::getTimeOnline() +{ + return 0; } ///////////////////////////////////////// diff --git a/src/plugins/bearer/connman/qconnmanservice_linux_p.h b/src/plugins/bearer/connman/qconnmanservice_linux_p.h index a2b1e73..6e6b702 100644 --- a/src/plugins/bearer/connman/qconnmanservice_linux_p.h +++ b/src/plugins/bearer/connman/qconnmanservice_linux_p.h @@ -331,6 +331,7 @@ public: QString getInterface(); quint32 getReceivedByteCount(); quint32 getTransmittedByteCount(); + quint64 getTimeOnline(); private: QConnmanCounterInterfacePrivate *d; diff --git a/src/plugins/bearer/connman/qofonoservice_linux.cpp b/src/plugins/bearer/connman/qofonoservice_linux.cpp new file mode 100644 index 0000000..955f4b1 --- /dev/null +++ b/src/plugins/bearer/connman/qofonoservice_linux.cpp @@ -0,0 +1,940 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the plugins of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "qofonoservice_linux_p.h" + + +QT_BEGIN_NAMESPACE +static QDBusConnection dbusConnection = QDBusConnection::systemBus(); + + +QOfonoManagerInterface::QOfonoManagerInterface( QObject *parent) + : QDBusAbstractInterface(QLatin1String(OFONO_SERVICE), + QLatin1String(OFONO_MANAGER_PATH), + OFONO_MANAGER_INTERFACE, + QDBusConnection::systemBus(), parent) +{ +} + +QOfonoManagerInterface::~QOfonoManagerInterface() +{ +} + +QList QOfonoManagerInterface::getModems() +{ + QVariant var = getProperty("Modems"); + return qdbus_cast >(var); +} + +QDBusObjectPath QOfonoManagerInterface::currentModem() +{ + QList modems = getModems(); + foreach(const QDBusObjectPath modem, modems) { + QOfonoModemInterface device(modem.path()); + if(device.isPowered() && device.isOnline()) + return modem;; + } + return QDBusObjectPath(); +} + + +void QOfonoManagerInterface::connectNotify(const char *signal) +{ +if (QLatin1String(signal) == SIGNAL(propertyChanged(QString,QDBusVariant))) { + if(!connection().connect(QLatin1String(OFONO_SERVICE), + QLatin1String(OFONO_MANAGER_PATH), + QLatin1String(OFONO_MANAGER_INTERFACE), + QLatin1String("PropertyChanged"), + this,SIGNAL(propertyChanged(const QString &, const QDBusVariant & )))) { + qWarning() << "PropertyCHanged not connected"; + } + } + + if (QLatin1String(signal) == SIGNAL(propertyChangedContext(QString,QString,QDBusVariant))) { + QOfonoDBusHelper *helper; + helper = new QOfonoDBusHelper(this); + + dbusConnection.connect(QLatin1String(OFONO_SERVICE), + QLatin1String(OFONO_MANAGER_PATH), + QLatin1String(OFONO_MANAGER_INTERFACE), + QLatin1String("PropertyChanged"), + helper,SLOT(propertyChanged(QString,QDBusVariant))); + + + QObject::connect(helper,SIGNAL(propertyChangedContext(const QString &,const QString &,const QDBusVariant &)), + this,SIGNAL(propertyChangedContext(const QString &,const QString &,const QDBusVariant &))); + } +} + +void QOfonoManagerInterface::disconnectNotify(const char *signal) +{ + if (QLatin1String(signal) == SIGNAL(propertyChanged(QString,QVariant))) { + + } +} + +QVariant QOfonoManagerInterface::getProperty(const QString &property) +{ + QVariantMap map = getProperties(); + if (map.contains(property)) { + return map.value(property); + } else { + qDebug() << Q_FUNC_INFO << "does not contain" << property; + } + return QVariant(); +} + +QVariantMap QOfonoManagerInterface::getProperties() +{ + QDBusReply reply = this->call(QLatin1String("GetProperties")); + if(reply.isValid()) + return reply.value(); + else + return QVariantMap(); +} + +QOfonoDBusHelper::QOfonoDBusHelper(QObject * parent) + : QObject(parent) +{ +} + +QOfonoDBusHelper::~QOfonoDBusHelper() +{ +} + +void QOfonoDBusHelper::propertyChanged(const QString &item, const QDBusVariant &var) +{ + QDBusMessage msg = this->message(); + Q_EMIT propertyChangedContext(msg.path() ,item, var); +} + + +QOfonoModemInterface::QOfonoModemInterface(const QString &dbusPathName, QObject *parent) + : QDBusAbstractInterface(QLatin1String(OFONO_SERVICE), + dbusPathName, + OFONO_MODEM_INTERFACE, + QDBusConnection::systemBus(), parent) +{ +} + +QOfonoModemInterface::~QOfonoModemInterface() +{ +} + +bool QOfonoModemInterface::isPowered() +{ + QVariant var = getProperty("Powered"); + return qdbus_cast(var); +} + +bool QOfonoModemInterface::isOnline() +{ + QVariant var = getProperty("Online"); + return qdbus_cast(var); +} + +QString QOfonoModemInterface::getName() +{ + QVariant var = getProperty("Name"); + return qdbus_cast(var); +} + +QString QOfonoModemInterface::getManufacturer() +{ + QVariant var = getProperty("Manufacturer"); + return qdbus_cast(var); + +} + +QString QOfonoModemInterface::getModel() +{ + + QVariant var = getProperty("Model"); + return qdbus_cast(var); +} + +QString QOfonoModemInterface::getRevision() +{ + QVariant var = getProperty("Revision"); + return qdbus_cast(var); + +} +QString QOfonoModemInterface::getSerial() +{ + QVariant var = getProperty("Serial"); + return qdbus_cast(var); + +} + +QStringList QOfonoModemInterface::getFeatures() +{ + //sms, sim + QVariant var = getProperty("Features"); + return qdbus_cast(var); +} + +QStringList QOfonoModemInterface::getInterfaces() +{ + QVariant var = getProperty("Interfaces"); + return qdbus_cast(var); +} + +QString QOfonoModemInterface::defaultInterface() +{ + foreach(const QString &modem,getInterfaces()) { + return modem; + } + return QString(); +} + + +void QOfonoModemInterface::connectNotify(const char *signal) +{ + if (QLatin1String(signal) == SIGNAL(propertyChanged(QString,QDBusVariant))) { + if(!connection().connect(QLatin1String(OFONO_SERVICE), + this->path(), + QLatin1String(OFONO_MODEM_INTERFACE), + QLatin1String("PropertyChanged"), + this,SIGNAL(propertyChanged(const QString &, const QDBusVariant & )))) { + qWarning() << "PropertyCHanged not connected"; + } + } + + if (QLatin1String(signal) == SIGNAL(propertyChangedContext(QString,QString,QDBusVariant))) { + QOfonoDBusHelper *helper; + helper = new QOfonoDBusHelper(this); + + dbusConnection.connect(QLatin1String(OFONO_SERVICE), + this->path(), + QLatin1String(OFONO_MODEM_INTERFACE), + QLatin1String("PropertyChanged"), + helper,SLOT(propertyChanged(QString,QDBusVariant))); + + + QObject::connect(helper,SIGNAL(propertyChangedContext(const QString &,const QString &,const QDBusVariant &)), + this,SIGNAL(propertyChangedContext(const QString &,const QString &,const QDBusVariant &))); + }} + +void QOfonoModemInterface::disconnectNotify(const char *signal) +{ + if (QLatin1String(signal) == SIGNAL(propertyChanged(QString,QVariant))) { + + } +} + +QVariantMap QOfonoModemInterface::getProperties() +{ + QDBusReply reply = this->call(QLatin1String("GetProperties")); + return reply.value(); +} + +QVariant QOfonoModemInterface::getProperty(const QString &property) +{ + QVariant var; + QVariantMap map = getProperties(); + if (map.contains(property)) { + var = map.value(property); + } else { + qDebug() << Q_FUNC_INFO << "does not contain" << property; + } + return var; +} + + +QOfonoNetworkRegistrationInterface::QOfonoNetworkRegistrationInterface(const QString &dbusPathName, QObject *parent) + : QDBusAbstractInterface(QLatin1String(OFONO_SERVICE), + dbusPathName, + OFONO_NETWORK_REGISTRATION_INTERFACE, + QDBusConnection::systemBus(), parent) +{ +} + +QOfonoNetworkRegistrationInterface::~QOfonoNetworkRegistrationInterface() +{ +} + +QString QOfonoNetworkRegistrationInterface::getStatus() +{ + /* + "unregistered" Not registered to any network + "registered" Registered to home network + "searching" Not registered, but searching + "denied" Registration has been denied + "unknown" Status is unknown + "roaming" Registered, but roaming*/ + QVariant var = getProperty("Status"); + return qdbus_cast(var); +} + +quint16 QOfonoNetworkRegistrationInterface::getLac() +{ + QVariant var = getProperty("LocationAreaCode"); + return var.value(); +} + + +quint32 QOfonoNetworkRegistrationInterface::getCellId() +{ + QVariant var = getProperty("CellId"); + return var.value(); +} + +QString QOfonoNetworkRegistrationInterface::getTechnology() +{ + // "gsm", "edge", "umts", "hspa","lte" + QVariant var = getProperty("Technology"); + return qdbus_cast(var); +} + +QString QOfonoNetworkRegistrationInterface::getOperatorName() +{ + QVariant var = getProperty("Name"); + return qdbus_cast(var); +} + +int QOfonoNetworkRegistrationInterface::getSignalStrength() +{ + QVariant var = getProperty("Strength"); + return qdbus_cast(var); + +} + +QString QOfonoNetworkRegistrationInterface::getBaseStation() +{ + QVariant var = getProperty("BaseStation"); + return qdbus_cast(var); +} + +QList QOfonoNetworkRegistrationInterface::getOperators() +{ + QVariant var = getProperty("Operators"); + return qdbus_cast >(var); +} + +void QOfonoNetworkRegistrationInterface::connectNotify(const char *signal) +{ +if (QLatin1String(signal) == SIGNAL(propertyChanged(QString,QDBusVariant))) { + if(!connection().connect(QLatin1String(OFONO_SERVICE), + this->path(), + QLatin1String(OFONO_NETWORK_REGISTRATION_INTERFACE), + QLatin1String("PropertyChanged"), + this,SIGNAL(propertyChanged(const QString &, const QDBusVariant & )))) { + qWarning() << "PropertyCHanged not connected"; + } + } + + if (QLatin1String(signal) == SIGNAL(propertyChangedContext(QString,QString,QDBusVariant))) { + QOfonoDBusHelper *helper; + helper = new QOfonoDBusHelper(this); + + dbusConnection.connect(QLatin1String(OFONO_SERVICE), + this->path(), + QLatin1String(OFONO_NETWORK_REGISTRATION_INTERFACE), + QLatin1String("PropertyChanged"), + helper,SLOT(propertyChanged(QString,QDBusVariant))); + + + QObject::connect(helper,SIGNAL(propertyChangedContext(const QString &,const QString &,const QDBusVariant &)), + this,SIGNAL(propertyChangedContext(const QString &,const QString &,const QDBusVariant &))); + } +} + +void QOfonoNetworkRegistrationInterface::disconnectNotify(const char *signal) +{ + if (QLatin1String(signal) == SIGNAL(propertyChanged(QString,QVariant))) { + + } +} + +QVariant QOfonoNetworkRegistrationInterface::getProperty(const QString &property) +{ + QVariant var; + QVariantMap map = getProperties(); + if (map.contains(property)) { + var = map.value(property); + } else { + qDebug() << Q_FUNC_INFO << "does not contain" << property; + } + return var; +} + +QVariantMap QOfonoNetworkRegistrationInterface::getProperties() +{ + QDBusReply reply = this->call(QLatin1String("GetProperties")); + return reply.value(); +} + + + +QOfonoNetworkOperatorInterface::QOfonoNetworkOperatorInterface(const QString &dbusPathName, QObject *parent) + : QDBusAbstractInterface(QLatin1String(OFONO_SERVICE), + dbusPathName, + OFONO_NETWORK_OPERATOR_INTERFACE, + QDBusConnection::systemBus(), parent) +{ +} + +QOfonoNetworkOperatorInterface::~QOfonoNetworkOperatorInterface() +{ +} + +QString QOfonoNetworkOperatorInterface::getName() +{ + QVariant var = getProperty("Name"); + return qdbus_cast(var); +} + +QString QOfonoNetworkOperatorInterface::getStatus() +{ + // "unknown", "available", "current" and "forbidden" + QVariant var = getProperty("Status"); + return qdbus_cast(var); +} + +QString QOfonoNetworkOperatorInterface::getMcc() +{ + QVariant var = getProperty("MobileCountryCode"); + return qdbus_cast(var); +} + +QString QOfonoNetworkOperatorInterface::getMnc() +{ + QVariant var = getProperty("MobileNetworkCode"); + return qdbus_cast(var); +} + +QStringList QOfonoNetworkOperatorInterface::getTechnologies() +{ + QVariant var = getProperty("Technologies"); + return qdbus_cast(var); +} + +void QOfonoNetworkOperatorInterface::connectNotify(const char *signal) +{ +if (QLatin1String(signal) == SIGNAL(propertyChanged(QString,QDBusVariant))) { + if(!connection().connect(QLatin1String(OFONO_SERVICE), + this->path(), + QLatin1String(OFONO_NETWORK_OPERATOR_INTERFACE), + QLatin1String("PropertyChanged"), + this,SIGNAL(propertyChanged(const QString &, const QDBusVariant & )))) { + qWarning() << "PropertyCHanged not connected"; + } + } + + if (QLatin1String(signal) == SIGNAL(propertyChangedContext(QString,QString,QDBusVariant))) { + QOfonoDBusHelper *helper; + helper = new QOfonoDBusHelper(this); + + dbusConnection.connect(QLatin1String(OFONO_SERVICE), + this->path(), + QLatin1String(OFONO_NETWORK_OPERATOR_INTERFACE), + QLatin1String("PropertyChanged"), + helper,SLOT(propertyChanged(QString,QDBusVariant))); + + + QObject::connect(helper,SIGNAL(propertyChangedContext(const QString &,const QString &,const QDBusVariant &)), + this,SIGNAL(propertyChangedContext(const QString &,const QString &,const QDBusVariant &))); + } +} + +void QOfonoNetworkOperatorInterface::disconnectNotify(const char *signal) +{ + if (QLatin1String(signal) == SIGNAL(propertyChanged(QString,QVariant))) { + + } +} + +QVariant QOfonoNetworkOperatorInterface::getProperty(const QString &property) +{ + QVariant var; + QVariantMap map = getProperties(); + if (map.contains(property)) { + var = map.value(property); + } else { + qDebug() << Q_FUNC_INFO << "does not contain" << property; + } + return var; +} + +QVariantMap QOfonoNetworkOperatorInterface::getProperties() +{ + QDBusReply reply = this->call(QLatin1String("GetProperties")); + return reply.value(); +} + +QOfonoSimInterface::QOfonoSimInterface(const QString &dbusPathName, QObject *parent) + : QDBusAbstractInterface(QLatin1String(OFONO_SERVICE), + dbusPathName, + OFONO_SIM_MANAGER_INTERFACE, + QDBusConnection::systemBus(), parent) +{ +} + +QOfonoSimInterface::~QOfonoSimInterface() +{ +} + +bool QOfonoSimInterface::isPresent() +{ + QVariant var = getProperty("Present"); + return qdbus_cast(var); +} + +QString QOfonoSimInterface::getHomeMcc() +{ + QVariant var = getProperty("MobileCountryCode"); + return qdbus_cast(var); +} + +QString QOfonoSimInterface::getHomeMnc() +{ + QVariant var = getProperty("MobileNetworkCode"); + return qdbus_cast(var); +} + +// QStringList subscriberNumbers(); +// QMap serviceNumbers(); +QString QOfonoSimInterface::pinRequired() +{ + QVariant var = getProperty("PinRequired"); + return qdbus_cast(var); +} + +QString QOfonoSimInterface::lockedPins() +{ + QVariant var = getProperty("LockedPins"); + return qdbus_cast(var); +} + +QString QOfonoSimInterface::cardIdentifier() +{ + QVariant var = getProperty("CardIdentifier"); + return qdbus_cast(var); +} + +void QOfonoSimInterface::connectNotify(const char *signal) +{ +if (QLatin1String(signal) == SIGNAL(propertyChanged(QString,QDBusVariant))) { + if(!connection().connect(QLatin1String(OFONO_SERVICE), + this->path(), + QLatin1String(OFONO_SIM_MANAGER_INTERFACE), + QLatin1String("PropertyChanged"), + this,SIGNAL(propertyChanged(const QString &, const QDBusVariant & )))) { + qWarning() << "PropertyCHanged not connected"; + } + } + + if (QLatin1String(signal) == SIGNAL(propertyChangedContext(QString,QString,QDBusVariant))) { + QOfonoDBusHelper *helper; + helper = new QOfonoDBusHelper(this); + + dbusConnection.connect(QLatin1String(OFONO_SERVICE), + this->path(), + QLatin1String(OFONO_SIM_MANAGER_INTERFACE), + QLatin1String("PropertyChanged"), + helper,SLOT(propertyChanged(QString,QDBusVariant))); + + + QObject::connect(helper,SIGNAL(propertyChangedContext(const QString &,const QString &,const QDBusVariant &)), + this,SIGNAL(propertyChangedContext(const QString &,const QString &,const QDBusVariant &))); + } +} + +void QOfonoSimInterface::disconnectNotify(const char *signal) +{ + if (QLatin1String(signal) == SIGNAL(propertyChanged(QString,QVariant))) { + + } +} + +QVariant QOfonoSimInterface::getProperty(const QString &property) +{ + QVariant var; + QVariantMap map = getProperties(); + if (map.contains(property)) { + var = map.value(property); + } else { + qDebug() << Q_FUNC_INFO << "does not contain" << property; + } + return var; +} + +QVariantMap QOfonoSimInterface::getProperties() +{ + QDBusReply reply = this->call(QLatin1String("GetProperties")); + return reply.value(); +} + +QOfonoDataConnectionManagerInterface::QOfonoDataConnectionManagerInterface(const QString &dbusPathName, QObject *parent) + : QDBusAbstractInterface(QLatin1String(OFONO_SERVICE), + dbusPathName, + OFONO_DATA_CONNECTION_MANAGER_INTERFACE, + QDBusConnection::systemBus(), parent) +{ +} + +QOfonoDataConnectionManagerInterface::~QOfonoDataConnectionManagerInterface() +{ +} + +QList QOfonoDataConnectionManagerInterface::getPrimaryContexts() +{ + QVariant var = getProperty("PrimaryContexts"); + return qdbus_cast >(var); +} + +bool QOfonoDataConnectionManagerInterface::isAttached() +{ + QVariant var = getProperty("Attached"); + return qdbus_cast(var); +} + +bool QOfonoDataConnectionManagerInterface::isRoamingAllowed() +{ + QVariant var = getProperty("RoamingAllowed"); + return qdbus_cast(var); +} + +bool QOfonoDataConnectionManagerInterface::isPowered() +{ + QVariant var = getProperty("Powered"); + return qdbus_cast(var); +} + +void QOfonoDataConnectionManagerInterface::connectNotify(const char *signal) +{ +if (QLatin1String(signal) == SIGNAL(propertyChanged(QString,QDBusVariant))) { + if(!connection().connect(QLatin1String(OFONO_SERVICE), + this->path(), + QLatin1String(OFONO_DATA_CONNECTION_MANAGER_INTERFACE), + QLatin1String("PropertyChanged"), + this,SIGNAL(propertyChanged(const QString &, const QDBusVariant & )))) { + qWarning() << "PropertyCHanged not connected"; + } + } + + if (QLatin1String(signal) == SIGNAL(propertyChangedContext(QString,QString,QDBusVariant))) { + QOfonoDBusHelper *helper; + helper = new QOfonoDBusHelper(this); + + dbusConnection.connect(QLatin1String(OFONO_SERVICE), + this->path(), + QLatin1String(OFONO_DATA_CONNECTION_MANAGER_INTERFACE), + QLatin1String("PropertyChanged"), + helper,SLOT(propertyChanged(QString,QDBusVariant))); + + + QObject::connect(helper,SIGNAL(propertyChangedContext(const QString &,const QString &,const QDBusVariant &)), + this,SIGNAL(propertyChangedContext(const QString &,const QString &,const QDBusVariant &))); + } +} + +void QOfonoDataConnectionManagerInterface::disconnectNotify(const char *signal) +{ + if (QLatin1String(signal) == SIGNAL(propertyChanged(QString,QVariant))) { + + } +} + +QVariant QOfonoDataConnectionManagerInterface::getProperty(const QString &property) +{ + QVariant var; + QVariantMap map = getProperties(); + if (map.contains(property)) { + var = map.value(property); + } else { + qDebug() << Q_FUNC_INFO << "does not contain" << property; + } + return var; +} + +QVariantMap QOfonoDataConnectionManagerInterface::getProperties() +{ + QDBusReply reply = this->call(QLatin1String("GetProperties")); + return reply.value(); +} + +QOfonoPrimaryDataContextInterface::QOfonoPrimaryDataContextInterface(const QString &dbusPathName, QObject *parent) + : QDBusAbstractInterface(QLatin1String(OFONO_SERVICE), + dbusPathName, + OFONO_DATA_CONTEXT_INTERFACE, + QDBusConnection::systemBus(), parent) +{ +} + +QOfonoPrimaryDataContextInterface::~QOfonoPrimaryDataContextInterface() +{ +} + +bool QOfonoPrimaryDataContextInterface::isActive() +{ + QVariant var = getProperty("Active"); + return qdbus_cast(var); +} + +QString QOfonoPrimaryDataContextInterface::getApName() +{ + QVariant var = getProperty("AccessPointName"); + return qdbus_cast(var); +} + +QString QOfonoPrimaryDataContextInterface::getType() +{ + QVariant var = getProperty("Type"); + return qdbus_cast(var); +} + +QString QOfonoPrimaryDataContextInterface::getName() +{ + QVariant var = getProperty("Name"); + return qdbus_cast(var); +} + +QVariantMap QOfonoPrimaryDataContextInterface::getSettings() +{ + QVariant var = getProperty("Settings"); + return qdbus_cast(var); +} + +QString QOfonoPrimaryDataContextInterface::getInterface() +{ + QVariant var = getProperty("Interface"); + return qdbus_cast(var); +} + +QString QOfonoPrimaryDataContextInterface::getAddress() +{ + QVariant var = getProperty("Address"); + return qdbus_cast(var); +} + +bool QOfonoPrimaryDataContextInterface::setActive(bool on) +{ +// this->setProperty("Active", QVariant(on)); + + return setProp("Active", qVariantFromValue(on)); +} + +bool QOfonoPrimaryDataContextInterface::setApn(const QString &name) +{ + return setProp("AccessPointName", QVariant::fromValue(name)); +} + +void QOfonoPrimaryDataContextInterface::connectNotify(const char *signal) +{ +if (QLatin1String(signal) == SIGNAL(propertyChanged(QString,QDBusVariant))) { + if(!connection().connect(QLatin1String(OFONO_SERVICE), + this->path(), + QLatin1String(OFONO_DATA_CONTEXT_INTERFACE), + QLatin1String("PropertyChanged"), + this,SIGNAL(propertyChanged(const QString &, const QDBusVariant & )))) { + qWarning() << "PropertyCHanged not connected"; + } + } + + if (QLatin1String(signal) == SIGNAL(propertyChangedContext(QString,QString,QDBusVariant))) { + QOfonoDBusHelper *helper; + helper = new QOfonoDBusHelper(this); + + dbusConnection.connect(QLatin1String(OFONO_SERVICE), + this->path(), + QLatin1String(OFONO_DATA_CONTEXT_INTERFACE), + QLatin1String("PropertyChanged"), + helper,SLOT(propertyChanged(QString,QDBusVariant))); + + + QObject::connect(helper,SIGNAL(propertyChangedContext(const QString &,const QString &,const QDBusVariant &)), + this,SIGNAL(propertyChangedContext(const QString &,const QString &,const QDBusVariant &))); + } +} + +void QOfonoPrimaryDataContextInterface::disconnectNotify(const char *signal) +{ + if (QLatin1String(signal) == SIGNAL(propertyChanged(QString,QVariant))) { + + } +} + +QVariant QOfonoPrimaryDataContextInterface::getProperty(const QString &property) +{ + QVariant var; + QVariantMap map = getProperties(); + if (map.contains(property)) { + var = map.value(property); + } else { + qDebug() << Q_FUNC_INFO << "does not contain" << property; + } + return var; +} + +QVariantMap QOfonoPrimaryDataContextInterface::getProperties() +{ + QDBusReply reply = this->call(QLatin1String("GetProperties")); + return reply.value(); +} + +bool QOfonoPrimaryDataContextInterface::setProp(const QString &property, const QVariant &var) +{ + QList args; + args << qVariantFromValue(property) << qVariantFromValue(QDBusVariant(var)); + + QDBusMessage reply = this->callWithArgumentList(QDBus::AutoDetect, + QLatin1String("SetProperty"), + args); + bool ok = true; + if(reply.type() != QDBusMessage::ReplyMessage) { + qWarning() << reply.errorMessage(); + ok = false; + } + qWarning() << reply.errorMessage(); + return ok; +} + +QOfonoSmsInterface::QOfonoSmsInterface(const QString &dbusPathName, QObject *parent) + : QDBusAbstractInterface(QLatin1String(OFONO_SERVICE), + dbusPathName, + OFONO_SMS_MANAGER_INTERFACE, + QDBusConnection::systemBus(), parent) +{ +} + +QOfonoSmsInterface::~QOfonoSmsInterface() +{ +} + +void QOfonoSmsInterface::connectNotify(const char *signal) +{ + if (QLatin1String(signal) == SIGNAL(propertyChanged(QString,QDBusVariant))) { + if(!connection().connect(QLatin1String(OFONO_SERVICE), + this->path(), + QLatin1String(OFONO_SMS_MANAGER_INTERFACE), + QLatin1String("PropertyChanged"), + this,SIGNAL(propertyChanged(const QString &, const QDBusVariant & )))) { + qWarning() << "PropertyCHanged not connected"; + } + } + + if (QLatin1String(signal) == SIGNAL(propertyChangedContext(QString,QString,QDBusVariant))) { + QOfonoDBusHelper *helper; + helper = new QOfonoDBusHelper(this); + + dbusConnection.connect(QLatin1String(OFONO_SERVICE), + this->path(), + QLatin1String(OFONO_SMS_MANAGER_INTERFACE), + QLatin1String("PropertyChanged"), + helper,SLOT(propertyChanged(QString,QDBusVariant))); + + + QObject::connect(helper,SIGNAL(propertyChangedContext(const QString &,const QString &,const QDBusVariant &)), + this,SIGNAL(propertyChangedContext(const QString &,const QString &,const QDBusVariant &))); + } + + if (QLatin1String(signal) == SIGNAL(immediateMessage(QString,QVariantMap))) { + if(!connection().connect(QLatin1String(OFONO_SERVICE), + this->path(), + QLatin1String(OFONO_SMS_MANAGER_INTERFACE), + QLatin1String("ImmediateMessage"), + this,SIGNAL(immediateMessage(QString,QVariantMap )))) { + qWarning() << "PropertyCHanged not connected"; + } + } + + if (QLatin1String(signal) == SIGNAL(incomingMessage(QString,QVariantMap))) { + if(!connection().connect(QLatin1String(OFONO_SERVICE), + this->path(), + QLatin1String(OFONO_SMS_MANAGER_INTERFACE), + QLatin1String("IncomingMessage"), + this,SIGNAL(incomingMessage(QString,QVariantMap)))) { + qWarning() << "PropertyCHanged not connected"; + } + } +} + +void QOfonoSmsInterface::disconnectNotify(const char *signal) +{ + if (QLatin1String(signal) == SIGNAL(propertyChanged(QString,QVariant))) { + + } +} + +QVariant QOfonoSmsInterface::getProperty(const QString &property) +{ + QVariant var; + QVariantMap map = getProperties(); + if (map.contains(property)) { + var = map.value(property); + } else { + qDebug() << Q_FUNC_INFO << "does not contain" << property; + } + return var; +} + +QVariantMap QOfonoSmsInterface::getProperties() +{ + QDBusReply reply = this->call(QLatin1String("GetProperties")); + return reply.value(); +} + +void QOfonoSmsInterface::sendMessage(const QString &to, const QString &message) +{ + QDBusReply reply = this->call(QLatin1String("SendMessage"), + QVariant::fromValue(to), + QVariant::fromValue(message)); + bool ok = true; + if(reply.error().type() == QDBusError::InvalidArgs) { + qWarning() << reply.error().message(); + ok = false; + } +} + +QT_END_NAMESPACE diff --git a/src/plugins/bearer/connman/qofonoservice_linux_p.h b/src/plugins/bearer/connman/qofonoservice_linux_p.h new file mode 100644 index 0000000..4892666 --- /dev/null +++ b/src/plugins/bearer/connman/qofonoservice_linux_p.h @@ -0,0 +1,332 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the plugins of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QOFONOSERVICE_H +#define QOFONOSERVICE_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#define OFONO_SERVICE "org.ofono" +#define OFONO_MANAGER_INTERFACE "org.ofono.Manager" +#define OFONO_MANAGER_PATH "/" +#define OFONO_MODEM_INTERFACE "org.ofono.Modem" +#define OFONO_NETWORK_REGISTRATION_INTERFACE "org.ofono.NetworkRegistration" +#define OFONO_NETWORK_OPERATOR_INTERFACE "org.ofono.NetworkOperator" +#define OFONO_DATA_CONNECTION_MANAGER_INTERFACE "org.ofono.DataConnectionManager" +#define OFONO_SIM_MANAGER_INTERFACE "org.ofono.SimManager" +#define OFONO_DATA_CONTEXT_INTERFACE "org.ofono.PrimaryDataContext" + +#define OFONO_SMS_MANAGER_INTERFACE "org.ofono.SmsManager" +#define OFONO_PHONEBOOK_INTERFACE "org.ofono.Phonebook" +#define OFONO_MESSAGE_WAITING_INTERFACE "org.ofono.MessageWaiting" + + + +QT_BEGIN_NAMESPACE + +QT_END_NAMESPACE + + +QT_BEGIN_NAMESPACE + +class QOfonoManagerInterface : public QDBusAbstractInterface +{ + Q_OBJECT + +public: + + QOfonoManagerInterface( QObject *parent = 0); + ~QOfonoManagerInterface(); + + QDBusObjectPath path() const; + + QVariantMap getProperties(); + bool setProperty(const QString &name, const QDBusVariant &value); + QList getModems(); + QDBusObjectPath currentModem(); + +Q_SIGNALS: + void propertyChanged(const QString &, const QDBusVariant &value); + void propertyChangedContext(const QString &,const QString &,const QDBusVariant &); +protected: + void connectNotify(const char *signal); + void disconnectNotify(const char *signal); + QVariant getProperty(const QString &); + +}; + + +class QOfonoDBusHelper: public QObject, protected QDBusContext + { + Q_OBJECT + public: + QOfonoDBusHelper(QObject *parent = 0); + ~QOfonoDBusHelper(); + + public slots: + void propertyChanged(const QString &, const QDBusVariant &); + Q_SIGNALS: + void propertyChangedContext(const QString &,const QString &,const QDBusVariant &); +}; + +class QOfonoModemInterface : public QDBusAbstractInterface +{ + Q_OBJECT + +public: + + QOfonoModemInterface(const QString &dbusModemPathName, QObject *parent = 0); + ~QOfonoModemInterface(); + + QVariantMap getProperties(); + //properties + bool isPowered(); + bool isOnline(); + QString getName(); + QString getManufacturer(); + QString getModel(); + QString getRevision(); + QString getSerial(); + + QStringList getFeatures(); //sms, sim + QStringList getInterfaces(); + QString defaultInterface(); + +protected: + void connectNotify(const char *signal); + void disconnectNotify(const char *signal); + QVariant getProperty(const QString &); +Q_SIGNALS: + void propertyChanged(const QString &, const QDBusVariant &value); + void propertyChangedContext(const QString &,const QString &,const QDBusVariant &); +}; + + +class QOfonoNetworkRegistrationInterface : public QDBusAbstractInterface +{ + Q_OBJECT + +public: + + QOfonoNetworkRegistrationInterface(const QString &dbusModemPathName, QObject *parent = 0); + ~QOfonoNetworkRegistrationInterface(); + + QVariantMap getProperties(); + + //properties + QString getStatus(); + quint16 getLac(); + quint32 getCellId(); + QString getTechnology(); + QString getOperatorName(); + int getSignalStrength(); + QString getBaseStation(); + QList getOperators(); + +protected: + void connectNotify(const char *signal); + void disconnectNotify(const char *signal); + QVariant getProperty(const QString &); +Q_SIGNALS: + void propertyChanged(const QString &, const QDBusVariant &value); + void propertyChangedContext(const QString &,const QString &,const QDBusVariant &); + +}; + +class QOfonoNetworkOperatorInterface : public QDBusAbstractInterface +{ + Q_OBJECT + +public: +//modem or operator paths + QOfonoNetworkOperatorInterface(const QString &dbusPathName, QObject *parent = 0); + ~QOfonoNetworkOperatorInterface(); + + QVariantMap getProperties(); + + //properties + QString getName(); + QString getStatus();// "unknown", "available", "current" and "forbidden" + QString getMcc(); + QString getMnc(); + QStringList getTechnologies(); + +protected: + void connectNotify(const char *signal); + void disconnectNotify(const char *signal); + QVariant getProperty(const QString &); +}; + +class QOfonoSimInterface : public QDBusAbstractInterface +{ + Q_OBJECT + +public: + + QOfonoSimInterface(const QString &dbusModemPathName, QObject *parent = 0); + ~QOfonoSimInterface(); + + QVariantMap getProperties(); + + //properties + bool isPresent(); + QString getHomeMcc(); + QString getHomeMnc(); +// QStringList subscriberNumbers(); +// QMap serviceNumbers(); + QString pinRequired(); + QString lockedPins(); + QString cardIdentifier(); + +protected: + void connectNotify(const char *signal); + void disconnectNotify(const char *signal); + QVariant getProperty(const QString &); +}; + + +class QOfonoDataConnectionManagerInterface : public QDBusAbstractInterface +{ + Q_OBJECT + +public: + + QOfonoDataConnectionManagerInterface(const QString &dbusPathName, QObject *parent = 0); + ~QOfonoDataConnectionManagerInterface(); + + QVariantMap getProperties(); + + //properties + QList getPrimaryContexts(); + bool isAttached(); + bool isRoamingAllowed(); + bool isPowered(); + + bool setPower(bool on); + +protected: + void connectNotify(const char *signal); + void disconnectNotify(const char *signal); + QVariant getProperty(const QString &); +}; + + +class QOfonoPrimaryDataContextInterface : public QDBusAbstractInterface +{ + Q_OBJECT + +public: + + QOfonoPrimaryDataContextInterface(const QString &dbusPathName, QObject *parent = 0); + ~QOfonoPrimaryDataContextInterface(); + + QVariantMap getProperties(); + + //properties + bool isActive(); + QString getApName(); + QString getType(); + QString getName(); + QVariantMap getSettings(); + QString getInterface(); + QString getAddress(); + + bool setActive(bool on); + bool setApn(const QString &name); + +protected: + void connectNotify(const char *signal); + void disconnectNotify(const char *signal); + QVariant getProperty(const QString &); + bool setProp(const QString &, const QVariant &var); +}; + +class QOfonoSmsInterface : public QDBusAbstractInterface +{ + Q_OBJECT + +public: + + QOfonoSmsInterface(const QString &dbusModemPathName, QObject *parent = 0); + ~QOfonoSmsInterface(); + + QVariantMap getProperties(); + void sendMessage(const QString &to, const QString &message); + + //properties + QString serviceCenterAddress(); + bool useDeliveryReports(); + QString bearer(); + +protected: + void connectNotify(const char *signal); + void disconnectNotify(const char *signal); + QVariant getProperty(const QString &); + +Q_SIGNALS: + void propertyChanged(const QString &, const QDBusVariant &value); + void propertyChangedContext(const QString &,const QString &,const QDBusVariant &); + void immediateMessage(const QString &message, const QVariantMap &info); + void incomingMessage(const QString &message, const QVariantMap &info); +}; + +#endif //QOFONOSERVICE_H -- cgit v0.12 From b237c17156a1626fada7fad50dc0892f790d6295 Mon Sep 17 00:00:00 2001 From: axis Date: Wed, 25 Aug 2010 15:37:56 +0200 Subject: Fixed sporadically failing autotest on Symbian. It failed because there sometimes is a spike in resource usage just after starting a process. This was fixed by adding a longer wait delay. RevBy: Trust me --- tests/auto/qtimer/tst_qtimer.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/auto/qtimer/tst_qtimer.cpp b/tests/auto/qtimer/tst_qtimer.cpp index 8d213ed..b651187 100644 --- a/tests/auto/qtimer/tst_qtimer.cpp +++ b/tests/auto/qtimer/tst_qtimer.cpp @@ -161,8 +161,9 @@ void tst_QTimer::singleShotTimeout() QCOMPARE(helper.count, 1); } -#if defined(Q_OS_SYMBIAN) && defined(Q_CC_NOKIAX86) -// Increase wait as emulator startup can cause unexpected delays +#if defined(Q_OS_SYMBIAN) +// Increase wait as emulator startup can cause unexpected delays, and +// on hardware there are sometimes spikes right after process startup. #define TIMEOUT_TIMEOUT 2000 #else #define TIMEOUT_TIMEOUT 200 -- cgit v0.12 From b4116c58cacc46732ff24db1ea8bf082fcb4b489 Mon Sep 17 00:00:00 2001 From: Alan Alpert Date: Thu, 26 Aug 2010 13:46:01 +1000 Subject: Maintain high score name dialog length, as well as name. Task-number: QTBUG-13129 --- demos/declarative/samegame/SamegameCore/samegame.js | 3 ++- demos/declarative/samegame/samegame.qml | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/demos/declarative/samegame/SamegameCore/samegame.js b/demos/declarative/samegame/SamegameCore/samegame.js index aa1b359..9266767 100755 --- a/demos/declarative/samegame/SamegameCore/samegame.js +++ b/demos/declarative/samegame/SamegameCore/samegame.js @@ -151,7 +151,8 @@ function victoryCheck() gameDuration = new Date() - gameDuration; nameInputDialog.show("You won! Please enter your name: "); nameInputDialog.initialWidth = nameInputDialog.text.width + 20; - nameInputDialog.width = nameInputDialog.initialWidth; + if(nameInputDialog.name == "") + nameInputDialog.width = nameInputDialog.initialWidth; nameInputDialog.text.opacity = 0;//Just a spacer } } diff --git a/demos/declarative/samegame/samegame.qml b/demos/declarative/samegame/samegame.qml index 9504fb6..3e9c505 100644 --- a/demos/declarative/samegame/samegame.qml +++ b/demos/declarative/samegame/samegame.qml @@ -82,6 +82,7 @@ Rectangle { id: nameInputDialog property int initialWidth: 0 + property alias name: nameInputText.text anchors.centerIn: parent z: 22; -- cgit v0.12 From b247124839db0a25e6200b258e71eb5d7acc033c Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Mon, 30 Aug 2010 16:25:33 +0200 Subject: qdrawhelper: backport the optimisations in fetchTransformBilinear from master to 4.7 This backport the following commits: e55b6a3 qdrawhelper: remove code duplication 0d7e683 qdrawhelper: optimize fetchTransformedBilinear 29ef46e Fix compilation with RVCT 6601458 qdrawhelper: Use SSE2 in fetchTransformedBilinear (when scalling up) 398ef0ca Fix nasty copy-paste bug in fetchTransformedBilinear() d585ece qdrawhelper: fix assert in fetchTransformedBilinear Reviewed-by: Benjamin Poulain --- src/gui/painting/qdrawhelper.cpp | 395 +++++++++++++++++++++++++-------------- 1 file changed, 257 insertions(+), 138 deletions(-) diff --git a/src/gui/painting/qdrawhelper.cpp b/src/gui/painting/qdrawhelper.cpp index be4275c..89754fa 100644 --- a/src/gui/painting/qdrawhelper.cpp +++ b/src/gui/painting/qdrawhelper.cpp @@ -656,6 +656,46 @@ const uint * QT_FASTCALL fetchTransformed(uint *buffer, const Operator *, const return buffer; } +/** \internal + interpolate 4 argb pixels with the distx and disty factor. + distx and disty bust be between 0 and 16 + */ +static inline uint interpolate_4_pixels_16(uint tl, uint tr, uint bl, uint br, int distx, int disty, int idistx, int idisty) +{ + uint tlrb = ((tl & 0x00ff00ff) * idistx * idisty); + uint tlag = (((tl & 0xff00ff00) >> 8) * idistx * idisty); + uint trrb = ((tr & 0x00ff00ff) * distx * idisty); + uint trag = (((tr & 0xff00ff00) >> 8) * distx * idisty); + uint blrb = ((bl & 0x00ff00ff) * idistx * disty); + uint blag = (((bl & 0xff00ff00) >> 8) * idistx * disty); + uint brrb = ((br & 0x00ff00ff) * distx * disty); + uint brag = (((br & 0xff00ff00) >> 8) * distx * disty); + return (((tlrb + trrb + blrb + brrb) >> 8) & 0x00ff00ff) | ((tlag + trag + blag + brag) & 0xff00ff00); +} + + +template +Q_STATIC_TEMPLATE_FUNCTION inline void fetchTransformedBilinear_pixelBounds(int max, int l1, int l2, int &v1, int &v2) +{ + if (blendType == BlendTransformedBilinearTiled) { + v1 %= max; + if (v1 < 0) v1 += max; + v2 = v1 + 1; + v2 %= max; + } else { + if (v1 < l1) { + v2 = v1 = l1; + } else if (v1 >= l2 - 1) { + v2 = v1 = l2 - 1; + } else { + v2 = v1 + 1; + } + } + + Q_ASSERT(v1 >= 0 && v1 < max); + Q_ASSERT(v2 >= 0 && v2 < max); +} + template /* blendType = BlendTransformedBilinear or BlendTransformedBilinearTiled */ Q_STATIC_TEMPLATE_FUNCTION const uint * QT_FASTCALL fetchTransformedBilinear(uint *buffer, const Operator *, const QSpanData *data, @@ -696,64 +736,230 @@ const uint * QT_FASTCALL fetchTransformedBilinear(uint *buffer, const Operator * fx -= half_point; fy -= half_point; - while (b < end) { - int x1 = (fx >> 16); - int x2; + + if (fdy == 0) { //simple scale, no rotation int y1 = (fy >> 16); int y2; + fetchTransformedBilinear_pixelBounds(image_height, image_y1, image_y2, y1, y2); + const uchar *s1 = data->texture.scanLine(y1); + const uchar *s2 = data->texture.scanLine(y2); - if (blendType == BlendTransformedBilinearTiled) { - x1 %= image_width; - if (x1 < 0) x1 += image_width; - x2 = x1 + 1; - x2 %= image_width; - - y1 %= image_height; - if (y1 < 0) y1 += image_height; - y2 = y1 + 1; - y2 %= image_height; - } else { - if (x1 < image_x1) { - x2 = x1 = image_x1; - } else if (x1 >= image_x2 - 1) { - x2 = x1 = image_x2 - 1; + if (fdx <= fixed_scale && fdx > 0) { // scale up on X + int disty = (fy & 0x0000ffff) >> 8; + int idisty = 256 - disty; + int x = fx >> 16; + + // The idea is first to do the interpolation between the row s1 and the row s2 + // into an intermediate buffer, then we interpolate between two pixel of this buffer. + + // intermediate_buffer[0] is a buffer of red-blue component of the pixel, in the form 0x00RR00BB + // intermediate_buffer[1] is the alpha-green component of the pixel, in the form 0x00AA00GG + quint32 intermediate_buffer[2][buffer_size + 2]; + // count is the size used in the intermediate_buffer. + int count = qCeil(length * data->m11) + 2; //+1 for the last pixel to interpolate with, and +1 for rounding errors. + Q_ASSERT(count <= buffer_size + 2); //length is supposed to be <= buffer_size and data->m11 < 1 in this case + int f = 0; + int lim = count; + if (blendType == BlendTransformedBilinearTiled) { + x %= image_width; + if (x < 0) x += image_width; } else { - x2 = x1 + 1; + lim = qMin(count, image_x2-x); + if (x < image_x1) { + Q_ASSERT(x < image_x2); + uint t = fetch(s1, image_x1, data->texture.colorTable); + uint b = fetch(s2, image_x1, data->texture.colorTable); + quint32 rb = (((t & 0xff00ff) * idisty + (b & 0xff00ff) * disty) >> 8) & 0xff00ff; + quint32 ag = ((((t>>8) & 0xff00ff) * idisty + ((b>>8) & 0xff00ff) * disty) >> 8) & 0xff00ff; + do { + intermediate_buffer[0][f] = rb; + intermediate_buffer[1][f] = ag; + f++; + x++; + } while (x < image_x1 && f < lim); + } } - if (y1 < image_y1) { - y2 = y1 = image_y1; - } else if (y1 >= image_y2 - 1) { - y2 = y1 = image_y2 - 1; - } else { - y2 = y1 + 1; + +#if defined(QT_ALWAYS_HAVE_SSE2) + if (blendType != BlendTransformedBilinearTiled && + (format == QImage::Format_ARGB32_Premultiplied || format == QImage::Format_RGB32)) { + + const __m128i disty_ = _mm_set1_epi16(disty); + const __m128i idisty_ = _mm_set1_epi16(idisty); + const __m128i colorMask = _mm_set1_epi32(0x00ff00ff); + + lim -= 3; + for (; f < lim; x += 4, f += 4) { + // Load 4 pixels from s1, and split the alpha-green and red-blue component + __m128i top = _mm_loadu_si128((__m128i*)((const uint *)(s1)+x)); + __m128i topAG = _mm_srli_epi16(top, 8); + __m128i topRB = _mm_and_si128(top, colorMask); + // Multiplies each colour component by idisty + topAG = _mm_mullo_epi16 (topAG, idisty_); + topRB = _mm_mullo_epi16 (topRB, idisty_); + + // Same for the s2 vector + __m128i bottom = _mm_loadu_si128((__m128i*)((const uint *)(s2)+x)); + __m128i bottomAG = _mm_srli_epi16(bottom, 8); + __m128i bottomRB = _mm_and_si128(bottom, colorMask); + bottomAG = _mm_mullo_epi16 (bottomAG, disty_); + bottomRB = _mm_mullo_epi16 (bottomRB, disty_); + + // Add the values, and shift to only keep 8 significant bits per colors + __m128i rAG =_mm_add_epi16(topAG, bottomAG); + rAG = _mm_srli_epi16(rAG, 8); + _mm_storeu_si128((__m128i*)(&intermediate_buffer[1][f]), rAG); + __m128i rRB =_mm_add_epi16(topRB, bottomRB); + rRB = _mm_srli_epi16(rRB, 8); + _mm_storeu_si128((__m128i*)(&intermediate_buffer[0][f]), rRB); + } + } +#endif + for (; f < count; f++) { // Same as above but without sse2 + if (blendType == BlendTransformedBilinearTiled) { + if (x >= image_width) x -= image_width; + } else { + x = qMin(x, image_x2 - 1); + } + + uint t = fetch(s1, x, data->texture.colorTable); + uint b = fetch(s2, x, data->texture.colorTable); + + intermediate_buffer[0][f] = (((t & 0xff00ff) * idisty + (b & 0xff00ff) * disty) >> 8) & 0xff00ff; + intermediate_buffer[1][f] = ((((t>>8) & 0xff00ff) * idisty + ((b>>8) & 0xff00ff) * disty) >> 8) & 0xff00ff; + x++; + } + // Now interpolate the values from the intermediate_buffer to get the final result. + fx &= fixed_scale - 1; + Q_ASSERT((fx >> 16) == 0); + while (b < end) { + register int x1 = (fx >> 16); + register int x2 = x1 + 1; + Q_ASSERT(x1 >= 0); + Q_ASSERT(x2 < count); + + register int distx = (fx & 0x0000ffff) >> 8; + register int idistx = 256 - distx; + int rb = ((intermediate_buffer[0][x1] * idistx + intermediate_buffer[0][x2] * distx) >> 8) & 0xff00ff; + int ag = (intermediate_buffer[1][x1] * idistx + intermediate_buffer[1][x2] * distx) & 0xff00ff00; + *b = rb | ag; + b++; + fx += fdx; + } + } else if ((fdx < 0 && fdx > -(fixed_scale / 8)) || fabs(data->m22) < (1./8.)) { // scale up more than 8x + int y1 = (fy >> 16); + int y2; + fetchTransformedBilinear_pixelBounds(image_height, image_y1, image_y2, y1, y2); + const uchar *s1 = data->texture.scanLine(y1); + const uchar *s2 = data->texture.scanLine(y2); + int disty = (fy & 0x0000ffff) >> 8; + int idisty = 256 - disty; + while (b < end) { + int x1 = (fx >> 16); + int x2; + fetchTransformedBilinear_pixelBounds(image_width, image_x1, image_x2, x1, x2); + uint tl = fetch(s1, x1, data->texture.colorTable); + uint tr = fetch(s1, x2, data->texture.colorTable); + uint bl = fetch(s2, x1, data->texture.colorTable); + uint br = fetch(s2, x2, data->texture.colorTable); + + int distx = (fx & 0x0000ffff) >> 8; + int idistx = 256 - distx; + + uint xtop = INTERPOLATE_PIXEL_256(tl, idistx, tr, distx); + uint xbot = INTERPOLATE_PIXEL_256(bl, idistx, br, distx); + *b = INTERPOLATE_PIXEL_256(xtop, idisty, xbot, disty); + + fx += fdx; + ++b; + } + } else { //scale down + int y1 = (fy >> 16); + int y2; + fetchTransformedBilinear_pixelBounds(image_height, image_y1, image_y2, y1, y2); + const uchar *s1 = data->texture.scanLine(y1); + const uchar *s2 = data->texture.scanLine(y2); + int disty = (fy & 0x0000ffff) >> 12; + int idisty = 16 - disty; + while (b < end) { + int x1 = (fx >> 16); + int x2; + fetchTransformedBilinear_pixelBounds(image_width, image_x1, image_x2, x1, x2); + uint tl = fetch(s1, x1, data->texture.colorTable); + uint tr = fetch(s1, x2, data->texture.colorTable); + uint bl = fetch(s2, x1, data->texture.colorTable); + uint br = fetch(s2, x2, data->texture.colorTable); + int distx = (fx & 0x0000ffff) >> 12; + int idistx = 16 - distx; + *b = interpolate_4_pixels_16(tl, tr, bl, br, distx, disty, idistx, idisty); + fx += fdx; + ++b; } } + } else { //rotation + if (fabs(data->m11) > 8 || fabs(data->m22) > 8) { + //if we are zooming more than 8 times, we use 8bit precision for the position. + while (b < end) { + int x1 = (fx >> 16); + int x2; + int y1 = (fy >> 16); + int y2; - Q_ASSERT(x1 >= 0 && x1 < image_width); - Q_ASSERT(x2 >= 0 && x2 < image_width); - Q_ASSERT(y1 >= 0 && y1 < image_height); - Q_ASSERT(y2 >= 0 && y2 < image_height); + fetchTransformedBilinear_pixelBounds(image_width, image_x1, image_x2, x1, x2); + fetchTransformedBilinear_pixelBounds(image_height, image_y1, image_y2, y1, y2); - const uchar *s1 = data->texture.scanLine(y1); - const uchar *s2 = data->texture.scanLine(y2); + const uchar *s1 = data->texture.scanLine(y1); + const uchar *s2 = data->texture.scanLine(y2); - uint tl = fetch(s1, x1, data->texture.colorTable); - uint tr = fetch(s1, x2, data->texture.colorTable); - uint bl = fetch(s2, x1, data->texture.colorTable); - uint br = fetch(s2, x2, data->texture.colorTable); + uint tl = fetch(s1, x1, data->texture.colorTable); + uint tr = fetch(s1, x2, data->texture.colorTable); + uint bl = fetch(s2, x1, data->texture.colorTable); + uint br = fetch(s2, x2, data->texture.colorTable); - int distx = (fx & 0x0000ffff) >> 8; - int disty = (fy & 0x0000ffff) >> 8; - int idistx = 256 - distx; - int idisty = 256 - disty; + int distx = (fx & 0x0000ffff) >> 8; + int disty = (fy & 0x0000ffff) >> 8; + int idistx = 256 - distx; + int idisty = 256 - disty; - uint xtop = INTERPOLATE_PIXEL_256(tl, idistx, tr, distx); - uint xbot = INTERPOLATE_PIXEL_256(bl, idistx, br, distx); - *b = INTERPOLATE_PIXEL_256(xtop, idisty, xbot, disty); + uint xtop = INTERPOLATE_PIXEL_256(tl, idistx, tr, distx); + uint xbot = INTERPOLATE_PIXEL_256(bl, idistx, br, distx); + *b = INTERPOLATE_PIXEL_256(xtop, idisty, xbot, disty); - fx += fdx; - fy += fdy; - ++b; + fx += fdx; + fy += fdy; + ++b; + } + } else { + //we are zooming less than 8x, use 4bit precision + while (b < end) { + int x1 = (fx >> 16); + int x2; + int y1 = (fy >> 16); + int y2; + + fetchTransformedBilinear_pixelBounds(image_width, image_x1, image_x2, x1, x2); + fetchTransformedBilinear_pixelBounds(image_height, image_y1, image_y2, y1, y2); + + const uchar *s1 = data->texture.scanLine(y1); + const uchar *s2 = data->texture.scanLine(y2); + + uint tl = fetch(s1, x1, data->texture.colorTable); + uint tr = fetch(s1, x2, data->texture.colorTable); + uint bl = fetch(s2, x1, data->texture.colorTable); + uint br = fetch(s2, x2, data->texture.colorTable); + + int distx = (fx & 0x0000ffff) >> 12; + int disty = (fy & 0x0000ffff) >> 12; + int idistx = 16 - distx; + int idisty = 16 - disty; + + *b = interpolate_4_pixels_16(tl, tr, bl, br, distx, disty, idistx, idisty); + + fx += fdx; + fy += fdy; + ++b; + } + } } } else { const qreal fdx = data->m11; @@ -779,37 +985,8 @@ const uint * QT_FASTCALL fetchTransformedBilinear(uint *buffer, const Operator * int idistx = 256 - distx; int idisty = 256 - disty; - if (blendType == BlendTransformedBilinearTiled) { - x1 %= image_width; - if (x1 < 0) x1 += image_width; - x2 = x1 + 1; - x2 %= image_width; - - y1 %= image_height; - if (y1 < 0) y1 += image_height; - y2 = y1 + 1; - y2 %= image_height; - } else { - if (x1 < 0) { - x2 = x1 = 0; - } else if (x1 >= image_width - 1) { - x2 = x1 = image_width - 1; - } else { - x2 = x1 + 1; - } - if (y1 < 0) { - y2 = y1 = 0; - } else if (y1 >= image_height - 1) { - y2 = y1 = image_height - 1; - } else { - y2 = y1 + 1; - } - } - - Q_ASSERT(x1 >= 0 && x1 < image_width); - Q_ASSERT(x2 >= 0 && x2 < image_width); - Q_ASSERT(y1 >= 0 && y1 < image_height); - Q_ASSERT(y2 >= 0 && y2 < image_height); + fetchTransformedBilinear_pixelBounds(image_width, image_x1, image_x2, x1, x2); + fetchTransformedBilinear_pixelBounds(image_height, image_y1, image_y2, y1, y2); const uchar *s1 = data->texture.scanLine(y1); const uchar *s2 = data->texture.scanLine(y2); @@ -5212,37 +5389,8 @@ Q_STATIC_TEMPLATE_FUNCTION void blend_transformed_bilinear_argb(int count, const int y1 = (y >> 16); int y2; - if (blendType == BlendTransformedBilinearTiled) { - x1 %= image_width; - if (x1 < 0) x1 += image_width; - x2 = x1 + 1; - x2 %= image_width; - - y1 %= image_height; - if (y1 < 0) y1 += image_height; - y2 = y1 + 1; - y2 %= image_height; - - Q_ASSERT(x1 >= 0 && x1 < image_width); - Q_ASSERT(x2 >= 0 && x2 < image_width); - Q_ASSERT(y1 >= 0 && y1 < image_height); - Q_ASSERT(y2 >= 0 && y2 < image_height); - } else { - if (x1 < image_x1) { - x2 = x1 = image_x1; - } else if (x1 >= image_x2 - 1) { - x2 = x1 = image_x2 - 1; - } else { - x2 = x1 + 1; - } - if (y1 < image_y1) { - y2 = y1 = image_y1; - } else if (y1 >= image_y2 - 1) { - y2 = y1 = image_y2 - 1; - } else { - y2 = y1 + 1; - } - } + fetchTransformedBilinear_pixelBounds(image_width, image_x1, image_x2, x1, x2); + fetchTransformedBilinear_pixelBounds(image_height, image_y1, image_y2, y1, y2); int y1_offset = y1 * scanline_offset; int y2_offset = y2 * scanline_offset; @@ -5322,37 +5470,8 @@ Q_STATIC_TEMPLATE_FUNCTION void blend_transformed_bilinear_argb(int count, const int idistx = 256 - distx; int idisty = 256 - disty; - if (blendType == BlendTransformedBilinearTiled) { - x1 %= image_width; - if (x1 < 0) x1 += image_width; - x2 = x1 + 1; - x2 %= image_width; - - y1 %= image_height; - if (y1 < 0) y1 += image_height; - y2 = y1 + 1; - y2 %= image_height; - - Q_ASSERT(x1 >= 0 && x1 < image_width); - Q_ASSERT(x2 >= 0 && x2 < image_width); - Q_ASSERT(y1 >= 0 && y1 < image_height); - Q_ASSERT(y2 >= 0 && y2 < image_height); - } else { - if (x1 < image_x1) { - x2 = x1 = image_x1; - } else if (x1 >= image_x2 - 1) { - x2 = x1 = image_x2 - 1; - } else { - x2 = x1 + 1; - } - if (y1 < image_y1) { - y2 = y1 = image_y1; - } else if (y1 >= image_y2 - 1) { - y2 = y1 = image_y2 - 1; - } else { - y2 = y1 + 1; - } - } + fetchTransformedBilinear_pixelBounds(image_width, image_x1, image_x2, x1, x2); + fetchTransformedBilinear_pixelBounds(image_height, image_y1, image_y2, y1, y2); int y1_offset = y1 * scanline_offset; int y2_offset = y2 * scanline_offset; -- cgit v0.12 From d17a1cd32b4577a96245ac9894f678486443a516 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Mon, 30 Aug 2010 16:34:52 +0200 Subject: tst_qimage: backport fix of commit 0d7e683 into 4.7 --- tests/auto/qimage/tst_qimage.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/auto/qimage/tst_qimage.cpp b/tests/auto/qimage/tst_qimage.cpp index 49514dc..405eb98 100644 --- a/tests/auto/qimage/tst_qimage.cpp +++ b/tests/auto/qimage/tst_qimage.cpp @@ -1490,9 +1490,9 @@ void tst_QImage::smoothScale3() QRgb cb = b.pixel(x, y); // tolerate a little bit of rounding errors - QVERIFY(compare(qRed(ca), qRed(cb), 3)); - QVERIFY(compare(qGreen(ca), qGreen(cb), 3)); - QVERIFY(compare(qBlue(ca), qBlue(cb), 3)); + QVERIFY(compare(qRed(ca), qRed(cb), 16)); + QVERIFY(compare(qGreen(ca), qGreen(cb), 16)); + QVERIFY(compare(qBlue(ca), qBlue(cb), 16)); } } } -- cgit v0.12 From d0f1f569e27f7f34f3bfc03bd759f28f7b567997 Mon Sep 17 00:00:00 2001 From: Eskil Abrahamsen Blomfeldt Date: Mon, 30 Aug 2010 17:08:48 +0200 Subject: Fix QStaticText with OpenGL1 engine Like OpenGL2 and OpenVG, the OpenGL1 paint engine also transforms text coordinates itself and does not require QStaticText to use device coordinates. Task-number: QTBUG-13228 Reviewed-by: Samuel --- src/gui/painting/qpainter.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/gui/painting/qpainter.cpp b/src/gui/painting/qpainter.cpp index ee590a4..4e10671 100644 --- a/src/gui/painting/qpainter.cpp +++ b/src/gui/painting/qpainter.cpp @@ -5863,7 +5863,8 @@ void QPainter::drawStaticText(const QPointF &topLeftPosition, const QStaticText } bool paintEngineSupportsTransformations = d->extended->type() == QPaintEngine::OpenGL2 - || d->extended->type() == QPaintEngine::OpenVG; + || d->extended->type() == QPaintEngine::OpenVG + || d->extended->type() == QPaintEngine::OpenGL; if (paintEngineSupportsTransformations && !staticText_d->untransformedCoordinates) { staticText_d->untransformedCoordinates = true; -- cgit v0.12 From eb0307cac2f6c35094ffcf7de782881cb440cf2f Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 31 Aug 2010 17:37:30 +1000 Subject: Ignore non-scriptable properties in QML QTBUG-13043 --- src/declarative/qml/qdeclarativecompiler.cpp | 14 ++++++-- src/declarative/qml/qdeclarativepropertycache.cpp | 38 +++++++++++++++++----- src/declarative/qml/qmetaobjectbuilder.cpp | 4 +-- .../qdeclarativeecmascript/data/nonscriptable.qml | 19 +++++++++++ .../declarative/qdeclarativeecmascript/testtypes.h | 5 +++ .../tst_qdeclarativeecmascript.cpp | 12 +++++++ .../data/invalidAlias.7.errors.txt | 1 + .../qdeclarativelanguage/data/invalidAlias.7.qml | 6 ++++ .../data/nonScriptableProperty.errors.txt | 1 + .../data/nonScriptableProperty.qml | 5 +++ .../declarative/qdeclarativelanguage/testtypes.h | 4 +++ .../tst_qdeclarativelanguage.cpp | 2 ++ .../qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp | 12 +++---- 13 files changed, 104 insertions(+), 19 deletions(-) create mode 100644 tests/auto/declarative/qdeclarativeecmascript/data/nonscriptable.qml create mode 100644 tests/auto/declarative/qdeclarativelanguage/data/invalidAlias.7.errors.txt create mode 100644 tests/auto/declarative/qdeclarativelanguage/data/invalidAlias.7.qml create mode 100644 tests/auto/declarative/qdeclarativelanguage/data/nonScriptableProperty.errors.txt create mode 100644 tests/auto/declarative/qdeclarativelanguage/data/nonScriptableProperty.qml diff --git a/src/declarative/qml/qdeclarativecompiler.cpp b/src/declarative/qml/qdeclarativecompiler.cpp index 5bfe5b2..7847303 100644 --- a/src/declarative/qml/qdeclarativecompiler.cpp +++ b/src/declarative/qml/qdeclarativecompiler.cpp @@ -1362,7 +1362,7 @@ bool QDeclarativeCompiler::doesPropertyExist(QDeclarativeParser::Property *prop, return p.name() != 0; } else { int idx = mo->indexOfProperty(prop->name.constData()); - return idx != -1; + return idx != -1 && mo->property(idx).isScriptable(); } } @@ -1427,6 +1427,11 @@ bool QDeclarativeCompiler::buildProperty(QDeclarativeParser::Property *prop, if (prop->index != -1) { p = metaObject->property(prop->index); Q_ASSERT(p.name()); + + if (!p.isScriptable()) { + prop->index = -1; + p = QMetaProperty(); + } } } @@ -1813,6 +1818,8 @@ bool QDeclarativeCompiler::buildValueTypeProperty(QObject *type, if (idx == -1) COMPILE_EXCEPTION(prop, tr("Cannot assign to non-existent property \"%1\"").arg(QString::fromUtf8(prop->name))); QMetaProperty p = type->metaObject()->property(idx); + if (!p.isScriptable()) + COMPILE_EXCEPTION(prop, tr("Cannot assign to non-existent property \"%1\"").arg(QString::fromUtf8(prop->name))); prop->index = idx; prop->type = p.userType(); prop->isValueTypeSubProperty = true; @@ -2406,7 +2413,6 @@ bool QDeclarativeCompiler::buildDynamicMeta(QDeclarativeParser::Object *obj, Dyn builder.addSignal(p.name + "Changed()"); QMetaPropertyBuilder propBuilder = builder.addProperty(p.name, type, builder.methodCount() - 1); - propBuilder.setScriptable(true); propBuilder.setWritable(!readonly); } @@ -2572,6 +2578,9 @@ bool QDeclarativeCompiler::compileAlias(QMetaObjectBuilder &builder, COMPILE_EXCEPTION(prop.defaultValue, tr("Invalid alias location")); QMetaProperty aliasProperty = idObject->metaObject()->property(propIdx); + if (!aliasProperty.isScriptable()) + COMPILE_EXCEPTION(prop.defaultValue, tr("Invalid alias location")); + writable = aliasProperty.isWritable(); if (aliasProperty.isEnumType()) @@ -2608,7 +2617,6 @@ bool QDeclarativeCompiler::compileAlias(QMetaObjectBuilder &builder, builder.addSignal(prop.name + "Changed()"); QMetaPropertyBuilder propBuilder = builder.addProperty(prop.name, typeName.constData(), builder.methodCount() - 1); - propBuilder.setScriptable(true); propBuilder.setWritable(writable); return true; } diff --git a/src/declarative/qml/qdeclarativepropertycache.cpp b/src/declarative/qml/qdeclarativepropertycache.cpp index 839d79f..1121a8d 100644 --- a/src/declarative/qml/qdeclarativepropertycache.cpp +++ b/src/declarative/qml/qdeclarativepropertycache.cpp @@ -134,8 +134,9 @@ QDeclarativePropertyCache::~QDeclarativePropertyCache() void QDeclarativePropertyCache::clear() { - for (int ii = 0; ii < indexCache.count(); ++ii) - indexCache.at(ii)->release(); + for (int ii = 0; ii < indexCache.count(); ++ii) { + if (indexCache.at(ii)) indexCache.at(ii)->release(); + } for (StringCache::ConstIterator iter = stringCache.begin(); iter != stringCache.end(); ++iter) @@ -156,10 +157,23 @@ QDeclarativePropertyCache::Data QDeclarativePropertyCache::create(const QMetaObj Q_ASSERT(metaObject); QDeclarativePropertyCache::Data rv; - int idx = metaObject->indexOfProperty(property.toUtf8()); - if (idx != -1) { - rv.load(metaObject->property(idx)); - return rv; + { + const QMetaObject *cmo = metaObject; + while (cmo) { + int idx = metaObject->indexOfProperty(property.toUtf8()); + if (idx != -1) { + QMetaProperty p = metaObject->property(idx); + if (p.isScriptable()) { + rv.load(metaObject->property(idx)); + return rv; + } else { + while (cmo && cmo->propertyOffset() >= idx) + cmo = cmo->superClass(); + } + } else { + cmo = 0; + } + } } int methodCount = metaObject->methodCount(); @@ -189,8 +203,9 @@ QDeclarativePropertyCache *QDeclarativePropertyCache::copy() const cache->stringCache = stringCache; cache->identifierCache = identifierCache; - for (int ii = 0; ii < indexCache.count(); ++ii) - indexCache.at(ii)->addref(); + for (int ii = 0; ii < indexCache.count(); ++ii) { + if (indexCache.at(ii)) indexCache.at(ii)->addref(); + } for (StringCache::ConstIterator iter = stringCache.begin(); iter != stringCache.end(); ++iter) (*iter)->addref(); for (IdentifierCache::ConstIterator iter = identifierCache.begin(); iter != identifierCache.end(); ++iter) @@ -210,6 +225,9 @@ void QDeclarativePropertyCache::append(QDeclarativeEngine *engine, const QMetaOb indexCache.resize(propCount); for (int ii = propOffset; ii < propCount; ++ii) { QMetaProperty p = metaObject->property(ii); + if (!p.isScriptable()) + continue; + QString propName = QString::fromUtf8(p.name()); RData *data = new RData; @@ -275,6 +293,10 @@ void QDeclarativePropertyCache::update(QDeclarativeEngine *engine, const QMetaOb indexCache.resize(propCount); for (int ii = propCount - 1; ii >= 0; --ii) { QMetaProperty p = metaObject->property(ii); + if (!p.isScriptable()) { + indexCache[ii] = 0; + continue; + } QString propName = QString::fromUtf8(p.name()); RData *data = new RData; diff --git a/src/declarative/qml/qmetaobjectbuilder.cpp b/src/declarative/qml/qmetaobjectbuilder.cpp index 0954248..58f8811 100644 --- a/src/declarative/qml/qmetaobjectbuilder.cpp +++ b/src/declarative/qml/qmetaobjectbuilder.cpp @@ -205,7 +205,7 @@ public: (const QByteArray& _name, const QByteArray& _type, int notifierIdx=-1) : name(_name), type(QMetaObject::normalizedType(_type.constData())), - flags(Readable | Writable), notifySignal(-1) + flags(Readable | Writable | Scriptable), notifySignal(-1) { if (notifierIdx >= 0) { flags |= Notify; @@ -2187,7 +2187,7 @@ bool QMetaPropertyBuilder::isDesignable() const /*! Returns true if the property is scriptable; otherwise returns false. - This default value is false. + This default value is true. \sa setScriptable(), isDesignable(), isStored() */ diff --git a/tests/auto/declarative/qdeclarativeecmascript/data/nonscriptable.qml b/tests/auto/declarative/qdeclarativeecmascript/data/nonscriptable.qml new file mode 100644 index 0000000..024d82e --- /dev/null +++ b/tests/auto/declarative/qdeclarativeecmascript/data/nonscriptable.qml @@ -0,0 +1,19 @@ +import Qt.test 1.0 +import Qt 4.7 + +MyQmlObject { + id: root + + property bool readOk: false; + property bool writeOk: false + + Component.onCompleted: { + readOk = (root.nonscriptable == undefined); + + try { + root.nonscriptable = 10 + } catch (e) { + writeOk = true; + } + } +} diff --git a/tests/auto/declarative/qdeclarativeecmascript/testtypes.h b/tests/auto/declarative/qdeclarativeecmascript/testtypes.h index 37d6dbd..7d7e3d9 100644 --- a/tests/auto/declarative/qdeclarativeecmascript/testtypes.h +++ b/tests/auto/declarative/qdeclarativeecmascript/testtypes.h @@ -92,6 +92,7 @@ class MyQmlObject : public QObject Q_PROPERTY(QDeclarativeListProperty objectListProperty READ objectListProperty CONSTANT) Q_PROPERTY(int resettableProperty READ resettableProperty WRITE setResettableProperty RESET resetProperty) Q_PROPERTY(QRegExp regExp READ regExp WRITE setRegExp) + Q_PROPERTY(int nonscriptable READ nonscriptable WRITE setNonscriptable SCRIPTABLE false); public: MyQmlObject(): m_methodCalled(false), m_methodIntCalled(false), m_object(0), m_value(0), m_resetProperty(13) {} @@ -144,6 +145,10 @@ public: void setRegExp(const QRegExp ®Exp) { m_regExp = regExp; } int console() const { return 11; } + + int nonscriptable() const { return 0; } + void setNonscriptable(int) {} + signals: void basicSignal(); void argumentSignal(int a, QString b, qreal c); diff --git a/tests/auto/declarative/qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp b/tests/auto/declarative/qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp index a6d2dac..c01d756 100644 --- a/tests/auto/declarative/qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp +++ b/tests/auto/declarative/qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp @@ -157,6 +157,7 @@ private slots: void qtbug_10696(); void qtbug_11606(); void qtbug_11600(); + void nonscriptable(); void include(); @@ -2530,6 +2531,17 @@ void tst_qdeclarativeecmascript::qtbug_11600() delete o; } +// Reading and writing non-scriptable properties should fail +void tst_qdeclarativeecmascript::nonscriptable() +{ + QDeclarativeComponent component(&engine, TEST_FILE("nonscriptable.qml")); + QObject *o = component.create(); + QVERIFY(o != 0); + QCOMPARE(o->property("readOk").toBool(), true); + QCOMPARE(o->property("writeOk").toBool(), true); + delete o; +} + QTEST_MAIN(tst_qdeclarativeecmascript) diff --git a/tests/auto/declarative/qdeclarativelanguage/data/invalidAlias.7.errors.txt b/tests/auto/declarative/qdeclarativelanguage/data/invalidAlias.7.errors.txt new file mode 100644 index 0000000..93652a7 --- /dev/null +++ b/tests/auto/declarative/qdeclarativelanguage/data/invalidAlias.7.errors.txt @@ -0,0 +1 @@ +5:23:Invalid alias location diff --git a/tests/auto/declarative/qdeclarativelanguage/data/invalidAlias.7.qml b/tests/auto/declarative/qdeclarativelanguage/data/invalidAlias.7.qml new file mode 100644 index 0000000..2a09648 --- /dev/null +++ b/tests/auto/declarative/qdeclarativelanguage/data/invalidAlias.7.qml @@ -0,0 +1,6 @@ +import Test 1.0 + +MyTypeObject { + id: root + property alias a: root.nonScriptable +} diff --git a/tests/auto/declarative/qdeclarativelanguage/data/nonScriptableProperty.errors.txt b/tests/auto/declarative/qdeclarativelanguage/data/nonScriptableProperty.errors.txt new file mode 100644 index 0000000..cdfa4b2 --- /dev/null +++ b/tests/auto/declarative/qdeclarativelanguage/data/nonScriptableProperty.errors.txt @@ -0,0 +1 @@ +4:5:Cannot assign to non-existent property "nonScriptable" diff --git a/tests/auto/declarative/qdeclarativelanguage/data/nonScriptableProperty.qml b/tests/auto/declarative/qdeclarativelanguage/data/nonScriptableProperty.qml new file mode 100644 index 0000000..bd59bc8 --- /dev/null +++ b/tests/auto/declarative/qdeclarativelanguage/data/nonScriptableProperty.qml @@ -0,0 +1,5 @@ +import Test 1.0 + +MyQmlObject { + nonScriptable: 11 +} diff --git a/tests/auto/declarative/qdeclarativelanguage/testtypes.h b/tests/auto/declarative/qdeclarativelanguage/testtypes.h index 19790f1..ac55bae 100644 --- a/tests/auto/declarative/qdeclarativelanguage/testtypes.h +++ b/tests/auto/declarative/qdeclarativelanguage/testtypes.h @@ -112,6 +112,7 @@ class MyQmlObject : public QObject, public MyInterface Q_PROPERTY(MyCustomVariantType customType READ customType WRITE setCustomType) Q_PROPERTY(MyQmlObject *qmlobjectProperty READ qmlobject WRITE setQmlobject) Q_PROPERTY(int propertyWithNotify READ propertyWithNotify WRITE setPropertyWithNotify NOTIFY oddlyNamedNotifySignal) + Q_PROPERTY(int nonScriptable READ nonScriptable WRITE setNonScriptable SCRIPTABLE false); Q_INTERFACES(MyInterface) public: @@ -150,6 +151,9 @@ public: int propertyWithNotify() const { return m_propertyWithNotify; } void setPropertyWithNotify(int i) { m_propertyWithNotify = i; emit oddlyNamedNotifySignal(); } + + int nonScriptable() const { return 0; } + void setNonScriptable(int) {} public slots: void basicSlot() { qWarning("MyQmlObject::basicSlot"); } void basicSlotWithArgs(int v) { qWarning("MyQmlObject::basicSlotWithArgs(%d)", v); } diff --git a/tests/auto/declarative/qdeclarativelanguage/tst_qdeclarativelanguage.cpp b/tests/auto/declarative/qdeclarativelanguage/tst_qdeclarativelanguage.cpp index b43fbf4..fc78663 100644 --- a/tests/auto/declarative/qdeclarativelanguage/tst_qdeclarativelanguage.cpp +++ b/tests/auto/declarative/qdeclarativelanguage/tst_qdeclarativelanguage.cpp @@ -343,6 +343,7 @@ void tst_qdeclarativelanguage::errors_data() QTest::newRow("invalidAlias.4") << "invalidAlias.4.qml" << "invalidAlias.4.errors.txt" << false; QTest::newRow("invalidAlias.5") << "invalidAlias.5.qml" << "invalidAlias.5.errors.txt" << false; QTest::newRow("invalidAlias.6") << "invalidAlias.6.qml" << "invalidAlias.6.errors.txt" << false; + QTest::newRow("invalidAlias.7") << "invalidAlias.7.qml" << "invalidAlias.7.errors.txt" << false; QTest::newRow("invalidAttachedProperty.1") << "invalidAttachedProperty.1.qml" << "invalidAttachedProperty.1.errors.txt" << false; QTest::newRow("invalidAttachedProperty.2") << "invalidAttachedProperty.2.qml" << "invalidAttachedProperty.2.errors.txt" << false; @@ -373,6 +374,7 @@ void tst_qdeclarativelanguage::errors_data() QTest::newRow("assignToNamespace") << "assignToNamespace.qml" << "assignToNamespace.errors.txt" << false; QTest::newRow("invalidOn") << "invalidOn.qml" << "invalidOn.errors.txt" << false; QTest::newRow("invalidProperty") << "invalidProperty.qml" << "invalidProperty.errors.txt" << false; + QTest::newRow("nonScriptableProperty") << "nonScriptableProperty.qml" << "nonScriptableProperty.errors.txt" << false; } diff --git a/tests/auto/declarative/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp b/tests/auto/declarative/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp index 8ba9d45..0f6d531 100644 --- a/tests/auto/declarative/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp +++ b/tests/auto/declarative/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp @@ -558,7 +558,7 @@ void tst_QMetaObjectBuilder::property() QVERIFY(prop1.isWritable()); QVERIFY(!prop1.isResettable()); QVERIFY(!prop1.isDesignable()); - QVERIFY(!prop1.isScriptable()); + QVERIFY(prop1.isScriptable()); QVERIFY(!prop1.isStored()); QVERIFY(!prop1.isEditable()); QVERIFY(!prop1.isUser()); @@ -577,7 +577,7 @@ void tst_QMetaObjectBuilder::property() QVERIFY(prop2.isWritable()); QVERIFY(!prop2.isResettable()); QVERIFY(!prop2.isDesignable()); - QVERIFY(!prop2.isScriptable()); + QVERIFY(prop2.isScriptable()); QVERIFY(!prop2.isStored()); QVERIFY(!prop2.isEditable()); QVERIFY(!prop2.isUser()); @@ -599,7 +599,7 @@ void tst_QMetaObjectBuilder::property() prop1.setWritable(false); prop1.setResettable(true); prop1.setDesignable(true); - prop1.setScriptable(true); + prop1.setScriptable(false); prop1.setStored(true); prop1.setEditable(true); prop1.setUser(true); @@ -614,7 +614,7 @@ void tst_QMetaObjectBuilder::property() QVERIFY(!prop1.isWritable()); QVERIFY(prop1.isResettable()); QVERIFY(prop1.isDesignable()); - QVERIFY(prop1.isScriptable()); + QVERIFY(!prop1.isScriptable()); QVERIFY(prop1.isStored()); QVERIFY(prop1.isEditable()); QVERIFY(prop1.isUser()); @@ -627,7 +627,7 @@ void tst_QMetaObjectBuilder::property() QCOMPARE(prop2.type(), QByteArray("int")); QVERIFY(!prop2.isResettable()); QVERIFY(!prop2.isDesignable()); - QVERIFY(!prop2.isScriptable()); + QVERIFY(prop2.isScriptable()); QVERIFY(!prop2.isStored()); QVERIFY(!prop2.isEditable()); QVERIFY(!prop2.isUser()); @@ -643,7 +643,7 @@ void tst_QMetaObjectBuilder::property() QCOMPARE(prop2.type(), QByteArray("int")); QVERIFY(!prop2.isResettable()); QVERIFY(!prop2.isDesignable()); - QVERIFY(!prop2.isScriptable()); + QVERIFY(prop2.isScriptable()); QVERIFY(!prop2.isStored()); QVERIFY(!prop2.isEditable()); QVERIFY(!prop2.isUser()); -- cgit v0.12 From 07095fe95200112ba14bf728148d03f579940c28 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 31 Aug 2010 17:56:11 +1000 Subject: Prevent calling deleteLater() from QML QTBUG-13045 --- src/declarative/qml/qdeclarativepropertycache.cpp | 4 ++-- .../qdeclarativeecmascript/data/deleteLater.qml | 14 ++++++++++++++ .../qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp | 10 ++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 tests/auto/declarative/qdeclarativeecmascript/data/deleteLater.qml diff --git a/src/declarative/qml/qdeclarativepropertycache.cpp b/src/declarative/qml/qdeclarativepropertycache.cpp index 1121a8d..08503c2 100644 --- a/src/declarative/qml/qdeclarativepropertycache.cpp +++ b/src/declarative/qml/qdeclarativepropertycache.cpp @@ -177,7 +177,7 @@ QDeclarativePropertyCache::Data QDeclarativePropertyCache::create(const QMetaObj } int methodCount = metaObject->methodCount(); - for (int ii = methodCount - 1; ii >= 2; --ii) { // >=2 to block the destroyed signal + for (int ii = methodCount - 1; ii >= 3; --ii) { // >=3 to block the destroyed signal and deleteLater() slot QMetaMethod m = metaObject->method(ii); if (m.access() == QMetaMethod::Private) continue; @@ -316,7 +316,7 @@ void QDeclarativePropertyCache::update(QDeclarativeEngine *engine, const QMetaOb } int methodCount = metaObject->methodCount(); - for (int ii = methodCount - 1; ii >= 2; --ii) { // >=2 to block the destroyed signal + for (int ii = methodCount - 1; ii >= 3; --ii) { // >=3 to block the destroyed signal and deleteLater() slot QMetaMethod m = metaObject->method(ii); if (m.access() == QMetaMethod::Private) continue; diff --git a/tests/auto/declarative/qdeclarativeecmascript/data/deleteLater.qml b/tests/auto/declarative/qdeclarativeecmascript/data/deleteLater.qml new file mode 100644 index 0000000..6d23e5f7 --- /dev/null +++ b/tests/auto/declarative/qdeclarativeecmascript/data/deleteLater.qml @@ -0,0 +1,14 @@ +import Qt 4.7 + +QtObject { + id: root + property bool test: false + + Component.onCompleted: { + try { + root.deleteLater() + } catch(e) { + test = true; + } + } +} diff --git a/tests/auto/declarative/qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp b/tests/auto/declarative/qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp index c01d756..496cc05 100644 --- a/tests/auto/declarative/qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp +++ b/tests/auto/declarative/qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp @@ -158,6 +158,7 @@ private slots: void qtbug_11606(); void qtbug_11600(); void nonscriptable(); + void deleteLater(); void include(); @@ -2542,6 +2543,15 @@ void tst_qdeclarativeecmascript::nonscriptable() delete o; } +// deleteLater() should not be callable from QML +void tst_qdeclarativeecmascript::deleteLater() +{ + QDeclarativeComponent component(&engine, TEST_FILE("deleteLater.qml")); + QObject *o = component.create(); + QVERIFY(o != 0); + QCOMPARE(o->property("test").toBool(), true); + delete o; +} QTEST_MAIN(tst_qdeclarativeecmascript) -- cgit v0.12 From 63aa8c467941cf6cb19fc6fcad5c0efde0b53216 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Tue, 24 Aug 2010 16:22:40 +0200 Subject: Made QT_GL_SWAPBUFFER_PRESERVE=1 with the GL graphics system work. On desktop, we should just do swapBuffers() in swapRegion(). Reviewed-by: Trond --- src/opengl/qgl.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 943a195..c49dba4 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -2103,11 +2103,8 @@ void QGLContextPrivate::syncGlState() #ifdef QT_NO_EGL void QGLContextPrivate::swapRegion(const QRegion *) { - static bool firstWarning = true; - if (firstWarning) { - qWarning() << "::swapRegion called but not supported!"; - firstWarning = false; - } + Q_Q(QGLContext); + q->swapBuffers(); } #endif -- cgit v0.12 From 34d0cd1e65644970d890e52bd3c880fc941d99f9 Mon Sep 17 00:00:00 2001 From: Michael Dominic K Date: Fri, 27 Aug 2010 09:28:40 +0200 Subject: Clear the QGLWindowSurface in ::beginPaint when needed. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Merge-request: 2462 Reviewed-by: Samuel Rødal --- src/opengl/qwindowsurface_gl.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index b86fb78..d602000 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -426,6 +426,20 @@ static void drawTexture(const QRectF &rect, GLuint tex_id, const QSize &texSize, void QGLWindowSurface::beginPaint(const QRegion &) { + if (! context()) + return; + + int clearFlags = 0; + + if (context()->d_func()->workaround_needsFullClearOnEveryFrame) + clearFlags = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT; + else if (context()->format().alpha()) + clearFlags = GL_COLOR_BUFFER_BIT; + + if (clearFlags) { + glClearColor(0.0, 0.0, 0.0, 0.0); + glClear(clearFlags); + } } void QGLWindowSurface::endPaint(const QRegion &rgn) -- cgit v0.12 From e9e0d32bb9c37f42740ffaa8145c30dc5da491d4 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 31 Aug 2010 18:19:51 +1000 Subject: Center and clip QML startup animation so it looks correct in fullscreen QTBUG-12831 --- tools/qml/startup/startup.qml | 88 +++++++++++++++++++++++-------------------- 1 file changed, 47 insertions(+), 41 deletions(-) diff --git a/tools/qml/startup/startup.qml b/tools/qml/startup/startup.qml index be67598..ddc7217 100644 --- a/tools/qml/startup/startup.qml +++ b/tools/qml/startup/startup.qml @@ -49,14 +49,53 @@ Rectangle { Component.onCompleted: treatsApp.state = "part1" signal animationFinished - Logo { - id: logo - x: 165 - y: 35 - rotation: -15 - scale: 0.6 - opacity: 0 - onAnimationFinished: treatsApp.animationFinished(); + Item { + width: 800 + height: 480 + anchors.centerIn: parent + clip: true + + Logo { + id: logo + x: 165 + y: 35 + rotation: -15 + scale: 0.6 + opacity: 0 + onAnimationFinished: treatsApp.animationFinished(); + } + + Item { + id: quickblur + x: 800//325 + y: 344 + Image { + id: blurText + source: "quick-blur.png" + } + Image { + id: quickregular + x: -1 + y: 0 + opacity: 0 + source: "quick-regular.png" + } + Image { + id: star + x: -1 + y: 0 + opacity: 0 + source: "white-star.png" + smooth: true + NumberAnimation on rotation { + from: 0 + to: 360 + loops: NumberAnimation.Infinite + running: true + duration: 2000 + } + } + } } states: [ @@ -96,39 +135,6 @@ Rectangle { } ] - - Item { - id: quickblur - x: 800//325 - y: 344 - Image { - id: blurText - source: "quick-blur.png" - } - Image { - id: quickregular - x: -1 - y: 0 - opacity: 0 - source: "quick-regular.png" - } - Image { - id: star - x: -1 - y: 0 - opacity: 0 - source: "white-star.png" - smooth: true - NumberAnimation on rotation { - from: 0 - to: 360 - loops: NumberAnimation.Infinite - running: true - duration: 2000 - } - } - } - transitions: [ Transition { ParallelAnimation { -- cgit v0.12 From 1a72dd3a1c8f66e31ce4102b2d3e7e5cff4817f8 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Mon, 7 Jun 2010 21:01:36 +0200 Subject: Make tst_image a little bit more tollerent to rounding errors (cherry picked from commit 23306a399c0703eea7420231903c850566bfe2f0) --- tests/auto/qimage/tst_qimage.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/auto/qimage/tst_qimage.cpp b/tests/auto/qimage/tst_qimage.cpp index 405eb98..ec0ecec 100644 --- a/tests/auto/qimage/tst_qimage.cpp +++ b/tests/auto/qimage/tst_qimage.cpp @@ -1451,11 +1451,6 @@ static inline int rand8() return int(256. * (qrand() / (RAND_MAX + 1.0))); } -static inline bool compare(int a, int b, int tolerance) -{ - return qAbs(a - b) <= tolerance; -} - // compares img.scale against the bilinear filtering used by QPainter void tst_QImage::smoothScale3() { @@ -1483,6 +1478,7 @@ void tst_QImage::smoothScale3() p.scale(scales[i], scales[i]); p.drawImage(0, 0, img); p.end(); + int err = 0; for (int y = 0; y < a.height(); ++y) { for (int x = 0; x < a.width(); ++x) { @@ -1490,11 +1486,15 @@ void tst_QImage::smoothScale3() QRgb cb = b.pixel(x, y); // tolerate a little bit of rounding errors - QVERIFY(compare(qRed(ca), qRed(cb), 16)); - QVERIFY(compare(qGreen(ca), qGreen(cb), 16)); - QVERIFY(compare(qBlue(ca), qBlue(cb), 16)); + bool r = true; + r &= qAbs(qRed(ca) - qRed(cb)) <= 18; + r &= qAbs(qGreen(ca) - qGreen(cb)) <= 18; + r &= qAbs(qBlue(ca) - qBlue(cb)) <= 18; + if (!r) + err++; } } + QCOMPARE(err, 0); } } -- cgit v0.12 From 500e4d4a7faef619354cb92b6bf7df6a639d29e3 Mon Sep 17 00:00:00 2001 From: Peter Hartmann Date: Tue, 31 Aug 2010 11:53:27 +0200 Subject: QNetworkAccessManager doc: add since tag for added enum --- src/network/access/qnetworkaccessmanager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/network/access/qnetworkaccessmanager.cpp b/src/network/access/qnetworkaccessmanager.cpp index 837cf66..b35c318 100644 --- a/src/network/access/qnetworkaccessmanager.cpp +++ b/src/network/access/qnetworkaccessmanager.cpp @@ -201,7 +201,7 @@ static void ensureInitialized() deleteResource()) \value CustomOperation custom operation (created with - sendCustomRequest()) + sendCustomRequest()) \since 4.7 \omitvalue UnknownOperation -- cgit v0.12 From 2192d722a0b2af2aae0a8c45741f1ee4fd28269c Mon Sep 17 00:00:00 2001 From: David Boddie Date: Tue, 31 Aug 2010 13:44:35 +0200 Subject: Doc: Reviewed updates to the model/view tutorial. --- doc/src/tutorials/modelview.qdoc | 810 +++++++++++++++++---------------------- 1 file changed, 356 insertions(+), 454 deletions(-) diff --git a/doc/src/tutorials/modelview.qdoc b/doc/src/tutorials/modelview.qdoc index 6dc1594..65f6674 100644 --- a/doc/src/tutorials/modelview.qdoc +++ b/doc/src/tutorials/modelview.qdoc @@ -29,72 +29,36 @@ \page modelview.html \startpage {index.html}{Qt Reference Documentation} - \nextpage {modelview-part1.html}{Introduction} \title Model/View Contents \brief An introduction to ModelView programming - Every UI developer should know about ModelView programming and the goal of this tutorial is to provide you with an easily understandable introduction to this topic. + Every UI developer should know about ModelView programming and the goal of + this tutorial is to provide you with an easily understandable introduction + to this topic. -\raw HTML -
-\endraw + Table, list and tree widgets are components frequently used in GUIs. There + are 2 different ways how these widgets can access their data. The + traditional way involves widgets which include internal containers for + storing data. This approach is very intuitive, however, in many non-trivial + applications, it leads to data synchronization issues. + The second approach is model/view programming, in + which widgets do not maintain internal data containers. They access external + data through a standardized interface and therefore avoid data duplication. + This may seem complicated at first, but once you take a closer look, it is + not only easy to grasp, but the many benefits of model/view programming also + become clearer. -\raw HTML - - - - - - - -
-\endraw + \image treeview.png -Table, list and tree widgets are components frequently used in GUIs. There are 2 different ways how these widgets can access their data. The traditional way involves widgets which include internal containers for storing data. This approach is very intuitive, however, in many non-trivial applications, it leads to data synchronization issues. The second approach is modelview programming, in which widgets do not maintain internal data containers. They access external data through a standardized interface and therefore avoid data dupplication. This may seem complicated at first, but once you take a closer look, it is not only easy to grasp, but the many benefits of modelview programming also become clearer. - -\raw HTML - -\endraw - -\raw HTML - - -
-\endraw - -\raw HTML -

Contents:

-\endraw - - \list 1 - \o \l{modelview-part1.html}{Introduction} - \o \l{modelview-part2.html}{Developing a Simple Model/View Application} - \o \l{modelview-part3.html}{Intermediate Topics} - \o \l{modelview-part4.html}{Good Sources of Additional Information} - \endlist - -\raw HTML -
-\endraw - - -\raw HTML -
-\endraw - \raw HTML -

- \endraw - \omit - It doesn't cover everything; the emphasis is on teaching the programming - philosophy of Model/View programming, and Qt's features are introduced as - needed. Some commonly used features are never used in this tutorial. - \endomit - - In the process, we will learn about some basic technologies provided by Qt, such as: + In the process, we will learn about some basic technologies provided by Qt, + such as: \list \o The difference between standard and model/view widgets \o Adapters betweeen forms and models \o Developing a simple model/view application - \o Predefined models + \o Predefined models \o Intermediate topics such as: \list \o Tree views @@ -103,65 +67,27 @@ Table, list and tree widgets are components frequently used in GUIs. There are 2 \o Debugging with model test \endlist \endlist - - - \raw HTML -
- \endraw - You will also learn whether your new application can be written easier with ModelView programming or if classic widgets will work just as well. - \raw HTML -
- \endraw - This tutorial includes example code for you to edit and integrate into your project. The tutorial's source code is located in Qt's \c examples/tutorials/modelview directory. - \raw HTML -
- \endraw - For more detailed information you may also want to look at the \l {model-view-programming.html}{reference documentation} + You will also learn whether your new application can be written easier with + model/view programming or if classic widgets will work just as well. + This tutorial includes example code for you to edit and integrate into your + project. The tutorial's source code is located in Qt's + \c examples/tutorials/modelview directory. -\raw HTML -
-\endraw - - \raw HTML -

- \endraw - - + For more detailed information you may also want to look at the + \l{model-view-programming.html}{reference documentation} - \image treeview.png + If you are completely new to Qt, please read \l{How to Learn Qt} if you + have not already done so. -\raw HTML -
-\endraw - - - - \raw HTML -
- \endraw - If you are completely new to Qt, please read \l{How to Learn Qt} if you have not already done so. - - -*/ - -/*! - \page modelview-part1.html - \contentspage {modelview.html}{Model/View Contents} - \previouspage {modelview.html}{Model/View Contents} - \nextpage {modelview-part2.html}{Developing a Simple Model/View Application} - \title An Introduction to Model/View Programming - \raw HTML -
- \endraw \section1 1. Introduction - Model/View is a technology used to separate data from views in widgets that handle data sets. Standard widgets are not designed for separating data from views and this is why Qt 4 has two different types of widgets. Both types of widgets look the same, but they interact with data differently. + Model/View is a technology used to separate data from views in widgets that + handle data sets. Standard widgets are not designed for separating data + from views and this is why Qt 4 has two different types of widgets. Both + types of widgets look the same, but they interact with data differently. \table \row @@ -174,23 +100,45 @@ Table, list and tree widgets are components frequently used in GUIs. There are 2 \section2 1.1 Standard Widgets - Let's have a closer look at a standard table widget. A table widget is a 2D array of the data elements that the user can change. The table widget can be integrated into a program flow by reading and writing the data elements that the table widget provides. This method is very intuitive and useful in many applications. + Let's have a closer look at a standard table widget. A table widget is a 2D + array of the data elements that the user can change. The table widget can be + integrated into a program flow by reading and writing the data elements that + the table widget provides. This method is very intuitive and useful in many + applications. - Displaying and editing a database table with a standard table widget can be problematic. Two copies of the data have to be coordinated: one outside the widget; one inside the widget. The developer is responsible for synchronizing both versions. The tight coupling of presentation and data makes it harder to write unit tests. + Displaying and editing a database table with a standard table widget can be + problematic. Two copies of the data have to be coordinated: one outside the + widget; one inside the widget. The developer is responsible for + synchronizing both versions. The tight coupling of presentation and data + makes it harder to write unit tests. \section2 1.2 Model/View to the Rescue - Model/view stepped up to provide a solution that uses a more versatile architecture. Model/view eliminates the data consistency problems that may occur with standard widgets. Model/view also makes it easier to use more than one view of the same data because one model can be passed on to many views. The most important difference is that model/view widgets do not store data behind the table cells. In fact, they operate directly from your data. Since view classes do not know your data's structure, you need to provide a wrapper to make your data conform to the QAbstractItemModel interface. A view uses this interface to read from and write to your data. Any instance of a class that implements QAbstractItemModel is said to be a model. Once the view receives a pointer to a model, it will read and display its content and be its editor. + Model/view stepped up to provide a solution that uses a more versatile + architecture. Model/view eliminates the data consistency problems that may + occur with standard widgets. Model/view also makes it easier to use more + than one view of the same data because one model can be passed on to many + views. The most important difference is that model/view widgets do not store + data behind the table cells. In fact, they operate directly from your data. + Since view classes do not know your data's structure, you need to provide a + wrapper to make your data conform to the QAbstractItemModel interface. A + view uses this interface to read from and write to your data. Any instance + of a class that implements QAbstractItemModel is said to be a model. Once + the view receives a pointer to a model, it will read and display its content + and be its editor. \section2 1.3 Overview of the Model/View Widgets - Here is an overview of the model/view widgets and their corresponding standard widgets. + Here is an overview of the model/view widgets and their corresponding + standard widgets. \table \header \o Widget - \o Standard Widget (an item based convenience class) - \o Model/View View Class (for use with external data) + \o Standard Widget\br + (an item based convenience class) + \o Model/View View Class\br + (for use with external data) \row \o \inlineimage listview.png \o \l QListWidget @@ -217,125 +165,110 @@ Table, list and tree widgets are components frequently used in GUIs. There are 2 Having adapters between forms and models can come in handy. - We can edit data stored in tables directly from within the table itself, but it's much more comfortable to edit data in text fields. There is no direct model/view counterpart that separates data and views for widgets that operate on one value (QLineEdit, QCheckBox ...) instead of a dataset, so we need an adapter in order to connect the form to the source of data. + We can edit data stored in tables directly from within the table itself, but + it's much more comfortable to edit data in text fields. There is no direct + model/view counterpart that separates data and views for widgets that + operate on one value (QLineEdit, QCheckBox ...) instead of a dataset, so we + need an adapter in order to connect the form to the source of data. - \l QDataWidgetMapper is a great solution because it maps form widgets to a table row and makes it very easy to build forms for database tables. + \l QDataWidgetMapper is a great solution because it maps form widgets to a + table row and makes it very easy to build forms for database tables. \image widgetmapper.png - - Another example of an adapter is \l QCompleter. Qt has \l QCompleter for providing auto-completions in Qt widgets such as \l QComboBox and, as shown below, \l QLineEdit. \l QCompleter uses a model as its data source. - - \image qcompleter.png - - -\raw HTML -
-
-
-
-
-\endraw -\raw HTML -

-previous page -

-\endraw + Another example of an adapter is \l QCompleter. Qt has \l QCompleter for + providing auto-completions in Qt widgets such as \l QComboBox and, as shown + below, \l QLineEdit. \l QCompleter uses a model as its data source. -\raw HTML -

-next page -

-\endraw + \image qcompleter.png -*/ -/*! - \page modelview-part2-main-cpp.html - \title main.cpp - \quotefile tutorials/modelview/1_readonly/main.cpp -*/ - -/*! - \page modelview-part2.html - \contentspage {modelview-index.html}{Model/View Contents} - \previouspage {modelview-part1.html}{Introduction} - \nextpage {modelview-part3.html}{Intermediate Topics} - \title Model/View Chapter 2 - A Simple Model/View Application - \raw HTML -
- \endraw \section1 2. A Simple Model/View Application If you want to develop a model/view application, where should you start? We recommend starting with a simple example and extending it step-by-step. This makes understanding the architecture a lot easier. Trying to understand the model/view architecture in detail before invoking the IDE has proven to be less convenient for many developers. It is substantially easier to start with a simple model/view application that has demo data. Give it a try! Simply replace the data in the examples below with your own. - Below are 7 very simple and independent applications that show different sides of model/view programming. The source code can be found inside the \c{examples/tutorials/modelview} directory. + Below are 7 very simple and independent applications that show different + sides of model/view programming. The source code can be found inside the + \c{examples/tutorials/modelview} directory. \section2 2.1 A Read Only Table - We start with an application that uses a QTableView to show data. We will add editing capabilities later. - \raw HTML -
- \endraw - (file source: examples/tutorials/modelview/1_readonly/main.cpp) + + We start with an application that uses a QTableView to show data. We will + add editing capabilities later. + + (file source: examples/tutorials/modelview/1_readonly/main.cpp) \snippet examples/tutorials/modelview/1_readonly/main.cpp Quoting ModelView Tutorial We have the usual \l {modelview-part2-main-cpp.html}{main()} function: - \raw HTML -
- \endraw - - Here is the interesting part: We create an instance of MyModel and use \l{QTableView::setModel()}{tableView.setModel( &myModel );} to pass a pointer of it to to \l {QTableView}{tableView}. \l{QTableView}{tableView} will invoke the methods of the pointer it has received to find out two things: + Here is the interesting part: We create an instance of MyModel and use + \l{QTableView::setModel()}{tableView.setModel(&myModel);} to pass a + pointer of it to to \l{QTableView}{tableView}. \l{QTableView}{tableView} + will invoke the methods of the pointer it has received to find out two + things: \list - \o How many rows and columns should be displayed - \o What content should be printed into each cell. + \o How many rows and columns should be displayed. + \o What content should be printed into each cell. \endlist The model needs some code to respond to this. - We have a table data set, so let's start with QAbstractTableModel since it is easier to use than the more general QAbstractItemModel. - + We have a table data set, so let's start with QAbstractTableModel since it + is easier to use than the more general QAbstractItemModel. - \raw HTML -
- \endraw (file source: examples/tutorials/modelview/1_readonly/mymodel.h) \snippet examples/tutorials/modelview/1_readonly/mymodel.h Quoting ModelView Tutorial QAbstractTableModel requires the implementation of three abstract methods. - \raw HTML -
- \endraw (file source: examples/tutorials/modelview/1_readonly/mymodel.cpp) \snippet examples/tutorials/modelview/1_readonly/mymodel.cpp Quoting ModelView Tutorial - The number of rows and columns is provided by \l{QAbstractItemModel::rowCount()}{MyModel::rowCount()} and \l{QAbstractItemModel::columnCount()}{MyModel::columnCount()}. When the view has to know what the cell's text is, it calls the method \l{QAbstractItemModel::data()}{MyModel::data()}. Row and column information is specified with parameter \c index and the role is set to \l{Qt::ItemDataRole}{Qt::DisplayRole}. Other roles are covered in the next section. In our example, the data that should be displayed is generated. In a real application, \c MyModel would have a member called \c MyData, which serves as the target for all reading and writing operations. - - This small example demonstrates the passive nature of a model. The model does not know when it will be used or which data is needed. It simply provides data each time the view requests it. - - What happens when the model 's data needs to be changed? How does the view realize that data has changed and needs to be read again? The model has to emit a signal that indicates what range of cells has changed. This will be demonstrated in section 2.3. + The number of rows and columns is provided by + \l{QAbstractItemModel::rowCount()}{MyModel::rowCount()} and + \l{QAbstractItemModel::columnCount()}{MyModel::columnCount()}. When the view + has to know what the cell's text is, it calls the method + \l{QAbstractItemModel::data()}{MyModel::data()}. Row and column information + is specified with parameter \c index and the role is set to + \l{Qt::ItemDataRole}{Qt::DisplayRole}. Other roles are covered in the next + section. In our example, the data that should be displayed is generated. In + a real application, \c MyModel would have a member called \c MyData, which + serves as the target for all reading and writing operations. + + This small example demonstrates the passive nature of a model. The model + does not know when it will be used or which data is needed. It simply + provides data each time the view requests it. + + What happens when the model's data needs to be changed? How does the view + realize that data has changed and needs to be read again? The model has to + emit a signal that indicates what range of cells has changed. This will be + demonstrated in section 2.3. \section2 2.2 Extending the Read Only Example with Roles - In addition to controlling what text the view displays, the model also controls the text's appearance. When we slightly change the model, we get the following result: \image readonlytable_role.png - - In fact, nothing except for the \l{QAbstractItemModel::}{data()} method needs to be changed to set fonts, background colour, alignment and a checkbox. Below is the \l{QAbstractItemModel::data()}{data()} method that produces the result shown above. The difference is that this time we use parameter int role to return different pieces of information depending on its value. + In addition to controlling what text the view displays, the model also + controls the text's appearance. When we slightly change the model, we get + the following result: \image readonlytable_role.png + In fact, nothing except for the \l{QAbstractItemModel::}{data()} method + needs to be changed to set fonts, background colour, alignment and a + checkbox. + Below is the \l{QAbstractItemModel::data()}{data()} method that produces the + result shown above. The difference is that this time we use parameter int + role to return different pieces of information depending on its value. - \raw HTML -
- \endraw (file source: examples/tutorials/modelview/2_formatting/mymodel.cpp) \snippet examples/tutorials/modelview/2_formatting/mymodel.cpp Quoting ModelView Tutorial - Each formatting property will be requested from the model with a separate call to the \l{QAbstractItemModel::data()}{data()} method. The \c role parameter is used to let the model know which property is being requested: + Each formatting property will be requested from the model with a separate + call to the \l{QAbstractItemModel::data()}{data()} method. The \c role + parameter is used to let the model know which property is being requested: \table \header \o \l{Qt::ItemDataRole}{enum Qt::ItemDataRole} \o Meaning - \o Type + \o Type \row \o \l{Qt::ItemDataRole}{}Qt::DisplayRole \o text @@ -351,54 +284,60 @@ Table, list and tree widgets are components frequently used in GUIs. There are 2 \row \o \l{Qt::ItemDataRole}{Qt::TextAlignmentRole} \o text alignment - \o \l{Qt::AlignmentFlag-enum}{enum Qt::AlignmentFlag} - \row - \o {1, 3} \l{Qt::ItemDataRole}{Qt::CheckStateRole} - \o {1, 3} suppresses checkboxes with \l{QVariant}{QVariant()}, - - sets checkboxes with \l{Qt::CheckState-enum}{Qt::Checked} - - or \l{Qt::CheckState-enum}{Qt::Unchecked} - \o {1, 3} \l{Qt::ItemDataRole}{enum Qt::ItemDataRole} - \endtable + \o \l{Qt::AlignmentFlag}{enum Qt::AlignmentFlag} + \row + \o {1, 3} \l{Qt::ItemDataRole}{Qt::CheckStateRole} + \o {1, 3} suppresses checkboxes with \l{QVariant}{QVariant()}, + + sets checkboxes with \l{Qt::CheckState}{Qt::Checked} - Refer to the Qt namespace documentation to learn more about the \l{Qt::ItemDataRole}{Qt::ItemDataRole} enum's capabilities. + or \l{Qt::CheckState}{Qt::Unchecked} + \o {1, 3} \l{Qt::ItemDataRole}{enum Qt::ItemDataRole} + \endtable - Now we need to determine how using a separated model impacts the application's performance, so let's trace how often the view calls the \l{QAbstractItemModel::}{data()} method. In order to track how often the view calls the model, we have put a debug statement in the \l{QAbstractItemModel::}{data()} method, which logs onto stdio. In our small example, \l{QAbstractItemModel::}{data()} will be called 42 times. - Each time you hover the cursor over the field, \l{QAbstractItemModel::}{data()} will be called again \mdash 7 times for each cell. That's why it is important to make sure that your data is available when \l{QAbstractItemModel::}{data()} is invoked and expensive lookup operations are cached. + Refer to the Qt namespace documentation to learn more about the + \l{Qt::ItemDataRole}{Qt::ItemDataRole} enum's capabilities. + + Now we need to determine how using a separated model impacts the + application's performance, so let's trace how often the view calls the + \l{QAbstractItemModel::}{data()} method. In order to track how often the + view calls the model, we have put a debug statement in the + \l{QAbstractItemModel::}{data()} method, which logs onto the error output + stream. In our small example, \l{QAbstractItemModel::}{data()} will be + called 42 times. + Each time you hover the cursor over the field, + \l{QAbstractItemModel::}{data()} will be called again \mdash 7 times for + each cell. That's why it is important to make sure that your data is + available when \l{QAbstractItemModel::}{data()} is invoked and expensive + lookup operations are cached. \section2 2.3 A Clock inside a Table Cell \image clock.png - We still have a read only table, but this time the content changes every second because we are showing the current time. - + We still have a read only table, but this time the content changes every + second because we are showing the current time. - \raw HTML -
- \endraw (file source: examples/tutorials/modelview/3_changingmodel/mymodel.cpp) \snippet examples/tutorials/modelview/3_changingmodel/mymodel.cpp quoting mymodel_QVariant - Something is missing to make the clock tick. We need to tell the view every second that the time has changed and that it needs to be read again. We do this with a timer. In the constructor, we set its interval to 1 second and connect its timeout signal. - + Something is missing to make the clock tick. We need to tell the view every + second that the time has changed and that it needs to be read again. We do + this with a timer. In the constructor, we set its interval to 1 second and + connect its timeout signal. - \raw HTML -
- \endraw (file source: examples/tutorials/modelview/3_changingmodel/mymodel.cpp) \snippet examples/tutorials/modelview/3_changingmodel/mymodel.cpp quoting mymodel_a Here is the corresponding slot: - - \raw HTML -
- \endraw (file source: examples/tutorials/modelview/3_changingmodel/mymodel.cpp) \snippet examples/tutorials/modelview/3_changingmodel/mymodel.cpp quoting mymodel_b - We ask the view to read the data in the top left cell again by emitting the \l{QAbstractItemModel::}{dataChanged()} signal. Note that we did not explicitly connect the \l{QAbstractItemModel::}{dataChanged()} signal to the view. This happened automatically when we called \l{QTableView::}{setModel()}. + We ask the view to read the data in the top left cell again by emitting the + \l{QAbstractItemModel::}{dataChanged()} signal. Note that we did not + explicitly connect the \l{QAbstractItemModel::}{dataChanged()} signal to the + view. This happened automatically when we called \l{QTableView::}{setModel()}. \section2 2.4 Setting up Headers for Columns and Rows @@ -408,147 +347,141 @@ Table, list and tree widgets are components frequently used in GUIs. There are 2 The header content, however, is set via the model, so we reimplement the \l{QAbstractItemModel::headerData()}{headerData()} method: - - \raw HTML -
- \endraw (file source: examples/tutorials/modelview/4_headers/mymodel.cpp) \snippet examples/tutorials/modelview/4_headers/mymodel.cpp quoting mymodel_c - Note that method \l{QAbstractItemModel::headerData()}{headerData()} also has a parameter role which has the same meaning as in \l{QAbstractItemModel::data()}{MyModel::data()}. - \section2 2.5 The Minimal Editing Example - - In this example, we are going to build an application that automatically populates a window title with content by repeating values entered into table cells. To be able to access the window title easily we put the QTableView in a QMainWindow. + Note that method \l{QAbstractItemModel::headerData()}{headerData()} also has + a parameter role which has the same meaning as in + \l{QAbstractItemModel::data()}{MyModel::data()}. - The model decides whether editing capabilities are available . We only have to modify the model in order for the available editing capabilities to be enabled. This is done by reimplementing the following virtual methods: \l{QAbstractItemModel::}{setData()} and \l{QAbstractItemModel::}{flags()}. + \section2 2.5 The Minimal Editing Example + In this example, we are going to build an application that automatically + populates a window title with content by repeating values entered into table + cells. To be able to access the window title easily we put the QTableView in + a QMainWindow. + The model decides whether editing capabilities are available. We only have + to modify the model in order for the available editing capabilities to be + enabled. This is done by reimplementing the following virtual methods: + \l{QAbstractItemModel::}{setData()} and \l{QAbstractItemModel::}{flags()}. - \raw HTML -
- \endraw (file source: examples/tutorials/modelview/5_edit/mymodel.h) \snippet examples/tutorials/modelview/5_edit/mymodel.h Quoting ModelView Tutorial - We use \c the two-dimensional array QString m_gridData to store our data. This makes \c m_gridData the core of MyModel. The rest of \c MyModel acts like a wrapper and adapts \c m_gridData to the QAbstractItemModel interface. We have also introduced the \c editCompleted() signal, which makes it possible to transfer the modified text to the window title. + We use \c the two-dimensional array QString \c m_gridData to store our data. + This makes \c m_gridData the core of \c MyModel. The rest of \c MyModel acts + like a wrapper and adapts \c m_gridData to the QAbstractItemModel + interface. We have also introduced the \c editCompleted() signal, which + makes it possible to transfer the modified text to the window title. - \raw HTML -
- \endraw (file source: examples/tutorials/modelview/5_edit/mymodel.cpp) \snippet examples/tutorials/modelview/5_edit/mymodel.cpp quoting mymodel_e - \l{QAbstractItemModel::setData()}{setData()} will be called each time the user edits a cell. The \c index parameter tells us which field has been edited and \c value provides the result of the editing process. The role will always be set to \c Qt::EditRole because our cells only contain text. If a checkbox were present and user permissions are set to allow the checkbox to be selected, calls would also be made with the role set to \c Qt::CheckStateRole. - + \l{QAbstractItemModel::setData()}{setData()} will be called each time the + user edits a cell. The \c index parameter tells us which field has been + edited and \c value provides the result of the editing process. The role + will always be set to \l Qt::EditRole because our cells only contain text. + If a checkbox were present and user permissions are set to allow the + checkbox to be selected, calls would also be made with the role set to + \l Qt::CheckStateRole. - - \raw HTML -
- \endraw (file source: examples/tutorials/modelview/5_edit/mymodel.cpp) \snippet examples/tutorials/modelview/5_edit/mymodel.cpp quoting mymodel_f - Various properties of a cell can be adjusted with \l{QAbstractItemModel::flags()}{flags()}. - - \raw HTML -

Returning Qt::ItemIsEditable | Qt::ItemIsEnabled is enough to show an editor that a cell has been selected.

- \endraw - If editing one cell modifies more data than the data in that particular cell, the model must emit a \l{QAbstractItemModel::dataChanged()}{dataChanged()} signal in order for the data that has been changed to be read. - + Various properties of a cell can be adjusted with + \l{QAbstractItemModel::flags()}{flags()}. + Returning \l{Qt::ItemFlag}{Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled} + is enough to show an editor that a cell can be selected. -\raw HTML -
-
-
-
-
-\endraw + If editing one cell modifies more data than the data in that particular + cell, the model must emit a \l{QAbstractItemModel::}{dataChanged()} signal + in order for the data that has been changed to be read. -\raw HTML -

-previous page -

-\endraw -\raw HTML -

-next page -

-\endraw - -*/ - -/*! - \page modelview-part3.html - \contentspage {modelview-index.html}{Model/View Contents} - \previouspage {modelview-part2.html}{Developing a Simple Model/View Application} - \nextpage {modelview-part4.html}{Good Sources of Additional Information} - \title Model/View Chapter 3 - Intermediate Topics -\raw HTML -
-\endraw \section1 3. Intermediate Topics -\raw HTML -
-\endraw + \section2 3.1 TreeView - You can convert the example above into an application with a tree view. Simply replace QTableView with QTreeView, which results in a read/write tree. No changes have to be made to the model. The tree won't have any hierarchies because there aren't any hierarchies in the model itself. + You can convert the example above into an application with a tree view. + Simply replace QTableView with QTreeView, which results in a read/write + tree. No changes have to be made to the model. The tree won't have any + hierarchies because there aren't any hierarchies in the model itself. + \image dummy_tree.png + QListView, QTableView and QTreeView all use a model abstraction, which is a + merged list, table and tree. This makes it possible to use several different + types of view classes from the same model. - QListView, QTableView and QTreeView all use a model abstraction, which is a merged list, table and tree. This makes it possible to use several different types of view classes from the same model. \image list_table_tree.png - This is how our example model looks so far: - \image example_model.png + \image example_model.png - We want to present a real tree. We have wrapped our data in the examples above in order to make a model. This time we use QStandardItemModel, which is a container for hierarchical data that also implements QAbstractItemModel. To show a tree, QStandardItemModel must be populated with \l{QStandardItem}{QStandardItems}, which are able to hold all the standard properties of items like text, fonts, checkboxes or brushes. \image tree_2_with_algorithm.png + We want to present a real tree. We have wrapped our data in the examples + above in order to make a model. This time we use QStandardItemModel, which + is a container for hierarchical data that also implements + QAbstractItemModel. To show a tree, QStandardItemModel must be populated + with \l{QStandardItem}s, which are able to hold all the standard properties + of items like text, fonts, checkboxes or brushes. + \image tree_2_with_algorithm.png - \raw HTML -
- \endraw (file source: examples/tutorials/modelview/6_treeview/mainwindow.cpp) - \snippet examples/tutorials/modelview/6_treeview/mainwindow.cpp Quoting ModelView Tutorial - We simply instantiate a QStandardItemModel and add a couple of \l{QStandardItem}{QStandardItems} to the constructor. We can then make a hierarchical data structure because a QStandardItem can hold other \l{QStandardItem}{QStandardItems}. Nodes are collapsed and expanded within the view. + We simply instantiate a QStandardItemModel and add a couple of + \l{QStandardItem}{QStandardItems} to the constructor. We can then make a + hierarchical data structure because a QStandardItem can hold other + \l{QStandardItem}{QStandardItems}. Nodes are collapsed and expanded within + the view. \section2 3.2 Working with Selections We want to access a selected item's content in order to output it into the window title together with the hierarchy level. + \image selection2.png So let's create a couple of items: - - \raw HTML -
-

(file source: examples/tutorials/modelview/7_selections/mainwindow.cpp)

- \endraw + (file source: examples/tutorials/modelview/7_selections/mainwindow.cpp) \snippet examples/tutorials/modelview/7_selections/mainwindow.cpp quoting modelview_a - Views manage selections within a separate selection model, which can be retrieved with the \l{QAbstractItemView::}{selectionModel()} method. We retrieve the selection Model in order to connect a slot to its \l{QAbstractItemView::}{selectionChanged()} signal. - + Views manage selections within a separate selection model, which can be + retrieved with the \l{QAbstractItemView::}{selectionModel()} method. We + retrieve the selection Model in order to connect a slot to its + \l{QAbstractItemView::}{selectionChanged()} signal. - \raw HTML -
-

(file source: examples/tutorials/modelview/7_selections/mainwindow.cpp)

- \endraw + (file source: examples/tutorials/modelview/7_selections/mainwindow.cpp) \snippet examples/tutorials/modelview/7_selections/mainwindow.cpp quoting modelview_b - We get the model index that corresponds to the selection by calling \l{QItemSelectionModel::currentIndex()}{treeView->selectionModel()->currentIndex()} and we get the the field's string by using the model index. Then we just calculate the item's \c hierarchyLevel. Top level items do not have parents and the \l{QAbstractItemModel::}{parent()} method will return a default constructed \l{QModelIndex}{QModelIndex()}. This is why we use the \l{QAbstractItemModel::}{parent()} method to iterate to the top level while counting the steps performed during iteration. - - The selection model (as shown above) can be retrieved, but it can also be set with \l{QAbstractItemView}{QAbstractItemView::setSelectionModel}. This is how it's possible to have 3 view classes with synchronised selections because only one instance of a selection model is used. To share a selection model between 3 views use \l{QAbstractItemView::}{selectionModel()} and assign the result to the second and third view class with \l{QAbstractItemView::}{setSelectionModel()}. + We get the model index that corresponds to the selection by calling + \l{QItemSelectionModel::currentIndex()}{treeView->selectionModel()->currentIndex()} + and we get the the field's string by using the model index. Then we just + calculate the item's \c hierarchyLevel. Top level items do not have parents + and the \l{QAbstractItemModel::}{parent()} method will return a default + constructed \l{QModelIndex}{QModelIndex()}. This is why we use the + \l{QAbstractItemModel::}{parent()} method to iterate to the top level while + counting the steps performed during iteration. + + The selection model (as shown above) can be retrieved, but it can also be + set with \l{QAbstractItemView}{QAbstractItemView::setSelectionModel}. This + is how it's possible to have 3 view classes with synchronised selections + because only one instance of a selection model is used. To share a selection + model between 3 views use \l{QAbstractItemView::}{selectionModel()} and + assign the result to the second and third view class with + \l{QAbstractItemView::}{setSelectionModel()}. \section2 3.3 Predefined Models - The typical way to use model/view is to wrap specific data to make it usable with view classes. Qt, however, also provides predefined models for common underlying data structures. If one of the available data structures is suitable for your application, a predefined model can be a good choice. + The typical way to use model/view is to wrap specific data to make it usable + with view classes. Qt, however, also provides predefined models for common + underlying data structures. If one of the available data structures is + suitable for your application, a predefined model can be a good choice. \table \row @@ -578,21 +511,30 @@ Table, list and tree widgets are components frequently used in GUIs. There are 2 \section2 3.4 Delegates - In all examples so far, data is presented as text or a checkbox in a cell and is edited as text or a checkbox. The component that provides these presentation and editing services is called a \e delegate. We are only just beginning to work with the delegate because the view uses a default delegate. But imagine that we want to have a different editor.(e.g. a slider or a drop down list) Or imagine that we want to present data as graphics. Let's take a look at an example called \l{Star Delegate Example}{Star Delegate}, in which stars are used to show a rating: - \raw HTML -

- (Star Delegate Example)

- \endraw + In all examples so far, data is presented as text or a checkbox in a cell + and is edited as text or a checkbox. The component that provides these + presentation and editing services is called a \e delegate. We are only just + beginning to work with the delegate because the view uses a default + delegate. But imagine that we want to have a different editor (e.g., a + slider or a drop down list) Or imagine that we want to present data as + graphics. + Let's take a look at an example called \l{Star Delegate Example}{Star + Delegate}, in which stars are used to show a rating: + \image stardelegate.png - The view has a method that replaces the default delegate and installs a custom delegate. This method is called \l{QAbstractItemView::}{setItemDelegate()}. A new delegate can be written by creating a class that inherits from QStyledItemDelegate. In order to write a delegate that displays stars and has no input capabilities, we only need to overwrite 2 methods. + The view has a \l{QAbstractItemView::}{setItemDelegate()} method that + replaces the default delegate and installs a custom delegate. + A new delegate can be written by creating a class that inherits from + QStyledItemDelegate. In order to write a delegate that displays stars and + has no input capabilities, we only need to override 2 methods. \code class StarDelegate : public QStyledItemDelegate { Q_OBJECT public: - StarDelegate(QWidget *parent = 0); + StarDelegate(QWidget *parent = 0); void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; QSize sizeHint(const QStyleOptionViewItem &option, @@ -600,105 +542,52 @@ Table, list and tree widgets are components frequently used in GUIs. There are 2 }; \endcode - \l{QStyledItemDelegate::}{paint()} draws stars depending on the content of the underlying data. The data can be looked up with parameter \l{QModelIndex::data()}{index.data()}. \l{QAbstractItemDelegate::}{sizeHint()} specifies each star's dimensions so the the cell will provide enough height and width to accommodate the stars. + \l{QStyledItemDelegate::}{paint()} draws stars depending on the content of + the underlying data. The data can be looked up by calling + \l{QModelIndex::data()}{index.data()}. The delegate's + \l{QAbstractItemDelegate::}{sizeHint()} method is used to obtain each + star's dimensions, so the the cell will provide enough height and width to + accommodate the stars. - Writing custom delegates is the right choice if you want to show your data with a custom graphical representation inside the grid of the view class. If you want to leave the grid, you would not use a custom delegate but a custom view class. + Writing custom delegates is the right choice if you want to show your data + with a custom graphical representation inside the grid of the view class. If + you want to leave the grid, you would not use a custom delegate but a custom + view class. -Other references to delegates in Qt Documentation: -\raw HTML -

-Spin Box Delegate Example
-QAbstractItemDelegate Class Reference
-QSqlRelationalDelegate Class Reference
-QStyledItemDelegate Class Reference
-QItemDelegate Class Reference
-

-

-\endraw + Other references to delegates in Qt Documentation: + \list + \o \l{Spin Box Delegate Example} + \o \l{QAbstractItemDelegate}{QAbstractItemDelegate Class Reference} + \o \l{QSqlRelationalDelegate}{QSqlRelationalDelegate Class Reference} + \o \l{QStyledItemDelegate}{QStyledItemDelegate Class Reference} + \o \l{QItemDelegate}{QItemDelegate Class Reference} + \endlist \section2 3.5 Debugging with ModelTest - The passive nature of models provides new challenges for programmers. Inconsistencies in the model can cause the application to crash. Since the model is hit by numerous calls from the view, it is hard to find out which call has crashed the application and which operation has introduced the problem. - - Qt provides software called \l{http://labs.qt.nokia.com/page/Projects/Itemview/Modeltest}{ModelTest}, which checks models while your programming is running. Every time the model is changed, ModelTest scans the model and reports errors with an assert. This is especially important for tree models, since their hierarchical nature leaves many possibilities for subtle inconsistencies. - - Unlike view classes, ModelTest uses out of range indexes to test the model. This means your application may crash with ModelTest even if it runs perfectly without it. So you also need to handle all of the indexes that are out of range when using ModelTest. - - - \section2 3.6 Model/View NG - - \raw HTML - -
- \endraw - - \raw HTML - - \endraw - - Model/View was introduced in Qt 4.0 and is a frequently used technology. Feedback from developers and new development trends have shown that there is a need to further develop the model/view technology. Therefore a research project originated at Nokia is looking into ways to go beyond the current implementation. - \raw HTML -

- \endraw - One limitation of model/view is that view classes are basically all fixed grids. It is possible, but really hard to make a list view with icons placed on a curve; or cells expanding on mouse over events to show additional information. In order to achieve graphically rich view experiences, Model/View NG will use QGraphicsView to render elements. Nodel/View NG also aims to make model/view programming more intuitive. One way to achieve this is to have separate models for lists, tables and trees. The current model abstraction is complex because it is capable of representing a list, a table or a tree. - \raw HTML -

- \endraw - Model/View NG is a research project. You are welcome to checkout the source code, monitor progress and take part in discussions at the following address: \l{http://labs.qt.nokia.com/page/Projects/Itemview/ItemviewsNG} - + The passive nature of models provides new challenges for programmers. + Inconsistencies in the model can cause the application to crash. Since the + model is hit by numerous calls from the view, it is hard to find out which + call has crashed the application and which operation has introduced the + problem. + Qt Labs provides software called + \l{http://labs.qt.nokia.com/page/Projects/Itemview/Modeltest}{ModelTest}, + which checks models while your programming is running. Every time the model + is changed, ModelTest scans the model and reports errors with an assert. + This is especially important for tree models, since their hierarchical + nature leaves many possibilities for subtle inconsistencies. + Unlike view classes, ModelTest uses out of range indexes to test the model. + This means your application may crash with ModelTest even if it runs + perfectly without it. So you also need to handle all of the indexes that are + out of range when using ModelTest. -\raw HTML -

-\endraw - - \raw HTML -
- \endraw - - \image path.png - - \raw HTML -
- \endraw - -\raw HTML -
-
-
-
-\endraw - - -\raw HTML -

-previous page -

-\endraw - -\raw HTML -

-last page -

-\endraw -*/ - -/*! - \page modelview-part4.html - \contentspage {modelview-index.html}{Model/View Contents} - \previouspage {modelview-part3.html}{Intermediate Topics} - \title Model/View Chapter 4 - Good Sources of Additional Information -\raw HTML -
-\endraw \section1 4. Good Sources of Additional Information -\raw HTML -
-\endraw + \section2 4.1 Books Model/View programming is covered quite extensively in the documentation of @@ -716,16 +605,19 @@ Other references to delegates in Qt Documentation: \o \bold{Foundations of Qt Development} / Johan Thelin, \e{Apress}, ISBN 1-59059-831-8. \endlist - More information about these books is available on the \l{Books about Qt Programming}{Qt Web site}. + More information about these books is available on the + \l{Books about Qt Programming}{Qt Web site}. - The following list provides an overview of example programs contained in the books above. Some of them make very good templates for developing similar applications. + The following list provides an overview of example programs contained in the + books above. Some of them make very good templates for developing similar + applications. \table \header - \o example name - \o view class used - \o model used - \o aspects touched + \o Example name + \o View class used + \o Model used + \o Aspects covered \o \row \o Team Leaders @@ -751,26 +643,26 @@ Other references to delegates in Qt Documentation: \o QTableView \o custom model based on QAbstractTableModel - \o read only + \o Read only \o Book 1, Chapter 10, Figure 10.10 \row \o Cities \o QTableView - \o custom model based on + \o Custom model based on QAbstractTableModel - \o read / write + \o Read / write \o Book 1, Chapter 10, Figure 10.12 \row \o Boolean Parser \o QTreeView - \o custom model based on + \o Custom model based on QAbstractItemModel - \o read only + \o Read only \o Book 1, Chapter 10, Figure 10.14 \row \o Track Editor \o {2, 1} QTableWidget - \o custom delegate providing a custom editor + \o Custom delegate providing a custom editor \o Book 1, Chapter 10, Figure 10.15 \row @@ -779,47 +671,47 @@ Other references to delegates in Qt Documentation: QTableView QTreeView \o QDirModel - \o demonstrates the use of multiple views + \o Demonstrates the use of multiple views \o Book2, Chapter 8.2 \row \o Address Book \o QListView QTableView QTreeView - \o custom model based on + \o Custom model based on QAbstractTableModel - \o read / write + \o Read / write \o Book2, Chapter 8.4 \row \o Address Book with sorting \o \o QProxyModel - \o introducing sort and filter capabilities + \o Introducing sort and filter capabilities \o Book2, Chapter 8.5 \row \o Address Book with checkboxes \o \o - \o introducing checkboxes in model/view + \o Introducing checkboxes in model/view \o Book2, Chapter 8.6 \row \o Address Book with transposed grid \o - \o custom proxy Model based on QAbstractProxyModel - \o introducing a custom model + \o Custom proxy Model based on QAbstractProxyModel + \o Introducing a custom model \o Book2, Chapter 8.7 \row \o Address Book with drag and drop \o \o - \o introducing drag and drop support + \o Introducing drag and drop support \o Book2, Chapter 8.8 \row \o Address Book with custom editor \o \o - \o introducing custom delegates + \o Introducing custom delegates \o Book2, Chapter 8.9 \row \o Views @@ -827,51 +719,51 @@ Other references to delegates in Qt Documentation: QTableView QTreeView \o QStandardItemModel - \o read only + \o Read only \o Book 3, Chapter 5, figure 5-3 \row \o Bardelegate \o QTableView \o - \o custom delegate for presentation based on QAbstractItemDelegate + \o Custom delegate for presentation based on QAbstractItemDelegate \o Book 3, Chapter 5, figure 5-5 \row \o Editdelegate \o QTableView \o - \o custom delegate for editing based on QAbstractItemDelegate + \o Custom delegate for editing based on QAbstractItemDelegate \o Book 3, Chapter 5, figure 5-6 \row \o Singleitemview - \o custom view based on QAbstractItemView + \o Custom view based on QAbstractItemView \o - \o custom view + \o Custom view \o Book 3, Chapter 5, figure 5-7 \row \o listmodel \o QTableView - \o custom Model based on QAbstractTableModel - \o read only + \o Custom Model based on QAbstractTableModel + \o Read only \o Book 3, Chapter 5, Figure 5-8 \row \o treemodel \o QTreeView - \o custom Model based on QAbstractItemModel - \o read only + \o Custom Model based on QAbstractItemModel + \o Read only \o Book 3, Chapter 5, Figure 5-10 \row \o edit integers \o QListView - \o custom Model based on QAbstractListModel - \o read / write + \o Custom Model based on QAbstractListModel + \o Read / write \o Book 3, Chapter 5, Listing 5-37, Figure 5-11 \row \o sorting \o QTableView \o QSortFilterProxyModel applied to QStringListModel - \o demonstrates sorting + \o Demonstrates sorting \o Book 3, Chapter 5, Figure 5-12 \endtable @@ -879,19 +771,20 @@ Other references to delegates in Qt Documentation: \section2 4.2 Qt Documentation Qt 4.7 comes with 17 examples and 2 Demonstrations for model/view. - The examples can be found here: \l{Item Views Examples} + The examples can be found on the \l{Item Views Examples} page. + \table \header \o Example name \o View class used \o Model used - \o Aspects touched + \o Aspects covered \row \o Address Book \o QTableView \o QAbstractTableModel QSortFilterProxyModel - \o usage of QSortFilterProxyModel to generate different + \o Usage of QSortFilterProxyModel to generate different subsets from one data pool \row \o Basic Sort/Filter Model @@ -901,41 +794,41 @@ Other references to delegates in Qt Documentation: \o \row \o Chart - \o custom view + \o Custom view \o QStandardItemModel - \o designing custom views that cooperate with selection models + \o Designing custom views that cooperate with selection models \row \o Color Editor Factory \o {2, 1} QTableWidget - \o enhancing the standard delegate with a new custom editor to choose colours + \o Enhancing the standard delegate with a new custom editor to choose colours \row \o Combo Widget Mapper \o QDataWidgetMapper to map QLineEdit, QTextEdit and QComboBox \o QStandardItemModel - \o shows how a QComboBox can serve as a view class + \o Shows how a QComboBox can serve as a view class \row \o Custom Sort/Filter Model \o QTreeView \o QStandardItemModel QSortFilterProxyModel - \o subclass QSortFilterProxyModel for advanced sorting and filtering + \o Subclass QSortFilterProxyModel for advanced sorting and filtering \row \o Dir View \o QTreeView \o QDirModel - \o very small example to demonstrate how to assign a model to a view + \o Very small example to demonstrate how to assign a model to a view \row \o Editable Tree Model \o QTreeView - \o custom tree model - \o comprehensive example for working with trees, demonstrates + \o Custom tree model + \o Comprehensive example for working with trees, demonstrates editing cells and tree structure with an underlying custom model \row \o Fetch More \o QListView - \o custom list model - \o dynamically changing model + \o Custom list model + \o Dynamically changing model \row \o Frozen Column \o QTableView @@ -944,48 +837,57 @@ Other references to delegates in Qt Documentation: \row \o Pixelator \o QTableView - \o custom table model - \o implementation of a custom delegate + \o Custom table model + \o Implementation of a custom delegate \row \o Puzzle \o QListView - \o custom list model - \o model/view with drag and drop + \o Custom list model + \o Model/view with drag and drop \row \o Simple DOM Model \o QTreeView - \o custom tree model - \o read only example for a custom tree model + \o Custom tree model + \o Read only example for a custom tree model \row \o Simple Tree Model \o QTreeView - \o custom tree model - \o read only example for a custom tree model + \o Custom tree model + \o Read only example for a custom tree model \row \o Simple Widget Mapper \o QDataWidgetMapper to map QLineEdit, QTextEdit and QSpinBox \o QStandardItemModel - \o basic QDataWidgetMapper usage + \o Basic QDataWidgetMapper usage \row \o Spin Box Delegate \o QTableView \o QStandardItemModel - \o custom delegate that uses a spin box as a cell editor + \o Custom delegate that uses a spin box as a cell editor \row \o Star Delegate \o {2, 1} QTableWidget - \o comprehensive custom delegate example. + \o Comprehensive custom delegate example. \endtable - \l{Qt Demonstrations}{Demonstrations} are similar to examples except that no walkthrough is provided for the code lines. Demonstrations are also sometimes more feature rich. ( \l demos.html ) + \l{Qt Demonstrations}{Demonstrations} are similar to examples except that no + walkthrough is provided for the code. Demonstrations are typically more + feature rich than examples. \list \o The \bold Interview demonstration shows the same model and selection being shared between three different views. - \o Demonstration \bold Spreadsheet demonstrates the use of a + \o The \bold Spreadsheet demonstration illustrates the use of a table view as a spreadsheet, using custom delegates to render each item according to the type of data it contains. \endlist - A \l{Model/View Programming}{reference document} for model/view technology is also available. + A \l{Model/View Programming}{reference document} for model/view technology + is also available. +*/ + +/*! + \page modelview-part2-main-cpp.html + \title main.cpp + \quotefile tutorials/modelview/1_readonly/main.cpp */ -- cgit v0.12 From 94791e6d5be6859d87862d40233aece16d54932a Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Tue, 31 Aug 2010 13:52:14 +0200 Subject: doc: Remove \internal tag from QScriptProgram The class has been there since 4.6 (http://labs.trolltech.com/blogs/2009/11/23/qtscript-in-46/), but we don't see a reason to hide it any longer. Task-number: QTBUG-13229 Reviewed-by: Olivier Goffart --- src/script/api/qscriptengine.cpp | 3 +-- src/script/api/qscriptprogram.cpp | 4 +--- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/src/script/api/qscriptengine.cpp b/src/script/api/qscriptengine.cpp index 8347626..07aced4 100644 --- a/src/script/api/qscriptengine.cpp +++ b/src/script/api/qscriptengine.cpp @@ -2626,8 +2626,7 @@ QScriptValue QScriptEngine::evaluate(const QString &program, const QString &file } /*! - \internal - \since 4.6 + \since 4.7 Evaluates the given \a program and returns the result of the evaluation. diff --git a/src/script/api/qscriptprogram.cpp b/src/script/api/qscriptprogram.cpp index 02beba4..3857b75 100644 --- a/src/script/api/qscriptprogram.cpp +++ b/src/script/api/qscriptprogram.cpp @@ -32,9 +32,7 @@ QT_BEGIN_NAMESPACE /*! - \internal - - \since 4.6 + \since 4.7 \class QScriptProgram \brief The QScriptProgram class encapsulates a Qt Script program. -- cgit v0.12 From 0781e6e539b07872f5d2063594a2057f3e31c9ec Mon Sep 17 00:00:00 2001 From: Miikka Heikkinen Date: Tue, 31 Aug 2010 14:57:08 +0300 Subject: Fix gcce building of apps using static libraries in symbian-sbsv2 Removed usage of buggy .release_gcce target from symbian-sbsv2 generated makefiles. Now gcce builds like armv5 as it is supposed to when using Raptor. Task-number: QTBUG-13307 Reviewed-by: axis --- bin/createpackage.pl | 17 +++++++++++++++- bin/patch_capabilities.pl | 9 ++++++++- doc/src/platforms/symbian-introduction.qdoc | 1 + mkspecs/features/sis_targets.prf | 10 ++++++++-- mkspecs/symbian-sbsv2/flm/qt/qmake_store_build.flm | 2 +- mkspecs/symbian-sbsv2/flm/qt/qt.xml | 1 - qmake/generators/symbian/symmake_sbsv2.cpp | 23 +++++++++++++++------- 7 files changed, 50 insertions(+), 13 deletions(-) diff --git a/bin/createpackage.pl b/bin/createpackage.pl index 984c1fd..2569a66 100755 --- a/bin/createpackage.pl +++ b/bin/createpackage.pl @@ -81,11 +81,14 @@ Where supported options are as follows: [-o|only-unsigned] = Creates only unsigned package. [-s|stub] = Generates stub sis for ROM. [-n|sisname ] = Specifies the final sis name. + [-g|gcce-is-armv5] = Convert gcce platform to armv5. Where parameters are as follows: templatepkg = Name of .pkg file template target = Either debug or release platform = One of the supported platform winscw | gcce | armv5 | armv6 | armv7 + Note that when packaging binaries built using gcce and symbian-sbsv2 + mkspec, armv5 must be used for platform instead of gcce. certificate = The certificate file used for signing key = The certificate's private key file passphrase = The passphrase of the certificate's private key file @@ -123,6 +126,7 @@ my $preserveUnsigned = ""; my $stub = ""; my $signed_sis_name = ""; my $onlyUnsigned = ""; +my $convertGcce = ""; unless (GetOptions('i|install' => \$install, 'p|preprocess' => \$preprocessonly, @@ -130,7 +134,8 @@ unless (GetOptions('i|install' => \$install, 'u|unsigned' => \$preserveUnsigned, 'o|only-unsigned' => \$onlyUnsigned, 's|stub' => \$stub, - 'n|sisname=s' => \$signed_sis_name,)) { + 'n|sisname=s' => \$signed_sis_name, + 'g|gcce-is-armv5' => \$convertGcce,)) { Usage(); } @@ -146,6 +151,16 @@ $target = $tmpvalues[0] or $target = ""; my $platform; $platform = $tmpvalues[1] or $platform = ""; +if ($platform =~ m/^gcce$/i) { + if (($convertGcce ne "")) { + $platform = "armv5"; + } elsif ($ENV{SBS_HOME}) { + # Print a informative note in case suspected misuse is detected. + print "\nNote: You should use armv5 as platform or specify -g parameter to convert platform\n"; + print " when packaging gcce binaries built using symbian-sbsv2 mkspec.\n\n"; + } +} + # Convert visual target to real target (debug->udeb and release->urel) $target =~ s/debug/udeb/i; $target =~ s/release/urel/i; diff --git a/bin/patch_capabilities.pl b/bin/patch_capabilities.pl index 7d6f5dc..0c0538c 100755 --- a/bin/patch_capabilities.pl +++ b/bin/patch_capabilities.pl @@ -54,7 +54,9 @@ sub Usage() { print("If no capabilities are given, the binaries will be given the\n"); print("capabilities supported by self-signed certificates.\n\n"); print(" *** NOTE: If *_template.pkg file is given and one is using symbian-abld or\n"); - print(" symbian-sbsv2 platform, 'target-platform' is REQUIRED. ***\n"); + print(" symbian-sbsv2 platform, 'target-platform' is REQUIRED. ***\n\n"); + print(" *** NOTE2: When patching gcce binaries built with symbian-sbsv2 toolchain,\n"); + print(" armv5 must be specified as platform.\n"); print("\nUsage: patch_capabilities.pl pkg_filename [target-platform [capability list]]\n"); print("\nE.g. patch_capabilities.pl myapp_template.pkg release-armv5 \"All -TCB\"\n"); exit(); @@ -104,6 +106,11 @@ if (@ARGV) # Convert visual target to real target (debug->udeb and release->urel) $target =~ s/debug/udeb/i; $target =~ s/release/urel/i; + + if (($platform =~ m/^gcce$/i) && ($ENV{SBS_HOME})) { + # Print a informative note in case suspected misuse is detected. + print "\nNote: You must use armv5 as platform when packaging gcce binaries built using symbian-sbsv2 mkspec.\n"; + } } # If the specified ".pkg" file exists (and can be read), diff --git a/doc/src/platforms/symbian-introduction.qdoc b/doc/src/platforms/symbian-introduction.qdoc index 701707e..fafe007 100644 --- a/doc/src/platforms/symbian-introduction.qdoc +++ b/doc/src/platforms/symbian-introduction.qdoc @@ -219,6 +219,7 @@ \row \o -o \o Creates only unsigned package. \row \o -s \o Generates stub sis for ROM. \row \o -n \o Specifies the final sis name. + \row \o -g \o Treat gcce platform as armv5. \endtable Execute the \c{createpackage.pl} script without any diff --git a/mkspecs/features/sis_targets.prf b/mkspecs/features/sis_targets.prf index abdf2d4..e069ee1 100644 --- a/mkspecs/features/sis_targets.prf +++ b/mkspecs/features/sis_targets.prf @@ -11,6 +11,12 @@ else:!equals(DEPLOYMENT, default_deployment) { equals(GENERATE_SIS_TARGETS, true) { symbian-abld|symbian-sbsv2 { + symbian-sbsv2 { + CONVERT_GCCE_PARAM = -g + } else { + CONVERT_GCCE_PARAM = + } + make_cache_name = .make.cache sis_target.target = sis sis_target.commands = $(if $(wildcard $$basename(TARGET)_template.pkg), \ @@ -28,7 +34,7 @@ equals(GENERATE_SIS_TARGETS, true) { ) ok_sis_target.target = ok_sis - ok_sis_target.commands = createpackage.bat $(QT_SIS_OPTIONS) $$basename(TARGET)_template.pkg \ + ok_sis_target.commands = createpackage.bat $$CONVERT_GCCE_PARAM $(QT_SIS_OPTIONS) $$basename(TARGET)_template.pkg \ $(QT_SIS_TARGET) $(QT_SIS_CERTIFICATE) $(QT_SIS_KEY) $(QT_SIS_PASSPHRASE) unsigned_sis_target.target = unsigned_sis @@ -47,7 +53,7 @@ equals(GENERATE_SIS_TARGETS, true) { ) ok_unsigned_sis_target.target = ok_unsigned_sis - ok_unsigned_sis_target.commands = createpackage.bat $(QT_SIS_OPTIONS) -o $$basename(TARGET)_template.pkg $(QT_SIS_TARGET) + ok_unsigned_sis_target.commands = createpackage.bat $$CONVERT_GCCE_PARAM $(QT_SIS_OPTIONS) -o $$basename(TARGET)_template.pkg $(QT_SIS_TARGET) target_sis_target.target = $$basename(TARGET).sis target_sis_target.commands = $(MAKE) -f $(MAKEFILE) sis diff --git a/mkspecs/symbian-sbsv2/flm/qt/qmake_store_build.flm b/mkspecs/symbian-sbsv2/flm/qt/qmake_store_build.flm index 47c3f1e..21638ea 100644 --- a/mkspecs/symbian-sbsv2/flm/qt/qmake_store_build.flm +++ b/mkspecs/symbian-sbsv2/flm/qt/qmake_store_build.flm @@ -38,7 +38,7 @@ $(STORE_BUILD_TARGET): echo "# make sis target." >> $(CACHE_FILENAME) && \ echo "# Version : " >> $(CACHE_FILENAME) && \ echo "# ==============================================================================" >> $(CACHE_FILENAME) && \ - echo QT_SIS_TARGET ?= $(VISUAL_CFG)-$(VARIANTPLATFORM) >> $(CACHE_FILENAME) + echo QT_SIS_TARGET ?= $(VISUAL_CFG)-$(PLATFORM_PATH) >> $(CACHE_FILENAME) $(call endrule,qmake_store_build) endef diff --git a/mkspecs/symbian-sbsv2/flm/qt/qt.xml b/mkspecs/symbian-sbsv2/flm/qt/qt.xml index 12857a2..0f7db3c 100644 --- a/mkspecs/symbian-sbsv2/flm/qt/qt.xml +++ b/mkspecs/symbian-sbsv2/flm/qt/qt.xml @@ -37,6 +37,5 @@ - diff --git a/qmake/generators/symbian/symmake_sbsv2.cpp b/qmake/generators/symbian/symmake_sbsv2.cpp index 036eb1d..e794351 100644 --- a/qmake/generators/symbian/symmake_sbsv2.cpp +++ b/qmake/generators/symbian/symmake_sbsv2.cpp @@ -202,10 +202,18 @@ void SymbianSbsv2MakefileGenerator::writeWrapperMakefile(QFile& wrapperFile, boo QString genericClause = " -c %1_%2" + testClause; QString winscwClause = " -c winscw_%1.mwccinc" + testClause; QString gcceClause; - if (QString::compare(gcceVersion(), UNDETECTED_GCCE_VERSION) == 0) - allPlatforms.removeAll(PLATFORM_GCCE); - else - gcceClause = " -c arm.v5.%1." + gcceVersion() + ".release_gcce" + testClause; + bool stripArmv5 = false; + + if (allPlatforms.contains(PLATFORM_GCCE)) { + if (QString::compare(gcceVersion(), UNDETECTED_GCCE_VERSION) == 0) { + allPlatforms.removeAll(PLATFORM_GCCE); + } else { + gcceClause = " -c arm.v5.%1." + gcceVersion() + testClause; + // Since gcce building is enabled, do not add armv5 for any sbs command + // that also contains gcce, because those will build same targets. + stripArmv5 = true; + } + } QStringList allClauses; QStringList debugClauses; @@ -216,14 +224,15 @@ void SymbianSbsv2MakefileGenerator::writeWrapperMakefile(QFile& wrapperFile, boo releasePlatforms.removeAll(PLATFORM_WINSCW); // No release for emulator foreach(QString item, debugPlatforms) { - debugClauses << configClause(item, debugBuild, winscwClause, gcceClause, genericClause); + if (item != PLATFORM_ARMV5 || !stripArmv5) + debugClauses << configClause(item, debugBuild, winscwClause, gcceClause, genericClause); } foreach(QString item, releasePlatforms) { - releaseClauses << configClause(item, releaseBuild, winscwClause, gcceClause, genericClause); + if (item != PLATFORM_ARMV5 || !stripArmv5) + releaseClauses << configClause(item, releaseBuild, winscwClause, gcceClause, genericClause); } allClauses << debugClauses << releaseClauses; - QTextStream t(&wrapperFile); t << "# ==============================================================================" << endl; -- cgit v0.12 From c9459fed5a3c57fea8705979064b9c028bfdaa72 Mon Sep 17 00:00:00 2001 From: Benjamin Poulain Date: Tue, 31 Aug 2010 13:18:39 +0200 Subject: Undefined SSE symbols when crosscompiling Qt on PPC. Qt does not build on PowerPC when compiling for both x86 and PPC on Mac. The compiler is invoked only once for both architecture so the defines are there in order to get the optimized path for x86. Those defines needs to be removed from the compilation environment when the target is set to PPC by GCC. Reviewed-by: Kent Hansen --- src/corelib/tools/qsimd_p.h | 7 ++++++- src/gui/painting/qdrawhelper.cpp | 1 - src/gui/painting/qdrawhelper_p.h | 8 +------- src/gui/painting/qdrawhelper_sse2.cpp | 1 - src/gui/painting/qdrawhelper_ssse3.cpp | 3 +-- 5 files changed, 8 insertions(+), 12 deletions(-) diff --git a/src/corelib/tools/qsimd_p.h b/src/corelib/tools/qsimd_p.h index 2626657..664543b 100644 --- a/src/corelib/tools/qsimd_p.h +++ b/src/corelib/tools/qsimd_p.h @@ -51,8 +51,13 @@ QT_BEGIN_HEADER #if defined(QT_NO_MAC_XARCH) || (defined(Q_OS_DARWIN) && (defined(__ppc__) || defined(__ppc64__))) // Disable MMX and SSE on Mac/PPC builds, or if the compiler // does not support -Xarch argument passing -#undef QT_HAVE_SSE2 #undef QT_HAVE_SSE +#undef QT_HAVE_SSE2 +#undef QT_HAVE_SSE3 +#undef QT_HAVE_SSSE3 +#undef QT_HAVE_SSE4_1 +#undef QT_HAVE_SSE4_2 +#undef QT_HAVE_AVX #undef QT_HAVE_3DNOW #undef QT_HAVE_MMX #endif diff --git a/src/gui/painting/qdrawhelper.cpp b/src/gui/painting/qdrawhelper.cpp index 89754fa..5223458 100644 --- a/src/gui/painting/qdrawhelper.cpp +++ b/src/gui/painting/qdrawhelper.cpp @@ -46,7 +46,6 @@ #include #include #include -#include #include QT_BEGIN_NAMESPACE diff --git a/src/gui/painting/qdrawhelper_p.h b/src/gui/painting/qdrawhelper_p.h index 75f42a0..5747da5 100644 --- a/src/gui/painting/qdrawhelper_p.h +++ b/src/gui/painting/qdrawhelper_p.h @@ -62,6 +62,7 @@ #define QT_FT_END_HEADER #endif #include "private/qrasterdefs_p.h" +#include #ifdef Q_WS_QWS #include "QtGui/qscreen_qws.h" @@ -69,13 +70,6 @@ QT_BEGIN_NAMESPACE -#if defined(Q_OS_MAC) && (defined(__ppc__) || defined(__ppc64__)) -#undef QT_HAVE_MMX -#undef QT_HAVE_SSE -#undef QT_HAVE_SSE2 -#undef QT_HAVE_3DNOW -#endif - #if defined(Q_CC_MSVC) && _MSCVER <= 1300 && !defined(Q_CC_INTEL) #define Q_STATIC_TEMPLATE_SPECIALIZATION static #else diff --git a/src/gui/painting/qdrawhelper_sse2.cpp b/src/gui/painting/qdrawhelper_sse2.cpp index 30454af..5b674b5 100644 --- a/src/gui/painting/qdrawhelper_sse2.cpp +++ b/src/gui/painting/qdrawhelper_sse2.cpp @@ -43,7 +43,6 @@ #ifdef QT_HAVE_SSE2 -#include #include #include diff --git a/src/gui/painting/qdrawhelper_ssse3.cpp b/src/gui/painting/qdrawhelper_ssse3.cpp index 9c02009..4cb4089 100644 --- a/src/gui/painting/qdrawhelper_ssse3.cpp +++ b/src/gui/painting/qdrawhelper_ssse3.cpp @@ -39,11 +39,10 @@ ** ****************************************************************************/ +#include #ifdef QT_HAVE_SSSE3 -#include -#include #include QT_BEGIN_NAMESPACE -- cgit v0.12 From 9d92e1556b18db068891c0f33ff35c8f05059b73 Mon Sep 17 00:00:00 2001 From: Jens Bache-Wiig Date: Tue, 31 Aug 2010 15:13:21 +0200 Subject: Updated Twitter demo in response to the new Twitter oauth requirement Twitter is blocking access to the old authentification method that our demo was using. This breaks the demo completely. To fix this, I changed the demo into only make use of the public search API. You can no longer tweet but you can search for different tweets. At the moment making an oauth capable demo is not desirable due to the problems with handling a secret app token among other issues. Task-number: QTBUG-13181 Reviewed-by: Alan Alpert --- demos/declarative/twitter/TwitterCore/AuthView.qml | 146 ------------------- demos/declarative/twitter/TwitterCore/Button.qml | 2 +- .../twitter/TwitterCore/FatDelegate.qml | 36 ++++- .../twitter/TwitterCore/HomeTitleBar.qml | 161 --------------------- demos/declarative/twitter/TwitterCore/Input.qml | 65 +++++++++ .../twitter/TwitterCore/MultiTitleBar.qml | 7 +- demos/declarative/twitter/TwitterCore/RssModel.qml | 59 ++++---- .../declarative/twitter/TwitterCore/SearchView.qml | 124 ++++++++++++++++ demos/declarative/twitter/TwitterCore/TitleBar.qml | 80 +++++----- demos/declarative/twitter/TwitterCore/ToolBar.qml | 5 +- .../declarative/twitter/TwitterCore/UserModel.qml | 26 ++-- demos/declarative/twitter/TwitterCore/qmldir | 4 +- demos/declarative/twitter/twitter.qml | 74 +++++----- doc/src/examples/qml-twitter.qdoc | 4 +- 14 files changed, 332 insertions(+), 461 deletions(-) delete mode 100644 demos/declarative/twitter/TwitterCore/AuthView.qml delete mode 100644 demos/declarative/twitter/TwitterCore/HomeTitleBar.qml create mode 100644 demos/declarative/twitter/TwitterCore/Input.qml create mode 100644 demos/declarative/twitter/TwitterCore/SearchView.qml diff --git a/demos/declarative/twitter/TwitterCore/AuthView.qml b/demos/declarative/twitter/TwitterCore/AuthView.qml deleted file mode 100644 index 0d05deb..0000000 --- a/demos/declarative/twitter/TwitterCore/AuthView.qml +++ /dev/null @@ -1,146 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtDeclarative module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -import Qt 4.7 - -Item { - id: wrapper - Column { - anchors.centerIn: parent - spacing: 20 - Column{ - spacing: 4 - Text { - text: "Screen name:" - font.pixelSize: 16; font.bold: true; color: "white"; style: Text.Raised; styleColor: "black" - horizontalAlignment: Qt.AlignRight - } - Item { - width: 220 - height: 28 - BorderImage { source: "images/lineedit.sci"; anchors.fill: parent } - TextInput{ - id: nameIn - width: parent.width - 8 - anchors.centerIn: parent - maximumLength:21 - font.pixelSize: 16; - font.bold: true - color: "#151515"; selectionColor: "green" - KeyNavigation.tab: passIn - KeyNavigation.backtab: guest - focus: true - } - } - } - Column{ - spacing: 4 - Text { - text: "Password:" - font.pixelSize: 16; font.bold: true; color: "white"; style: Text.Raised; styleColor: "black" - horizontalAlignment: Qt.AlignRight - } - Item { - width: 220 - height: 28 - BorderImage { source: "images/lineedit.sci"; anchors.fill: parent } - TextInput{ - id: passIn - width: parent.width - 8 - anchors.centerIn: parent - maximumLength:21 - echoMode: TextInput.Password - font.pixelSize: 16; - font.bold: true - color: "#151515"; selectionColor: "green" - KeyNavigation.tab: login - KeyNavigation.backtab: nameIn - onAccepted: login.doLogin(); - } - } - } - Row{ - spacing: 10 - Button { - width: 100 - height: 32 - id: login - keyUsing: true; - function doLogin(){ - rssModel.authName=nameIn.text; - rssModel.authPass=passIn.text; - rssModel.tags='my timeline'; - screen.focus = true; - } - text: "Log in" - KeyNavigation.right: guest - KeyNavigation.tab: guest - KeyNavigation.backtab: passIn - Keys.onReturnPressed: login.doLogin(); - Keys.onEnterPressed: login.doLogin(); - Keys.onSelectPressed: login.doLogin(); - Keys.onSpacePressed: login.doLogin(); - onClicked: login.doLogin(); - } - Button { - width: 100 - height: 32 - id: guest - keyUsing: true; - function doGuest() - { - rssModel.authName='-'; - screen.focus = true; - screen.setMode(true); - } - text: "Guest" - KeyNavigation.left: login - KeyNavigation.tab: nameIn - KeyNavigation.backtab: login - Keys.onReturnPressed: guest.doGuest(); - Keys.onEnterPressed: guest.doGuest(); - Keys.onSelectPressed: guest.doGuest(); - Keys.onSpacePressed: guest.doGuest(); - onClicked: guest.doGuest(); - } - } - } -} diff --git a/demos/declarative/twitter/TwitterCore/Button.qml b/demos/declarative/twitter/TwitterCore/Button.qml index d326c64..437b013 100644 --- a/demos/declarative/twitter/TwitterCore/Button.qml +++ b/demos/declarative/twitter/TwitterCore/Button.qml @@ -67,7 +67,7 @@ Item { } Text { id: btnText - color: if(container.keyUsing){"#DDDDDD";} else {"#FFFFFF";} + color: if(container.keyUsing){"#D0D0D0";} else {"#FFFFFF";} anchors.centerIn: buttonImage; font.bold: true text: container.text; style: Text.Raised; styleColor: "black" font.pixelSize: 12 diff --git a/demos/declarative/twitter/TwitterCore/FatDelegate.qml b/demos/declarative/twitter/TwitterCore/FatDelegate.qml index ff03b0b..27dd300 100644 --- a/demos/declarative/twitter/TwitterCore/FatDelegate.qml +++ b/demos/declarative/twitter/TwitterCore/FatDelegate.qml @@ -44,11 +44,10 @@ import Qt 4.7 Component { id: listDelegate Item { - id: wrapper; width: wrapper.ListView.view.width; height: if(txt.height > 58){txt.height+8}else{58}//50+4+4 + id: wrapper; width: wrapper.ListView.view.width; height: if(txt.height > 60){txt.height+10}else{60} //50+5+5 function handleLink(link){ if(link.slice(0,3) == 'app'){ screen.setUser(link.slice(7)); - screen.setMode(true); }else if(link.slice(0,4) == 'http'){ Qt.openUrlExternally(link); } @@ -58,26 +57,47 @@ Component { var ret2 = ret.replace(/http:\/\/[^ \n\t]+/g, '$&');//surrounds http links with html link tags return ret2; } + + // Strip away paranthesis + function userName(str) { + var user = str.replace(/\([\S|\s]*\)/gi, ""); + return user.trim(); + } + Item { id: moveMe; height: parent.height Rectangle { id: blackRect color: "black"; opacity: wrapper.ListView.index % 2 ? 0.2 : 0.3; height: wrapper.height-2; width: wrapper.width; y: 1 } - Rectangle { - id: whiteRect; x: 6; width: 50; height: 50; color: "white"; smooth: true + Item { + id: image; x: 6; width: 48; height: 48; smooth: true anchors.verticalCenter: parent.verticalCenter Loading { x: 1; y: 1; width: 48; height: 48; visible: realImage.status != Image.Ready } - Image { id: realImage; source: userImage; x: 1; y: 1; width:48; height:48 } + Image { + id: realImage; + source: userImage; x: 1; y: 1; + width:48; height:48; opacity:0 ; + onStatusChanged: { + if(status==Image.Ready) + image.state="loaded" + } + } + states: State { + name: "loaded"; + PropertyChanges { target: realImage ; opacity:1 } + } + transitions: Transition { NumberAnimation { target: realImage; property: "opacity"; duration: 200 } } + } Text { id:txt; y:4; x: 56 text: '' - + ''+userScreenName + " from " +source - + "
" + wrapper.addTags(statusText) + ""; + + ''+userName(name) + " from " +source + + "
" + statusText + ""; textFormat: Qt.RichText color: "#cccccc"; style: Text.Raised; styleColor: "black"; wrapMode: Text.WordWrap - anchors.left: whiteRect.right; anchors.right: blackRect.right; anchors.leftMargin: 6; anchors.rightMargin: 6 + anchors.left: image.right; anchors.right: blackRect.right; anchors.leftMargin: 6; anchors.rightMargin: 6 onLinkActivated: wrapper.handleLink(link) } } diff --git a/demos/declarative/twitter/TwitterCore/HomeTitleBar.qml b/demos/declarative/twitter/TwitterCore/HomeTitleBar.qml deleted file mode 100644 index 56f31b1..0000000 --- a/demos/declarative/twitter/TwitterCore/HomeTitleBar.qml +++ /dev/null @@ -1,161 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtDeclarative module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -import Qt 4.7 - -Item { - id: titleBar - - signal update() - onYChanged: state="" //When switching titlebars - - BorderImage { source: "images/titlebar.sci"; width: parent.width; height: parent.height + 14; y: -7 } - Item { - id: container - width: (parent.width * 2) - 55 ; height: parent.height - - function accept() { - if(rssModel.authName == '' || rssModel.authPass == '') - return false;//Can't login like that - - var postData = "status=" + editor.text; - var postman = new XMLHttpRequest(); - postman.open("POST", "http://twitter.com/statuses/update.xml", true, rssModel.authName, rssModel.authPass); - postman.onreadystatechange = function() { - if (postman.readyState == postman.DONE) { - titleBar.update(); - } - } - postman.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); - postman.send(postData); - - editor.text = "" - titleBar.state = "" - } - - Rectangle { - x: 6; width: 50; height: 50; color: "white"; smooth: true - anchors.verticalCenter: parent.verticalCenter - - UserModel { user: rssModel.authName; id: userModel } - Component { id: imgDelegate; - Item { - Loading { width:48; height:48; visible: realImage.status != Image.Ready } - Image { source: image; width:48; height:48; id: realImage } - } - } - ListView { model: userModel.model; x:1; y:1; delegate: imgDelegate } - } - - Text { - id: categoryText - anchors.left: parent.left; anchors.right: tagButton.left - anchors.leftMargin: 58; anchors.rightMargin: 10 - anchors.verticalCenter: parent.verticalCenter - elide: Text.ElideLeft - text: "Timeline for " + rssModel.authName - font.pixelSize: 12; font.bold: true; color: "white"; style: Text.Raised; styleColor: "black" - } - - Button { - id: tagButton; x: titleBar.width - 90; width: 85; height: 32; text: "New Post..." - anchors.verticalCenter: parent.verticalCenter; - onClicked: if (titleBar.state == "Posting") container.accept(); else titleBar.state = "Posting" - } - - Text { - id: charsLeftText; anchors.horizontalCenter: tagButton.horizontalCenter; - anchors.top: tagButton.bottom; anchors.topMargin: 2 - text: {140 - editor.text.length;} visible: titleBar.state == "Posting" - font.pointSize: 10; font.bold: true; color: "white"; style: Text.Raised; styleColor: "black" - } - Item { - id: txtEdit; - anchors.left: tagButton.right; anchors.leftMargin: 5; y: 4 - anchors.right: parent.right; anchors.rightMargin: 40; height: parent.height - 9 - BorderImage { source: "images/lineedit.sci"; anchors.fill: parent } - - Binding {//TODO: Can this be a function, which also resets the cursor? And flashes? - when: editor.text.length > 140 - target: editor - property: "text" - value: editor.text.slice(0,140) - } - TextEdit { - id: editor - anchors.left: parent.left; - anchors.leftMargin: 8; - anchors.bottom: parent.bottom - anchors.bottomMargin: 4; - cursorVisible: true; font.bold: true - width: parent.width - 12 - height: parent.height - 8 - font.pixelSize: 12 - wrapMode: TextEdit.Wrap - color: "#151515"; selectionColor: "green" - } - Keys.forwardTo: [(returnKey), (editor)] - Item { - id: returnKey - Keys.onReturnPressed: container.accept() - Keys.onEnterPressed: container.accept() - Keys.onEscapePressed: titleBar.state = "" - } - } - } - states: [ - State { - name: "Posting" - PropertyChanges { target: container; x: -tagButton.x + 5 } - PropertyChanges { target: titleBar; height: 80 } - PropertyChanges { target: tagButton; text: "OK" } - PropertyChanges { target: tagButton; width: 28 } - PropertyChanges { target: tagButton; height: 24 } - PropertyChanges { target: editor; focus: true } - } - ] - transitions: [ - Transition { - from: "*"; to: "*" - NumberAnimation { properties: "x,y,width,height"; easing.type: Easing.InOutQuad } - } - ] -} diff --git a/demos/declarative/twitter/TwitterCore/Input.qml b/demos/declarative/twitter/TwitterCore/Input.qml new file mode 100644 index 0000000..a33a995 --- /dev/null +++ b/demos/declarative/twitter/TwitterCore/Input.qml @@ -0,0 +1,65 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import Qt 4.7 + +FocusScope { + id:container + width: 220 + height: 28 + BorderImage { source: "images/lineedit.sci"; anchors.fill: parent } + signal accepted + property alias text: input.text + property alias item:input + TextInput{ + id: input + width: parent.width - 12 + anchors.centerIn: parent + maximumLength:21 + font.pixelSize: 16; + font.bold: true + color: "#151515"; selectionColor: "mediumseagreen" + focus: true + onAccepted:{container.accepted()} + text: "" + selectByMouse: true + } +} diff --git a/demos/declarative/twitter/TwitterCore/MultiTitleBar.qml b/demos/declarative/twitter/TwitterCore/MultiTitleBar.qml index 38d6c9c..29b7713 100644 --- a/demos/declarative/twitter/TwitterCore/MultiTitleBar.qml +++ b/demos/declarative/twitter/TwitterCore/MultiTitleBar.qml @@ -42,10 +42,6 @@ import Qt 4.7 Item { - height: homeBar.height - HomeTitleBar { id: homeBar; width: parent.width; height: 60; - onUpdate: rssModel.reload() - } TitleBar { id: titleBar; width: parent.width; height: 60; y: -80 untaggedString: "Latest tweets from everyone" @@ -53,9 +49,8 @@ Item { } states: [ State { - name: "search"; when: screen.userView + name: "search"; when: screen.state!="search" PropertyChanges { target: titleBar; y: 0 } - PropertyChanges { target: homeBar; y: -80 } } ] transitions: [ diff --git a/demos/declarative/twitter/TwitterCore/RssModel.qml b/demos/declarative/twitter/TwitterCore/RssModel.qml index bd73200..d03cdb3 100644 --- a/demos/declarative/twitter/TwitterCore/RssModel.qml +++ b/demos/declarative/twitter/TwitterCore/RssModel.qml @@ -43,43 +43,34 @@ import Qt 4.7 Item { id: wrapper property variant model: xmlModel - property string tags : "" - property string authName : "" - property string authPass : "" + property string from : "" + property string to : "" + property string phrase : "" + property string mode : "everyone" property int status: xmlModel.status function reload() { xmlModel.reload(); } -XmlListModel { - id: xmlModel + XmlListModel { + id: xmlModel - source:{ - if (wrapper.authName == ""){ - ""; //Avoid worthless calls to twitter servers - }else if(wrapper.mode == 'user'){ - "https://"+ ((wrapper.authName!="" && wrapper.authPass!="")? (wrapper.authName+":"+wrapper.authPass+"@") : "" )+"twitter.com/statuses/user_timeline.xml?screen_name="+wrapper.tags; - }else if(wrapper.mode == 'self'){ - "https://"+ ((wrapper.authName!="" && wrapper.authPass!="")? (wrapper.authName+":"+wrapper.authPass+"@") : "" )+"twitter.com/statuses/friends_timeline.xml"; - }else{//everyone/public - "http://twitter.com/statuses/public_timeline.xml"; - } - } - query: "/statuses/status" + source: (from=="" && to=="" && phrase=="") ? "" : + 'http://search.twitter.com/search.atom?from='+from+"&to="+to+"&phrase="+phrase - XmlRole { name: "statusText"; query: "text/string()" } - XmlRole { name: "timestamp"; query: "created_at/string()" } - XmlRole { name: "source"; query: "source/string()" } - XmlRole { name: "userName"; query: "user/name/string()" } - XmlRole { name: "userScreenName"; query: "user/screen_name/string()" } - XmlRole { name: "userImage"; query: "user/profile_image_url/string()" } - XmlRole { name: "userLocation"; query: "user/location/string()" } - XmlRole { name: "userDescription"; query: "user/description/string()" } - XmlRole { name: "userFollowers"; query: "user/followers_count/string()" } - XmlRole { name: "userStatuses"; query: "user/statuses_count/string()" } - //TODO: Could also get the user's color scheme, timezone and a few other things -} -Binding { - property: "mode" - target: wrapper - value: {if(wrapper.tags==''){"everyone";}else if(wrapper.tags=='my timeline'){"self";}else{"user";}} -} + namespaceDeclarations: "declare default element namespace 'http://www.w3.org/2005/Atom'; " + + "declare namespace twitter=\"http://api.twitter.com/\";"; + + query: "/feed/entry" + + XmlRole { name: "statusText"; query: "content/string()" } + XmlRole { name: "timestamp"; query: "published/string()" } + XmlRole { name: "source"; query: "twitter:source/string()" } + XmlRole { name: "name"; query: "author/name/string()" } + XmlRole { name: "userImage"; query: "link[@rel = 'image']/@href/string()" } + + } + Binding { + property: "mode" + target: wrapper + value: {if(wrapper.tags==''){"everyone";}else if(wrapper.tags=='my timeline'){"self";}else{"user";}} + } } diff --git a/demos/declarative/twitter/TwitterCore/SearchView.qml b/demos/declarative/twitter/TwitterCore/SearchView.qml new file mode 100644 index 0000000..22df374 --- /dev/null +++ b/demos/declarative/twitter/TwitterCore/SearchView.qml @@ -0,0 +1,124 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import Qt 4.7 + +FocusScope { + id: wrapper + Column { + anchors.centerIn: parent + spacing: 20 + Column{ + spacing: 4 + Text { + text: "Posted by:" + font.pixelSize: 16; font.bold: true; color: "white"; style: Text.Raised; styleColor: "black" + horizontalAlignment: Qt.AlignRight + } + Input{ + id: fromIn + KeyNavigation.backtab: searchbutton + KeyNavigation.tab:toIn + onAccepted:searchbutton.doSearch(); + focus: true + } + Text { + text: "In reply to:" + font.pixelSize: 16; font.bold: true; color: "white"; style: Text.Raised; styleColor: "black" + horizontalAlignment: Qt.AlignRight + } + Input{ + id: toIn + KeyNavigation.backtab: fromIn + KeyNavigation.tab:phraseIn + onAccepted:searchbutton.doSearch(); + } + Text { + text: "Search phrase:" + font.pixelSize: 16; font.bold: true; color: "white"; style: Text.Raised; styleColor: "black" + horizontalAlignment: Qt.AlignRight + } + Input{ + id: phraseIn + KeyNavigation.backtab: toIn + KeyNavigation.tab:searchbutton + onAccepted:searchbutton.doSearch(); + text: "Qt Quick" + } + } + Button { + width: 100 + height: 32 + id: searchbutton + keyUsing: true; + opacity: 1 + text: "Search" + KeyNavigation.tab: fromIn + Keys.onReturnPressed: searchbutton.doSearch(); + Keys.onEnterPressed: searchbutton.doSearch(); + Keys.onSelectPressed: searchbutton.doSearch(); + Keys.onSpacePressed: searchbutton.doSearch(); + onClicked: searchbutton.doSearch(); + + function doSearch() { + // Search ! allowed + if (wrapper.state=="invalidinput") + return; + + rssModel.from=fromIn.text; + rssModel.to= toIn.text; + rssModel.phrase = phraseIn.text; + screen.focus = true; + screen.state = "" + } + } + } + states: + State { + name: "invalidinput" + when: fromIn.text=="" && toIn.text=="" && phraseIn.text=="" + PropertyChanges { target: searchbutton ; opacity: 0.6 ; } + } + transitions: + Transition { + NumberAnimation { target: searchbutton; property: "opacity"; duration: 200 } + } +} diff --git a/demos/declarative/twitter/TwitterCore/TitleBar.qml b/demos/declarative/twitter/TwitterCore/TitleBar.qml index 479aa20..145c189 100644 --- a/demos/declarative/twitter/TwitterCore/TitleBar.qml +++ b/demos/declarative/twitter/TwitterCore/TitleBar.qml @@ -58,66 +58,58 @@ Item { rssModel.tags = editor.text } - Image { - id: quitButton - x: 5 + Item { + id:imageBox + x: 6; width: 0; height: 50; smooth: true anchors.verticalCenter: parent.verticalCenter - source: "images/quit.png" - MouseArea { - anchors.fill: parent - onClicked: Qt.quit() + + UserModel { user: rssModel.from; id: userModel } + Component { + id: imgDelegate; + Item { + id:imageitem + visible:true + Loading { width:48; height:48; visible: realImage.status != Image.Ready } + Image { id: realImage; source: image; width:48; height:48; opacity:0; } + states: + State { + name: "loaded" + when: (realImage.status == Image.Ready) + PropertyChanges { target: realImage; opacity:1 } + } + transitions: Transition { + NumberAnimation { target: realImage; property: "opacity"; duration: 200 } + } + } + } + ListView { id:view; model: userModel.model; x:1; y:1; delegate: imgDelegate } + states: + State { + when: !userModel.user=="" + PropertyChanges { target: imageBox; width: 50; } + } + transitions: + Transition { + NumberAnimation { target: imageBox; property: "width"; duration: 200 } } - } + } + Text { id: categoryText anchors { - left: quitButton.right; right: tagButton.left; leftMargin: 5; rightMargin: 10 + left: imageBox.right; right: parent.right; leftMargin: 10; rightMargin: 10 verticalCenter: parent.verticalCenter } elide: Text.ElideLeft - text: (rssModel.tags=="" ? untaggedString : taggedString + rssModel.tags) + text: (rssModel.from=="" ? untaggedString : taggedString + rssModel.from) font.bold: true; color: "White"; style: Text.Raised; styleColor: "Black" font.pixelSize: 12 } - - Button { - id: tagButton; x: titleBar.width - 50; width: 45; height: 32; text: "..." - onClicked: if (titleBar.state == "Tags") container.accept(); else titleBar.state = "Tags" - anchors.verticalCenter: parent.verticalCenter - } - - Item { - id: lineEdit - y: 4; height: parent.height - 9 - anchors { left: tagButton.right; leftMargin: 5; right: parent.right; rightMargin: 5 } - - BorderImage { source: "images/lineedit.sci"; anchors.fill: parent } - - TextInput { - id: editor - anchors { - left: parent.left; right: parent.right; leftMargin: 10; rightMargin: 10 - verticalCenter: parent.verticalCenter - } - cursorVisible: true; font.bold: true - color: "#151515"; selectionColor: "Green" - } - - Keys.forwardTo: [ (returnKey), (editor)] - - Item { - id: returnKey - Keys.onReturnPressed: container.accept() - Keys.onEnterPressed: container.accept() - Keys.onEscapePressed: titleBar.state = "" - } - } } states: State { name: "Tags" PropertyChanges { target: container; x: -tagButton.x + 5 } - PropertyChanges { target: tagButton; text: "OK" } PropertyChanges { target: editor; focus: true } } diff --git a/demos/declarative/twitter/TwitterCore/ToolBar.qml b/demos/declarative/twitter/TwitterCore/ToolBar.qml index b9cb915..e18f5c6 100644 --- a/demos/declarative/twitter/TwitterCore/ToolBar.qml +++ b/demos/declarative/twitter/TwitterCore/ToolBar.qml @@ -48,15 +48,14 @@ Item { property alias button2Label: button2.text signal button1Clicked signal button2Clicked - + focus:true BorderImage { source: "images/titlebar.sci"; width: parent.width; height: parent.height + 14; y: -7 } - Button { id: button1 anchors.left: parent.left; anchors.leftMargin: 5; y: 3; width: 140; height: 32 onClicked: toolbar.button1Clicked() + focus:true } - Button { id: button2 anchors.right: parent.right; anchors.rightMargin: 5; y: 3; width: 140; height: 32 diff --git a/demos/declarative/twitter/TwitterCore/UserModel.qml b/demos/declarative/twitter/TwitterCore/UserModel.qml index e653836..d8ca804 100644 --- a/demos/declarative/twitter/TwitterCore/UserModel.qml +++ b/demos/declarative/twitter/TwitterCore/UserModel.qml @@ -42,26 +42,24 @@ import Qt 4.7 //This "model" gets the user information about the searched user. Mainly for the icon. -//Copied from RssModel Item { id: wrapper property variant model: xmlModel property string user : "" property int status: xmlModel.status function reload() { xmlModel.reload(); } -XmlListModel { - id: xmlModel + XmlListModel { + id: xmlModel - source: {if(user!="") {"http://twitter.com/users/show.xml?screen_name="+user;}else{"";}} - query: "/user" + source: user!= "" ? "http://twitter.com/users/show.xml?screen_name="+user : "" + query: "/user" - XmlRole { name: "name"; query: "name/string()" } - XmlRole { name: "screenName"; query: "screen_name/string()" } - XmlRole { name: "image"; query: "profile_image_url/string()" } - XmlRole { name: "location"; query: "location/string()" } - XmlRole { name: "description"; query: "description/string()" } - XmlRole { name: "followers"; query: "followers_count/string()" } - //XmlRole { name: "protected"; query: "protected/bool()" } - //TODO: Could also get the user's color scheme, timezone and a few other things -} + XmlRole { name: "name"; query: "name/string()" } + XmlRole { name: "screenName"; query: "screen_name/string()" } + XmlRole { name: "image"; query: "profile_image_url/string()" } + XmlRole { name: "location"; query: "location/string()" } + XmlRole { name: "description"; query: "description/string()" } + XmlRole { name: "followers"; query: "followers_count/string()" } + //TODO: Could also get the user's color scheme, timezone and a few other things + } } diff --git a/demos/declarative/twitter/TwitterCore/qmldir b/demos/declarative/twitter/TwitterCore/qmldir index 8b56c56..84d85c2 100644 --- a/demos/declarative/twitter/TwitterCore/qmldir +++ b/demos/declarative/twitter/TwitterCore/qmldir @@ -1,7 +1,7 @@ -AuthView 1.0 AuthView.qml +SearchView 1.0 SearchView.qml Button 1.0 Button.qml +Input 1.0 Input.qml FatDelegate 1.0 FatDelegate.qml -HomeTitleBar 1.0 HomeTitleBar.qml Loading 1.0 Loading.qml MultiTitleBar 1.0 MultiTitleBar.qml TitleBar 1.0 TitleBar.qml diff --git a/demos/declarative/twitter/twitter.qml b/demos/declarative/twitter/twitter.qml index 08cecb0..6d224a2 100644 --- a/demos/declarative/twitter/twitter.qml +++ b/demos/declarative/twitter/twitter.qml @@ -46,28 +46,18 @@ Item { id: screen; width: 320; height: 480 property bool userView : false property variant tmpStr - function setMode(m){ - screen.userView = m; - if(m == false){ - rssModel.tags='my timeline'; - rssModel.reload(); - toolBar.button2Label = "View others"; - } else { - toolBar.button2Label = "Return home"; - } - } function setUser(str){hack.running = true; tmpStr = str} - function reallySetUser(){rssModel.tags = tmpStr;} - + function reallySetUser(){rssModel.from = tmpStr;rssModel.to = ""; rssModel.phrase = ""} + state:"searchquery" //Workaround for bug 260266 Timer{ interval: 1; running: false; repeat: false; onTriggered: screen.reallySetUser(); id:hack } - - //TODO: better way to return to the auth screen - Keys.onEscapePressed: rssModel.authName='' + Keys.onEscapePressed: screen.state="searchquery" + Keys.onBacktabPressed: screen.state="searchquery" Rectangle { id: background anchors.fill: parent; color: "#343434"; + state:"searchquery" Image { source: "TwitterCore/images/stripes.png"; fillMode: Image.Tile; anchors.fill: parent; opacity: 0.3 } MouseArea { @@ -90,8 +80,16 @@ Item { y:60 //Below the title bars height: 380 - Twitter.AuthView{ - id: authView + Text { + id:title + text: "Search Twitter" + anchors.horizontalCenter: parent.horizontalCenter + font.pixelSize: 20; font.bold: true; color: "#bbb"; style: Text.Raised; styleColor: "black" + opacity:0 + } + + Twitter.SearchView{ + id: searchView anchors.verticalCenter: parent.verticalCenter width: parent.width; height: parent.height-60; x: -(screen.width * 1.5) @@ -110,31 +108,27 @@ Item { //TODO: Use anchor changes instead of hard coding y: screen.height - 40 width: parent.width; opacity: 0.9 - button1Label: "Update" - button2Label: "View others" - onButton1Clicked: rssModel.reload(); - onButton2Clicked: + button1Label: "New Search" + button2Label: "Update" + onButton1Clicked: { - if(screen.userView == true){ - screen.setMode(false); - }else{ - rssModel.tags=''; - screen.setMode(true); - } + screen.state="searchquery" } + onButton2Clicked: rssModel.reload(); } - - states: [ - State { - name: "unauthed"; when: rssModel.authName=="" - PropertyChanges { target: authView; x: 0 } - PropertyChanges { target: mainView; x: -(parent.width * 1.5) } - PropertyChanges { target: titleBar; y: -80 } - PropertyChanges { target: toolBar; y: screen.height } - } - ] - transitions: [ - Transition { NumberAnimation { properties: "x,y"; duration: 500; easing.type: Easing.InOutQuad } } - ] } + states: [ + State { + name: "searchquery"; + PropertyChanges { target: searchView; x: 0; focus:true} + PropertyChanges { target: mainView; x: -(parent.width * 1.5) } + PropertyChanges { target: titleBar; y: -80 } + PropertyChanges { target: toolBar; y: screen.height } + PropertyChanges { target: toolBar } + PropertyChanges { target: title; opacity:1} + } + ] + transitions: [ + Transition { NumberAnimation { properties: "x,y,opacity"; duration: 500; easing.type: Easing.InOutQuad } } + ] } diff --git a/doc/src/examples/qml-twitter.qdoc b/doc/src/examples/qml-twitter.qdoc index 8a0de00..c3182a0 100644 --- a/doc/src/examples/qml-twitter.qdoc +++ b/doc/src/examples/qml-twitter.qdoc @@ -29,8 +29,8 @@ \title Twitter Mobile \example demos/declarative/twitter - This demo shows how to write a mobile Twitter client in QML. Use it to - tweet us(@qtbynokia) how much you like our demos! + This demo shows how to write a mobile Twitter search client in QML. Use it to + see what people think about Qt Quick! \image qml-twitter-demo.png */ -- cgit v0.12 From b5bfe694814ff4dccc82cc5ae5c5bee0f7254a47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Tue, 31 Aug 2010 16:52:33 +0200 Subject: QTextEngine::LayoutData::reallocate musn't corrupt memory MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ... on re-allocation failure. So, let's actually check the returned pointer and fail, instead of using Q_CHECK_PTR. Task-number: QT-3785 Reviewed-by: Peter Hartmann Reviewed-by: Samuel Rødal --- src/gui/text/qtextengine.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/gui/text/qtextengine.cpp b/src/gui/text/qtextengine.cpp index c30091e..119217a 100644 --- a/src/gui/text/qtextengine.cpp +++ b/src/gui/text/qtextengine.cpp @@ -2139,8 +2139,11 @@ bool QTextEngine::LayoutData::reallocate(int totalGlyphs) void **newMem = memory; newMem = (void **)::realloc(memory_on_stack ? 0 : memory, newAllocated*sizeof(void *)); - Q_CHECK_PTR(newMem); - if (memory_on_stack && newMem) + if (!newMem) { + layoutState = LayoutFailed; + return false; + } + if (memory_on_stack) memcpy(newMem, memory, allocated*sizeof(void *)); memory = newMem; memory_on_stack = false; -- cgit v0.12 From bba97ff5e7faecfaf9b3d0cbb0e2d788bdfd5ab9 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Tue, 31 Aug 2010 16:00:21 +0200 Subject: Update to the NTLM code. Fixes extraction of time from the server, and saves the domain information properly. Patch by subcontractor Reviewed-by: Thiago Macieira --- src/network/kernel/qauthenticator.cpp | 56 +++++++++++++++++++++++------------ 1 file changed, 37 insertions(+), 19 deletions(-) diff --git a/src/network/kernel/qauthenticator.cpp b/src/network/kernel/qauthenticator.cpp index d61c686..18cc14e 100644 --- a/src/network/kernel/qauthenticator.cpp +++ b/src/network/kernel/qauthenticator.cpp @@ -52,10 +52,13 @@ #include #include +//#define NTLMV1_CLIENT QT_BEGIN_NAMESPACE +#ifdef NTLMV1_CLIENT #include "../../3rdparty/des/des.cpp" +#endif static QByteArray qNtlmPhase1(); static QByteArray qNtlmPhase3(QAuthenticatorPrivate *ctx, const QByteArray& phase2data); @@ -203,17 +206,29 @@ QString QAuthenticator::user() const void QAuthenticator::setUser(const QString &user) { detach(); - int separatorPosn = 0; - separatorPosn = user.indexOf(QLatin1String("\\")); - if (separatorPosn == -1) { - //No domain name present + switch(d->method) { + case QAuthenticatorPrivate::DigestMd5: + case QAuthenticatorPrivate::Ntlm: + if((separatorPosn = user.indexOf(QLatin1String("\\"))) != -1) + { + //domain name is present + d->realm = user.left(separatorPosn); + d->user = user.mid(separatorPosn + 1); + } else if((separatorPosn = user.indexOf(QLatin1String("@"))) != -1) { + //domain name is present + d->realm = user.mid(separatorPosn + 1); + d->user = user.left(separatorPosn); + } else { + d->user = user; + d->realm.clear(); + } + break; + // For other auth mechanisms, domain name will be part of username + default: d->user = user; - } else { - //domain name is present - d->realm = user.left(separatorPosn); - d->user = user.mid(separatorPosn+1); + break; } } @@ -1178,11 +1193,9 @@ static QByteArray clientChallenge(const QAuthenticatorPrivate *ctx) } // caller has to ensure a valid targetInfoBuff -static bool qExtractServerTime(const QByteArray& targetInfoBuff, - quint64 *serverTime) +static QByteArray qExtractServerTime(const QByteArray& targetInfoBuff) { - Q_ASSERT(serverTime != 0); - bool retValue = false; + QByteArray timeArray; QDataStream ds(targetInfoBuff); ds.setByteOrder(QDataStream::LittleEndian); @@ -1193,19 +1206,16 @@ static bool qExtractServerTime(const QByteArray& targetInfoBuff, ds >> avLen; while(avId != 0) { if(avId == AVTIMESTAMP) { - QByteArray timeArray(avLen, 0); + timeArray.resize(avLen); //avLen size of QByteArray is allocated ds.readRawData(timeArray.data(), avLen); - bool ok; - *serverTime = timeArray.toHex().toLongLong(&ok, 16); - retValue = true; break; } ds.skipRawData(avLen); ds >> avId; ds >> avLen; } - return retValue; + return timeArray; } static QByteArray qEncodeNtlmv2Response(const QAuthenticatorPrivate *ctx, @@ -1228,9 +1238,17 @@ static QByteArray qEncodeNtlmv2Response(const QAuthenticatorPrivate *ctx, ds.writeRawData(reserved1.constData(), reserved1.size()); quint64 time = 0; + QByteArray timeArray; + + if(ch.targetInfo.len) + { + timeArray = qExtractServerTime(ch.targetInfoBuff); + } //if server sends time, use it instead of current time - if(!(ch.targetInfo.len && qExtractServerTime(ch.targetInfoBuff, &time))) { + if(timeArray.size()) { + ds.writeRawData(timeArray.constData(), timeArray.size()); + } else { QDateTime currentTime(QDate::currentDate(), QTime::currentTime(), Qt::UTC); @@ -1242,8 +1260,8 @@ static QByteArray qEncodeNtlmv2Response(const QAuthenticatorPrivate *ctx, // represented as 100 nano seconds time = Q_UINT64_C(time * 10000000); + ds << time; } - ds << time; //8 byte client challenge QByteArray clientCh = clientChallenge(ctx); -- cgit v0.12 From e3c0b388d92ccb3d06d924b499d90136de25e847 Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Tue, 31 Aug 2010 12:44:44 +0200 Subject: fix windows build with -prefix passing just a spec name to qmake is bogus, as it will try to find it in the install dir, which of course won't work before it is installed. so either pass nothing at all (when preparing the libraries, as .qmake.cache already contains the right path), or explicitly pass a full path (when building the host tools, as we have to override the spec here). Reviewed-by: mariusSO --- tools/configure/configureapp.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tools/configure/configureapp.cpp b/tools/configure/configureapp.cpp index e1d7275..09da581 100644 --- a/tools/configure/configureapp.cpp +++ b/tools/configure/configureapp.cpp @@ -3612,7 +3612,10 @@ void Configure::buildHostTools() // generate Makefile QStringList args; args << QDir::toNativeSeparators(buildPath + "/bin/qmake"); - args << "-spec" << dictionary["QMAKESPEC"] << "-r"; + // override .qmake.cache because we are not cross-building these. + // we need a full path so that a build with -prefix will still find it. + args << "-spec" << QDir::toNativeSeparators(buildPath + "/mkspecs/" + dictionary["QMAKESPEC"]); + args << "-r"; args << "-o" << QDir::toNativeSeparators(toolBuildPath + "/Makefile"); QDir().mkpath(toolBuildPath); @@ -3750,8 +3753,7 @@ void Configure::generateMakefiles() printf("Generating Makefiles...\n"); generate = false; // Now Makefiles will be done } - args << "-spec"; - args << spec; + // don't pass -spec - .qmake.cache has it already args << "-r"; args << (sourcePath + "/projects.pro"); args << "-o"; -- cgit v0.12 From a37dfcfdaa8029f25217fdec6dd6ec1a46929af2 Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Tue, 31 Aug 2010 15:02:16 +0200 Subject: fix qt_webkit_version.pri install for in-Qt builds always add the target, even if building inside Qt - as opposed to the headers and libraries, there are no rules for that coming from qbase.pri. Task-number: QTBUG-13306 --- src/3rdparty/webkit/WebCore/WebCore.pro | 34 ++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/src/3rdparty/webkit/WebCore/WebCore.pro b/src/3rdparty/webkit/WebCore/WebCore.pro index ac0c47c..537cdd3 100644 --- a/src/3rdparty/webkit/WebCore/WebCore.pro +++ b/src/3rdparty/webkit/WebCore/WebCore.pro @@ -2857,6 +2857,25 @@ contains(DEFINES, ENABLE_SYMBIAN_DIALOG_PROVIDERS) { } } +!symbian { + modfile.files = $$moduleFile + modfile.path = $$[QMAKE_MKSPECS]/modules + + INSTALLS += modfile +} else { + # INSTALLS is not implemented in qmake's s60 generators, copy headers manually + + inst_modfile.commands = $$QMAKE_COPY ${QMAKE_FILE_NAME} ${QMAKE_FILE_OUT} + inst_modfile.input = moduleFile + inst_modfile.output = $$[QMAKE_MKSPECS]/modules + inst_modfile.CONFIG = no_clean + + QMAKE_EXTRA_COMPILERS += inst_modfile + + install.depends += compiler_inst_modfile_make_all + QMAKE_EXTRA_TARGETS += install +} + include($$PWD/../WebKit/qt/Api/headers.pri) HEADERS += $$WEBKIT_API_HEADERS @@ -2873,10 +2892,7 @@ HEADERS += $$WEBKIT_API_HEADERS !isEmpty(INSTALL_LIBS): target.path = $$INSTALL_LIBS else: target.path = $$[QT_INSTALL_LIBS] - modfile.files = $$moduleFile - modfile.path = $$[QMAKE_MKSPECS]/modules - - INSTALLS += target headers modfile + INSTALLS += target headers } else { # INSTALLS is not implemented in qmake's s60 generators, copy headers manually inst_headers.commands = $$QMAKE_COPY ${QMAKE_FILE_NAME} ${QMAKE_FILE_OUT} @@ -2888,15 +2904,7 @@ HEADERS += $$WEBKIT_API_HEADERS QMAKE_EXTRA_COMPILERS += inst_headers - inst_modfile.commands = $$inst_headers.commands - inst_modfile.input = moduleFile - inst_modfile.output = $$[QMAKE_MKSPECS]/modules - inst_modfile.CONFIG = no_clean - - QMAKE_EXTRA_COMPILERS += inst_modfile - - install.depends += compiler_inst_headers_make_all compiler_inst_modfile_make_all - QMAKE_EXTRA_TARGETS += install + install.depends += compiler_inst_headers_make_all } win32-*|wince* { -- cgit v0.12 From f9ddd4e138606ed03f4bb585a9e518e39a5fe611 Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Tue, 31 Aug 2010 17:32:02 +0200 Subject: make various POST_LINK steps nicer put each step into a separate make command. that makes for cleaner output and less troubles with command separators. Reviewed-by: mariusSO --- mkspecs/features/symbian/symbian_building.prf | 13 ++----------- mkspecs/features/unix/separate_debug_info.prf | 3 ++- mkspecs/features/vxworks.prf | 11 ++++++----- mkspecs/features/win32/embed_manifest_dll.prf | 5 ++--- mkspecs/features/win32/embed_manifest_exe.prf | 5 ++--- 5 files changed, 14 insertions(+), 23 deletions(-) diff --git a/mkspecs/features/symbian/symbian_building.prf b/mkspecs/features/symbian/symbian_building.prf index 374fe21..414b081 100644 --- a/mkspecs/features/symbian/symbian_building.prf +++ b/mkspecs/features/symbian/symbian_building.prf @@ -114,14 +114,9 @@ isEmpty(capability): capability = "None" capability = "--capability=$$capability" contains(TEMPLATE, lib):!contains(CONFIG, static):!contains(CONFIG, staticlib) { - !isEmpty(QMAKE_POST_LINK) { - # No way to honor the '@' :-( - QMAKE_POST_LINK = $$replace(QMAKE_POST_LINK, "^@", "") - QMAKE_POST_LINK = && $$QMAKE_POST_LINK - } - contains(CONFIG, plugin):QMAKE_ELF2E32_FLAGS += --definput=plugin_commonu.def + !isEmpty(QMAKE_POST_LINK):QMAKE_POST_LINK = $$escape_expand(\\n\\t)$$QMAKE_POST_LINK QMAKE_POST_LINK = $$QMAKE_MOVE $$symbianDestdir/$${baseTarget}.dll $$symbianDestdir/$${baseTarget}.sym \ && $$QMAKE_ELF2E32_WRAPPER --version=$$decVersion \ --sid=$$TARGET.SID \ @@ -166,11 +161,7 @@ contains(TEMPLATE, lib):!contains(CONFIG, static):!contains(CONFIG, staticlib) { } contains(TEMPLATE, app):!contains(QMAKE_LINK, "^@:.*") { - !isEmpty(QMAKE_POST_LINK) { - # No way to honor the '@' :-( - QMAKE_POST_LINK = $$replace(QMAKE_POST_LINK, "^@", "") - QMAKE_POST_LINK = && $$QMAKE_POST_LINK - } + !isEmpty(QMAKE_POST_LINK):QMAKE_POST_LINK = $$escape_expand(\\n\\t)$$QMAKE_POST_LINK QMAKE_POST_LINK = $$QMAKE_MOVE $$symbianDestdir/$${baseTarget} $$symbianDestdir/$${baseTarget}.sym \ && $$QMAKE_ELF2E32_WRAPPER --version $$decVersion \ --sid=$$TARGET.SID \ diff --git a/mkspecs/features/unix/separate_debug_info.prf b/mkspecs/features/unix/separate_debug_info.prf index 40d52cb..8843c6d 100644 --- a/mkspecs/features/unix/separate_debug_info.prf +++ b/mkspecs/features/unix/separate_debug_info.prf @@ -1,8 +1,9 @@ !separate_debug_info_nocopy:!staticlib:!static:!contains(TEMPLATE, subdirs):!isEmpty(QMAKE_OBJCOPY) { - QMAKE_SEPARATE_DEBUG_INFO = (test -z \"$(DESTDIR)\" || cd \"$(DESTDIR)\" ; targ=`basename $(TARGET)`; $$QMAKE_OBJCOPY --only-keep-debug \"\$\$targ\" \"\$\$targ.debug\" && $$QMAKE_OBJCOPY --strip-debug \"\$\$targ\" && $$QMAKE_OBJCOPY --add-gnu-debuglink=\"\$\$targ.debug\" \"\$\$targ\" && chmod -x \"\$\$targ.debug\" ) ; + QMAKE_SEPARATE_DEBUG_INFO = test -z \"$(DESTDIR)\" || cd \"$(DESTDIR)\" ; targ=`basename $(TARGET)`; $$QMAKE_OBJCOPY --only-keep-debug \"\$\$targ\" \"\$\$targ.debug\" && $$QMAKE_OBJCOPY --strip-debug \"\$\$targ\" && $$QMAKE_OBJCOPY --add-gnu-debuglink=\"\$\$targ.debug\" \"\$\$targ\" && chmod -x \"\$\$targ.debug\" QMAKE_INSTALL_SEPARATE_DEBUG_INFO = test -z \"$(DESTDIR)\" || cd \"$(DESTDIR)\" ; $(INSTALL_FILE) `basename $(TARGET)`.debug $(INSTALL_ROOT)/\$\$target_path/ + !isEmpty(QMAKE_POST_LINK):QMAKE_POST_LINK = $$escape_expand(\\n\\t)$$QMAKE_POST_LINK QMAKE_POST_LINK = $$QMAKE_SEPARATE_DEBUG_INFO $$QMAKE_POST_LINK silent:QMAKE_POST_LINK = @echo creating $@.debug && $$QMAKE_POST_LINK diff --git a/mkspecs/features/vxworks.prf b/mkspecs/features/vxworks.prf index a910c69..e257cd7 100644 --- a/mkspecs/features/vxworks.prf +++ b/mkspecs/features/vxworks.prf @@ -22,20 +22,20 @@ isEmpty(VXWORKS_MUNCH_TOOL):VXWORKS_MUNCH_TOOL = $(WIND_BASE)/host/resource/huti shared|!staticlib:!lib { *-dcc { - VXWORKS_MUNCH_CMD = (targ=`basename $(TARGET)`; \ + VXWORKS_MUNCH_CMD = targ=`basename $(TARGET)`; \ ddump -Ng \"$(TARGET)\" | tclsh $$VXWORKS_MUNCH_TOOL -c $$VXWORKS_ARCH_MUNCH >\"$(OBJECTS_DIR)/\$\${targ}_ctdt.c\" && \ $$QMAKE_CC -c $$QMAKE_CFLAGS \"$(OBJECTS_DIR)/\$\${targ}_ctdt.c\" -o \"$(OBJECTS_DIR)/\$\${targ}_ctdt.o\" && \ $$QMAKE_LINK $$QMAKE_LFLAGS -X -r5 -r4 \"$(OBJECTS_DIR)/\$\${targ}_ctdt.o\" \"$(TARGET)\" -o \"$(TARGET).munched\" && \ mv \"$(TARGET).munched\" \"$(TARGET)\" && \ - chmod +x \"$(TARGET)\") + chmod +x \"$(TARGET)\" } *-g++ { - VXWORKS_MUNCH_CMD = (targ=`basename $(TARGET)`; \ + VXWORKS_MUNCH_CMD = targ=`basename $(TARGET)`; \ nm \"$(DESTDIR)$(TARGET)\" | tclsh $$VXWORKS_MUNCH_TOOL -c $$VXWORKS_ARCH_MUNCH >\"$(OBJECTS_DIR)/\$\${targ}_ctdt.c\" && \ $$QMAKE_CC -c $$QMAKE_CFLAGS -fdollars-in-identifiers \"$(OBJECTS_DIR)/\$\${targ}_ctdt.c\" -o \"$(OBJECTS_DIR)/\$\${targ}_ctdt.o\" && \ $$QMAKE_LINK $$QMAKE_LFLAGS -nostdlib -Wl,-X -T $(WIND_BASE)/target/h/tool/gnu/ldscripts/link.OUT \"$(OBJECTS_DIR)/\$\${targ}_ctdt.o\" \"$(DESTDIR)$(TARGET)\" -o \"$(DESTDIR)$(TARGET).munched\" && \ mv \"$(DESTDIR)$(TARGET).munched\" \"$(DESTDIR)$(TARGET)\" && \ - chmod +x \"$(DESTDIR)$(TARGET)\") + chmod +x \"$(DESTDIR)$(TARGET)\" } # We need to create a dummy lib.a in case someone links against this lib. @@ -48,7 +48,8 @@ shared|!staticlib:!lib { VXWORKS_MUNCH_CMD += (atarg=`basename $(TARGET) .so.$${VERSION}`.a ; touch \"$(DESTDIR)\$\${atarg}\") } - QMAKE_POST_LINK = $$VXWORKS_MUNCH_CMD $$QMAKE_POST_LINK + !isEmpty(QMAKE_POST_LINK):QMAKE_POST_LINK = $$escape_expand(\\n\\t)$$QMAKE_POST_LINK + QMAKE_POST_LINK = $$VXWORKS_MUNCH_CMD$$QMAKE_POST_LINK silent:QMAKE_POST_LINK = @echo creating $@.$$VXWORKS_MUNCH_EXT && $$QMAKE_POST_LINK isEmpty(DESTDIR) { diff --git a/mkspecs/features/win32/embed_manifest_dll.prf b/mkspecs/features/win32/embed_manifest_dll.prf index 7305c04..e8711da 100644 --- a/mkspecs/features/win32/embed_manifest_dll.prf +++ b/mkspecs/features/win32/embed_manifest_dll.prf @@ -6,8 +6,7 @@ isEmpty(MANIFEST_DIR):MANIFEST_DIR = . NOPATH_TARGET ~= s,\\\\,/,g # Change to single type separators NOPATH_TARGET ~= s,^(.*/)+,, # Remove all paths QMAKE_LFLAGS += /MANIFEST $$quote(/MANIFESTFILE:\"$${MANIFEST_DIR}\\$${NOPATH_TARGET}.intermediate.manifest\") - QMAKE_PREV_POST_LINK = $$QMAKE_POST_LINK - QMAKE_POST_LINK = $$quote(mt.exe -nologo -manifest \"$$replace(MANIFEST_DIR,/,\\)\\$${NOPATH_TARGET}.intermediate.manifest\" -outputresource:$(DESTDIR_TARGET);2$$escape_expand(\\n\\t)) - QMAKE_POST_LINK += $$QMAKE_PREV_POST_LINK + !isEmpty(QMAKE_POST_LINK):QMAKE_POST_LINK = $$escape_expand(\\n\\t)$$QMAKE_POST_LINK + QMAKE_POST_LINK = $$quote(mt.exe -nologo -manifest \"$$replace(MANIFEST_DIR,/,\\)\\$${NOPATH_TARGET}.intermediate.manifest\" -outputresource:$(DESTDIR_TARGET);2$$escape_expand(\\n\\t))$$QMAKE_POST_LINK QMAKE_CLEAN += \"$$replace(MANIFEST_DIR,/,\\)\\$${NOPATH_TARGET}.intermediate.manifest\" } diff --git a/mkspecs/features/win32/embed_manifest_exe.prf b/mkspecs/features/win32/embed_manifest_exe.prf index 5b37a6d..2d1c09b 100644 --- a/mkspecs/features/win32/embed_manifest_exe.prf +++ b/mkspecs/features/win32/embed_manifest_exe.prf @@ -6,8 +6,7 @@ if(win32-msvc2005*|win32-msvc2008*|win32-msvc2010*):!equals(TEMPLATE_PREFIX, "vc NOPATH_TARGET ~= s,\\\\,/,g # Change to single type separators NOPATH_TARGET ~= s,^(.*/)+,, # Remove all paths QMAKE_LFLAGS += /MANIFEST $$quote(/MANIFESTFILE:\"$${MANIFEST_DIR}\\$${NOPATH_TARGET}.intermediate.manifest\") - QMAKE_PREV_POST_LINK = $$QMAKE_POST_LINK - QMAKE_POST_LINK = $$quote(mt.exe -nologo -manifest \"$$replace(MANIFEST_DIR,/,\\)\\$${NOPATH_TARGET}.intermediate.manifest\" -outputresource:$(DESTDIR_TARGET);1$$escape_expand(\\n\\t)) - QMAKE_POST_LINK += $$QMAKE_PREV_POST_LINK + !isEmpty(QMAKE_POST_LINK):QMAKE_POST_LINK = $$escape_expand(\\n\\t)$$QMAKE_POST_LINK + QMAKE_POST_LINK = $$quote(mt.exe -nologo -manifest \"$$replace(MANIFEST_DIR,/,\\)\\$${NOPATH_TARGET}.intermediate.manifest\" -outputresource:$(DESTDIR_TARGET);1$$escape_expand(\\n\\t))$$QMAKE_POST_LINK QMAKE_CLEAN += \"$$replace(MANIFEST_DIR,/,\\)\\$${NOPATH_TARGET}.intermediate.manifest\" } -- cgit v0.12 From 31e4efaf2178b81552e875eb5a1d5a894310e561 Mon Sep 17 00:00:00 2001 From: Victor Ostashevsky Date: Tue, 31 Aug 2010 19:45:53 +0200 Subject: Remove unused source files in designer Merge-request: 2463 Reviewed-by: Oswald Buddenhagen --- .../src/components/propertyeditor/defs.cpp | 107 --------------------- .../designer/src/components/propertyeditor/defs.h | 60 ------------ .../components/propertyeditor/propertyeditor.pri | 4 +- 3 files changed, 1 insertion(+), 170 deletions(-) delete mode 100644 tools/designer/src/components/propertyeditor/defs.cpp delete mode 100644 tools/designer/src/components/propertyeditor/defs.h diff --git a/tools/designer/src/components/propertyeditor/defs.cpp b/tools/designer/src/components/propertyeditor/defs.cpp deleted file mode 100644 index 54dec74..0000000 --- a/tools/designer/src/components/propertyeditor/defs.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Designer of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "defs.h" - -QT_BEGIN_NAMESPACE - -namespace qdesigner_internal { - -int size_type_to_int( QSizePolicy::Policy t ) -{ - if ( t == QSizePolicy::Fixed ) - return 0; - if ( t == QSizePolicy::Minimum ) - return 1; - if ( t == QSizePolicy::Maximum ) - return 2; - if ( t == QSizePolicy::Preferred ) - return 3; - if ( t == QSizePolicy::MinimumExpanding ) - return 4; - if ( t == QSizePolicy::Expanding ) - return 5; - if ( t == QSizePolicy::Ignored ) - return 6; - return 0; -} - -QString size_type_to_string( QSizePolicy::Policy t ) -{ - if ( t == QSizePolicy::Fixed ) - return QString::fromUtf8("Fixed"); - if ( t == QSizePolicy::Minimum ) - return QString::fromUtf8("Minimum"); - if ( t == QSizePolicy::Maximum ) - return QString::fromUtf8("Maximum"); - if ( t == QSizePolicy::Preferred ) - return QString::fromUtf8("Preferred"); - if ( t == QSizePolicy::MinimumExpanding ) - return QString::fromUtf8("MinimumExpanding"); - if ( t == QSizePolicy::Expanding ) - return QString::fromUtf8("Expanding"); - if ( t == QSizePolicy::Ignored ) - return QString::fromUtf8("Ignored"); - return QString(); -} - -QSizePolicy::Policy int_to_size_type( int i ) -{ - if ( i == 0 ) - return QSizePolicy::Fixed; - if ( i == 1 ) - return QSizePolicy::Minimum; - if ( i == 2 ) - return QSizePolicy::Maximum; - if ( i == 3 ) - return QSizePolicy::Preferred; - if ( i == 4 ) - return QSizePolicy::MinimumExpanding; - if ( i == 5 ) - return QSizePolicy::Expanding; - if ( i == 6 ) - return QSizePolicy::Ignored; - return QSizePolicy::Preferred; -} - -} // namespace qdesigner_internal - -QT_END_NAMESPACE diff --git a/tools/designer/src/components/propertyeditor/defs.h b/tools/designer/src/components/propertyeditor/defs.h deleted file mode 100644 index 28e39fc..0000000 --- a/tools/designer/src/components/propertyeditor/defs.h +++ /dev/null @@ -1,60 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Designer of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef DEFS_H -#define DEFS_H - -#include -#include - -QT_BEGIN_NAMESPACE - -namespace qdesigner_internal { - -int size_type_to_int(QSizePolicy::Policy t); -QString size_type_to_string(QSizePolicy::Policy t); -QSizePolicy::Policy int_to_size_type(int i); - -} // namespace qdesigner_internal - -QT_END_NAMESPACE - -#endif // DEFS_H diff --git a/tools/designer/src/components/propertyeditor/propertyeditor.pri b/tools/designer/src/components/propertyeditor/propertyeditor.pri index 7d2e7cb..bb1afdb 100644 --- a/tools/designer/src/components/propertyeditor/propertyeditor.pri +++ b/tools/designer/src/components/propertyeditor/propertyeditor.pri @@ -45,10 +45,8 @@ SOURCES += $$PWD/propertyeditor.cpp \ HEADERS += \ $$PWD/propertyeditor_global.h \ - $$PWD/defs.h \ $$PWD/qlonglongvalidator.h -SOURCES += $$PWD/defs.cpp \ - $$PWD/qlonglongvalidator.cpp +SOURCES += $$PWD/qlonglongvalidator.cpp RESOURCES += $$PWD/propertyeditor.qrc -- cgit v0.12 From da038b5f74f98d73e25c10e12817cf46ad48f7f9 Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Wed, 1 Sep 2010 07:37:13 +1000 Subject: Use QApplication in QDeclarativeEngine example. Using QCoreApplication causes a crash if you tried to load graphical components. Task-number: QTBUG-13319 --- doc/src/declarative/qmlruntime.qdoc | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/doc/src/declarative/qmlruntime.qdoc b/doc/src/declarative/qmlruntime.qdoc index d44e774..9a84237 100644 --- a/doc/src/declarative/qmlruntime.qdoc +++ b/doc/src/declarative/qmlruntime.qdoc @@ -104,20 +104,22 @@ can be constructed directly instead. In this case, \c application.qml is loaded as a QDeclarativeComponent instance rather than placed into a view: \code - #include + #include #include + #include + #include int main(int argc, char *argv[]) { - QCoreApplication app(argc, argv); + QApplication app(argc, argv); QDeclarativeEngine engine; - QDeclarativeContext *windowContext = new QDeclarativeContext(engine.rootContext()); + QDeclarativeContext *objectContext = new QDeclarativeContext(engine.rootContext()); QDeclarativeComponent component(&engine, "application.qml"); - QObject *window = component.create(windowContext); + QObject *object = component.create(objectContext); - // ... delete window and windowContext when necessary + // ... delete object and objectContext when necessary return app.exec(); } -- cgit v0.12 From b8cca95c0395369cdfb17c198aff085badcddd94 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 1 Sep 2010 11:11:22 +1000 Subject: Only emit change signal when variant properties actually change QTBUG-12601 --- src/declarative/qml/qdeclarativevmemetaobject.cpp | 14 +++++++++++--- .../qdeclarativelanguage/data/variantNotify.qml | 13 +++++++++++++ .../qdeclarativelanguage/tst_qdeclarativelanguage.cpp | 16 +++++++++++++++- 3 files changed, 39 insertions(+), 4 deletions(-) create mode 100644 tests/auto/declarative/qdeclarativelanguage/data/variantNotify.qml diff --git a/src/declarative/qml/qdeclarativevmemetaobject.cpp b/src/declarative/qml/qdeclarativevmemetaobject.cpp index 689ed92..3e32006 100644 --- a/src/declarative/qml/qdeclarativevmemetaobject.cpp +++ b/src/declarative/qml/qdeclarativevmemetaobject.cpp @@ -707,11 +707,19 @@ void QDeclarativeVMEMetaObject::writeVarProperty(int id, const QScriptValue &val void QDeclarativeVMEMetaObject::writeVarProperty(int id, const QVariant &value) { - if (value.userType() == QMetaType::QObjectStar) + bool needActivate = false; + if (value.userType() == QMetaType::QObjectStar) { + QObject *o = qvariant_cast(value); + needActivate = (data[id].dataType() != QMetaType::QObjectStar || data[id].asQObject() != o); data[id].setValue(qvariant_cast(value)); - else + } else { + needActivate = (data[id].dataType() != qMetaTypeId() || + data[id].asQVariant().userType() != value.userType() || + data[id].asQVariant() != value); data[id].setValue(value); - activate(object, methodOffset + id, 0); + } + if (needActivate) + activate(object, methodOffset + id, 0); } void QDeclarativeVMEMetaObject::listChanged(int id) diff --git a/tests/auto/declarative/qdeclarativelanguage/data/variantNotify.qml b/tests/auto/declarative/qdeclarativelanguage/data/variantNotify.qml new file mode 100644 index 0000000..e7aaf16 --- /dev/null +++ b/tests/auto/declarative/qdeclarativelanguage/data/variantNotify.qml @@ -0,0 +1,13 @@ +import Qt 4.7 + +QtObject { + property int notifyCount: 0 + + property variant foo + onFooChanged: notifyCount++ + + Component.onCompleted: { + foo = 1; + foo = 1; + } +} diff --git a/tests/auto/declarative/qdeclarativelanguage/tst_qdeclarativelanguage.cpp b/tests/auto/declarative/qdeclarativelanguage/tst_qdeclarativelanguage.cpp index fc78663..dc00e16 100644 --- a/tests/auto/declarative/qdeclarativelanguage/tst_qdeclarativelanguage.cpp +++ b/tests/auto/declarative/qdeclarativelanguage/tst_qdeclarativelanguage.cpp @@ -142,8 +142,8 @@ private slots: void importsOrder(); void qmlAttachedPropertiesObjectMethod(); - void customOnProperty(); + void variantNotify(); // regression tests for crashes void crash1(); @@ -1685,6 +1685,20 @@ void tst_qdeclarativelanguage::customOnProperty() delete object; } +// QTBUG-12601 +void tst_qdeclarativelanguage::variantNotify() +{ + QDeclarativeComponent component(&engine, TEST_FILE("variantNotify.qml")); + + VERIFY_ERRORS(0); + QObject *object = component.create(); + QVERIFY(object != 0); + + QCOMPARE(object->property("notifyCount").toInt(), 1); + + delete object; +} + void tst_qdeclarativelanguage::initTestCase() { registerTypes(); -- cgit v0.12 From ce698d243f31d2b9adcdf2b6b40f5844c200b159 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 1 Sep 2010 11:54:14 +1000 Subject: Support JS "in" operator on QML objects QTBUG-12837 --- src/declarative/qml/qdeclarativeobjectscriptclass.cpp | 2 +- tests/auto/declarative/qdeclarativeecmascript/data/in.qml | 7 +++++++ .../qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp | 11 +++++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 tests/auto/declarative/qdeclarativeecmascript/data/in.qml diff --git a/src/declarative/qml/qdeclarativeobjectscriptclass.cpp b/src/declarative/qml/qdeclarativeobjectscriptclass.cpp index 3af892d..f439151 100644 --- a/src/declarative/qml/qdeclarativeobjectscriptclass.cpp +++ b/src/declarative/qml/qdeclarativeobjectscriptclass.cpp @@ -192,7 +192,7 @@ QDeclarativeObjectScriptClass::queryProperty(QObject *obj, const Identifier &nam if (!(hints & ImplicitObject)) { local.coreIndex = -1; lastData = &local; - return QScriptClass::HandlesReadAccess | QScriptClass::HandlesWriteAccess; + return QScriptClass::HandlesWriteAccess; } return 0; diff --git a/tests/auto/declarative/qdeclarativeecmascript/data/in.qml b/tests/auto/declarative/qdeclarativeecmascript/data/in.qml new file mode 100644 index 0000000..0b5b0ba --- /dev/null +++ b/tests/auto/declarative/qdeclarativeecmascript/data/in.qml @@ -0,0 +1,7 @@ +import Qt 4.7 + +Item { + id: root + property bool test1: "x" in root + property bool test2: !("foo" in root) +} diff --git a/tests/auto/declarative/qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp b/tests/auto/declarative/qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp index 496cc05..76ca964 100644 --- a/tests/auto/declarative/qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp +++ b/tests/auto/declarative/qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp @@ -159,6 +159,7 @@ private slots: void qtbug_11600(); void nonscriptable(); void deleteLater(); + void in(); void include(); @@ -2553,6 +2554,16 @@ void tst_qdeclarativeecmascript::deleteLater() delete o; } +void tst_qdeclarativeecmascript::in() +{ + QDeclarativeComponent component(&engine, TEST_FILE("in.qml")); + QObject *o = component.create(); + QVERIFY(o != 0); + QCOMPARE(o->property("test1").toBool(), true); + QCOMPARE(o->property("test2").toBool(), true); + delete o; +} + QTEST_MAIN(tst_qdeclarativeecmascript) #include "tst_qdeclarativeecmascript.moc" -- cgit v0.12 From 79000fcf68787c16096ed2231ae849dcd5e83c02 Mon Sep 17 00:00:00 2001 From: Joona Petrell Date: Wed, 1 Sep 2010 11:57:27 +1000 Subject: Fix examples autotest Task-number: Reviewed-by: Bea Lam --- doc/src/declarative/qml-intro.qdoc | 7 +++- .../declarative/qml-intro/basic-syntax.qml | 48 ---------------------- .../qml-intro/sequential-animation3.qml | 2 + 3 files changed, 8 insertions(+), 49 deletions(-) delete mode 100644 doc/src/snippets/declarative/qml-intro/basic-syntax.qml diff --git a/doc/src/declarative/qml-intro.qdoc b/doc/src/declarative/qml-intro.qdoc index 63d6825..9130be0 100644 --- a/doc/src/declarative/qml-intro.qdoc +++ b/doc/src/declarative/qml-intro.qdoc @@ -58,7 +58,12 @@ would be a property. The basic syntax of an \l{QML Elements}{element} is -\snippet doc/src/snippets/declarative/qml-intro/basic-syntax.qml basic syntax +\code +SomeElement { + id: myObject + ... some other things here ... +} +\endcode Here we are defining a new object. We specify its 'type' first as SomeElement. Then within matching braces { ... } we specify the various parts of our diff --git a/doc/src/snippets/declarative/qml-intro/basic-syntax.qml b/doc/src/snippets/declarative/qml-intro/basic-syntax.qml deleted file mode 100644 index 686a927..0000000 --- a/doc/src/snippets/declarative/qml-intro/basic-syntax.qml +++ /dev/null @@ -1,48 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtDeclarative module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** $QT_END_LICENSE$ -** -****************************************************************************/ - -// Note: this file is not intended to be run. - -//! [basic syntax] -SomeElement { - id: myObject - ... some other things here ... -} -//! [basic syntax] diff --git a/doc/src/snippets/declarative/qml-intro/sequential-animation3.qml b/doc/src/snippets/declarative/qml-intro/sequential-animation3.qml index f83a966..6926f8a 100644 --- a/doc/src/snippets/declarative/qml-intro/sequential-animation3.qml +++ b/doc/src/snippets/declarative/qml-intro/sequential-animation3.qml @@ -39,6 +39,8 @@ ****************************************************************************/ //! [document] +import Qt 4.7 + Rectangle { id: mainRec width: 600 -- cgit v0.12 From 9c70c81e6af2435d8d8217b81714b2e087326ecf Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Wed, 1 Sep 2010 12:17:36 +1000 Subject: Flickable ensure internal pressed state is cleared when mouse is released. We did this when handling the mouse events ourselves, but if e.g. a mousearea stole the mouse, we didn't reset the pressed flag. Task-number: QTBUG-12343 --- src/declarative/graphicsitems/qdeclarativeflickable.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/declarative/graphicsitems/qdeclarativeflickable.cpp b/src/declarative/graphicsitems/qdeclarativeflickable.cpp index 63a2a77..b302393 100644 --- a/src/declarative/graphicsitems/qdeclarativeflickable.cpp +++ b/src/declarative/graphicsitems/qdeclarativeflickable.cpp @@ -1258,6 +1258,7 @@ bool QDeclarativeFlickable::sendMouseEvent(QGraphicsSceneMouseEvent *event) if (mouseEvent.type() == QEvent::GraphicsSceneMouseRelease) { d->clearDelayedPress(); d->stealMouse = false; + d->pressed = false; } return false; } -- cgit v0.12 From cddf6992c2a00f894bfa04c68eee8fabbb424b2c Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Fri, 20 Aug 2010 11:29:08 +1000 Subject: Support for qsTrId and meta-data in comments for QML. --- src/declarative/qml/parser/qdeclarativejslexer.cpp | 2 +- .../lupdate/testdata/good/parseqml/main.qml | 97 ++++++++++ .../lupdate/testdata/good/parseqml/project.pro | 3 + .../testdata/good/parseqml/project.ts.result | 195 +++++++++++++++++++++ tools/linguist/lupdate/qdeclarative.cpp | 161 ++++++++++++++++- 5 files changed, 456 insertions(+), 2 deletions(-) create mode 100644 tests/auto/linguist/lupdate/testdata/good/parseqml/main.qml create mode 100644 tests/auto/linguist/lupdate/testdata/good/parseqml/project.pro create mode 100644 tests/auto/linguist/lupdate/testdata/good/parseqml/project.ts.result diff --git a/src/declarative/qml/parser/qdeclarativejslexer.cpp b/src/declarative/qml/parser/qdeclarativejslexer.cpp index cd08658..9024d50 100644 --- a/src/declarative/qml/parser/qdeclarativejslexer.cpp +++ b/src/declarative/qml/parser/qdeclarativejslexer.cpp @@ -696,7 +696,7 @@ int Lexer::lex() } else if (current == '*' && next1 == '/') { state = Start; shift(1); - if (driver) driver->addComment(startpos, tokenLength(), startlineno, startcolumn); + if (driver) driver->addComment(startpos, tokenLength()+1, startlineno, startcolumn); } break; diff --git a/tests/auto/linguist/lupdate/testdata/good/parseqml/main.qml b/tests/auto/linguist/lupdate/testdata/good/parseqml/main.qml new file mode 100644 index 0000000..172bd65 --- /dev/null +++ b/tests/auto/linguist/lupdate/testdata/good/parseqml/main.qml @@ -0,0 +1,97 @@ +import Qt 4.7 + +QtObject { + function translate() { + qsTr("One"); + qsTranslate("FooContext", "Two"); + + var greeting_strings = [ + QT_TR_NOOP("Hello"), + QT_TRANSLATE_NOOP("FooContext", "Goodbye") + ]; + + qsTr("One", "not the same one"); + + //: My first comment. + qsTr("See comment"); + + //: My second comment. + qsTranslate("BarContext", "See other comment"); + + //: My third comment + //: spans two lines. + qsTr("The comment explains it all"); + + //: My fourth comment + //: spans a whopping + //: three lines. + qsTranslate("BazContext", "It should be clear by now"); + + /*: C-style comment. */ + qsTr("I love C++"); + + /*: Another C-style comment. */ + qsTranslate("FooContext", "I really love C++"); + + /*: C-style comment, followed by */ + /*: another one. */ + qsTr("Qt is the best"); + + /*: Another C-style comment, followed by */ + /*: yet another one. */ + qsTranslate("BarContext", "Qt is the very best"); + + // This comment doesn't have any effect. + qsTr("The comment had no effect"); + + // This comment doesn't have any effect either. + qsTranslate("BazContext", "The comment had no effect, really"); + + /* This C-style comment doesn't have any effect. */ + qsTr("No comment to your comment"); + + /* This C-style comment doesn't have any effect either. */ + qsTranslate("FooContext", "I refuse to comment on that"); + + //= id_foo + qsTr("This string has an identifier"); + + //= id_bar + qsTranslate("BarContext", "This string also has an identifier"); + + //~ loc-blank False + qsTr("This string has meta-data"); + + //~ loc-layout_id foo_dialog + qsTranslate("BazContext", "This string also has meta-data"); + + // This comment is to be ignored. + //: This is a comment for the translator. + //= id_baz + //~ foo 123 + //~ magic-stuff This means something special. + qsTr("This string has a lot of information"); + + // This comment is also to be ignored. + //: This is another comment for the translator. + //= id_babar + //~ foo-bar Important stuff + //~ needle-in-haystack Found + //~ overflow True + qsTranslate("FooContext", "This string has even more information"); + + qsTr("This string has disambiguation", "Disambiguation"); + + qsTranslate("BarContext", "This string also has disambiguation", "Another disambiguation"); + + qsTr("This string contains plurals", "", 10); + + qsTrId("qtn_foo_bar"); + + var more_greeting_strings = [ QT_TRID_NOOP("qtn_needle"), QT_TRID_NOOP("qtn_haystack") ]; + + //: qsTrId() with comment, meta-data and plurals. + //~ well-tested True + qsTrId("qtn_bar_baz", 10); + } +} diff --git a/tests/auto/linguist/lupdate/testdata/good/parseqml/project.pro b/tests/auto/linguist/lupdate/testdata/good/parseqml/project.pro new file mode 100644 index 0000000..1040e22 --- /dev/null +++ b/tests/auto/linguist/lupdate/testdata/good/parseqml/project.pro @@ -0,0 +1,3 @@ +SOURCES += main.qml + +TRANSLATIONS = project.ts diff --git a/tests/auto/linguist/lupdate/testdata/good/parseqml/project.ts.result b/tests/auto/linguist/lupdate/testdata/good/parseqml/project.ts.result new file mode 100644 index 0000000..7dac8cb --- /dev/null +++ b/tests/auto/linguist/lupdate/testdata/good/parseqml/project.ts.result @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + qsTrId() with comment, meta-data and plurals. + + + + True + + + + BarContext + + + See other comment + My second comment. + + + + + Qt is the very best + Another C-style comment, followed by yet another one. + + + + + This string also has an identifier + + + + + This string also has disambiguation + Another disambiguation + + + + + BazContext + + + It should be clear by now + My fourth comment spans a whopping three lines. + + + + + The comment had no effect, really + + + + + This string also has meta-data + + foo_dialog + + + + FooContext + + + Two + + + + + Goodbye + + + + + I really love C++ + Another C-style comment. + + + + + I refuse to comment on that + + + + + This string has even more information + This is another comment for the translator. + + Found + True + Important stuff + + + + main + + + One + + + + + Hello + + + + + One + not the same one + + + + + See comment + My first comment. + + + + + The comment explains it all + My third comment spans two lines. + + + + + I love C++ + C-style comment. + + + + + Qt is the best + C-style comment, followed by another one. + + + + + The comment had no effect + + + + + No comment to your comment + + + + + This string has an identifier + + + + + This string has meta-data + + False + + + + This string has a lot of information + This is a comment for the translator. + + 123 + This means something special. + + + + This string has disambiguation + Disambiguation + + + + + This string contains plurals + + + + + + diff --git a/tools/linguist/lupdate/qdeclarative.cpp b/tools/linguist/lupdate/qdeclarative.cpp index 2377416..8b19140 100644 --- a/tools/linguist/lupdate/qdeclarative.cpp +++ b/tools/linguist/lupdate/qdeclarative.cpp @@ -67,6 +67,20 @@ QT_BEGIN_NAMESPACE using namespace QDeclarativeJS; +class Comment +{ +public: + Comment() : lastLine(-1) {} + QString extracomment; + QString msgid; + TranslatorMessage::ExtraData extra; + QString sourcetext; + int lastLine; + + bool isValid() const + { return !extracomment.isEmpty() || !msgid.isEmpty() || !sourcetext.isEmpty() || !extra.isEmpty(); } +}; + class FindTrCalls: protected AST::Visitor { public: @@ -78,6 +92,8 @@ public: accept(node); } + QList comments; + protected: using AST::Visitor::visit; using AST::Visitor::endVisit; @@ -114,10 +130,23 @@ protected: plural = true; } + QString id; + QString extracomment; + TranslatorMessage::ExtraData extra; + Comment scomment = findComment(node->firstSourceLocation().startLine); + if (scomment.isValid()) { + extracomment = scomment.extracomment; + extra = scomment.extra; + id = scomment.msgid; + } + TranslatorMessage msg(m_component, source, comment, QString(), m_fileName, node->firstSourceLocation().startLine, QStringList(), TranslatorMessage::Unfinished, plural); + msg.setExtraComment(extracomment.simplified()); + msg.setId(id); + msg.setExtras(extra); m_translator->extend(msg); } } else if (idExpr->name->asString() == QLatin1String("qsTranslate") || @@ -140,6 +169,17 @@ protected: } if (!literal && m_bSource.isEmpty()) return; + + QString id; + QString extracomment; + TranslatorMessage::ExtraData extra; + Comment scomment = findComment(node->firstSourceLocation().startLine); + if (scomment.isValid()) { + extracomment = scomment.extracomment; + extra = scomment.extra; + id = scomment.msgid; + } + source = literal ? literal->value->asString() : m_bSource; AST::ArgumentList *commentNode = sourceNode->next; if (commentNode && AST::cast(commentNode->expression)) { @@ -155,15 +195,48 @@ protected: comment, QString(), m_fileName, node->firstSourceLocation().startLine, QStringList(), TranslatorMessage::Unfinished, plural); + msg.setExtraComment(extracomment.simplified()); + msg.setId(id); + msg.setExtras(extra); m_translator->extend(msg); } + } else if (idExpr->name->asString() == QLatin1String("qsTrId") || + idExpr->name->asString() == QLatin1String("QT_TRID_NOOP")) { + if (!node->arguments) + return; + AST::StringLiteral *literal = AST::cast(node->arguments->expression); + if (literal) { + + QString extracomment; + QString sourcetext; + TranslatorMessage::ExtraData extra; + Comment comment = findComment(node->firstSourceLocation().startLine); + if (comment.isValid()) { + extracomment = comment.extracomment; + sourcetext = comment.sourcetext; + extra = comment.extra; + } + + const QString id = literal->value->asString(); + bool plural = node->arguments->next; + + TranslatorMessage msg(QString(), QString(), + QString(), QString(), m_fileName, + node->firstSourceLocation().startLine, QStringList(), + TranslatorMessage::Unfinished, plural); + msg.setExtraComment(extracomment.simplified()); + msg.setId(id); + msg.setExtras(extra); + m_translator->extend(msg); + } } } } private: - bool createString(AST::BinaryExpression *b) { + bool createString(AST::BinaryExpression *b) + { if (!b || b->op != 0) return false; AST::BinaryExpression *l = AST::cast(b->left); @@ -187,6 +260,23 @@ private: return true; } + Comment findComment(int loc) + { + if (comments.isEmpty()) + return Comment(); + + int i = 0; + int commentLoc = comments.at(i).lastLine; + while (commentLoc <= loc) { + if (commentLoc == loc) + return comments.at(i); + if (i == comments.count()-1) + break; + commentLoc = comments.at(++i).lastLine; + } + return Comment(); + } + Translator *m_translator; QString m_fileName; QString m_component; @@ -236,6 +326,54 @@ QString createErrorString(const QString &filename, const QString &code, Parser & return errorString; } +bool processComment(const QChar *chars, int length, Comment &comment) +{ + // Try to match the logic of the QtScript parser. + if (!length) + return comment.isValid(); + if (*chars == QLatin1Char(':') && chars[1].isSpace()) { + comment.extracomment += QString(chars+1, length-1); + } else if (*chars == QLatin1Char('=') && chars[1].isSpace()) { + comment.msgid = QString(chars+2, length-2).simplified(); + } else if (*chars == QLatin1Char('~') && chars[1].isSpace()) { + QString text = QString(chars+2, length-2).trimmed(); + int k = text.indexOf(QLatin1Char(' ')); + if (k > -1) + comment.extra.insert(text.left(k), text.mid(k + 1).trimmed()); + } else if (*chars == QLatin1Char('%') && chars[1].isSpace()) { + comment.sourcetext.reserve(comment.sourcetext.length() + length-2); + ushort *ptr = (ushort *)comment.sourcetext.data() + comment.sourcetext.length(); + int p = 2, c; + forever { + if (p >= length) + break; + c = chars[p++].unicode(); + if (isspace(c)) + continue; + if (c != '"') + break; + forever { + if (p >= length) + break; + c = chars[p++].unicode(); + if (c == '"') + break; + if (c == '\\') { + if (p >= length) + break; + c = chars[p++].unicode(); + if (c == '\n') + break; + *ptr++ = '\\'; + } + *ptr++ = c; + } + } + comment.sourcetext.resize(ptr - (ushort *)comment.sourcetext.data()); + } + return comment.isValid(); +} + bool loadQml(Translator &translator, const QString &filename, ConversionData &cd) { cd.m_sourceFileName = filename; @@ -260,6 +398,27 @@ bool loadQml(Translator &translator, const QString &filename, ConversionData &cd if (parser.parse()) { FindTrCalls trCalls; + + // build up a list of comments that contain translation information. + for (int i = 0; i < driver.comments().size(); ++i) { + AST::SourceLocation loc = driver.comments().at(i); + QString commentStr = code.mid(loc.offset+2, loc.length-2); + if (commentStr.endsWith(QLatin1String("*/"))) + commentStr.chop(2); + + if (trCalls.comments.isEmpty() || trCalls.comments.last().lastLine != int(loc.startLine)) { + Comment comment; + comment.lastLine = loc.startLine+1; + if (processComment(commentStr.constData(), commentStr.length(), comment)) + trCalls.comments.append(comment); + } else { + Comment &lastComment = trCalls.comments.last(); + lastComment.lastLine += 1; + processComment(commentStr.constData(), commentStr.length(), lastComment); + } + } + + //find all tr calls in the code trCalls(&translator, filename, parser.ast()); } else { QString error = createErrorString(filename, code, parser); -- cgit v0.12 From b2bae6c955440345ee4fac412b86d154a2ce540a Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Tue, 31 Aug 2010 14:12:27 +1000 Subject: The declarative parser should only save comment text (and not /*,*/,//) Reviewed-by: Roberto Raggi --- src/declarative/qml/parser/qdeclarativejslexer.cpp | 8 ++++---- tools/linguist/lupdate/qdeclarative.cpp | 4 +--- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/declarative/qml/parser/qdeclarativejslexer.cpp b/src/declarative/qml/parser/qdeclarativejslexer.cpp index 9024d50..1eb42e4 100644 --- a/src/declarative/qml/parser/qdeclarativejslexer.cpp +++ b/src/declarative/qml/parser/qdeclarativejslexer.cpp @@ -677,9 +677,9 @@ int Lexer::lex() setDone(Other); } else state = Start; - if (driver) driver->addComment(startpos, tokenLength(), startlineno, startcolumn); + if (driver) driver->addComment(startpos+2, tokenLength()-2, startlineno, startcolumn+2); } else if (current == 0) { - if (driver) driver->addComment(startpos, tokenLength(), startlineno, startcolumn); + if (driver) driver->addComment(startpos+2, tokenLength()-2, startlineno, startcolumn+2); setDone(Eof); } @@ -689,14 +689,14 @@ int Lexer::lex() setDone(Bad); err = UnclosedComment; errmsg = QCoreApplication::translate("QDeclarativeParser", "Unclosed comment at end of file"); - if (driver) driver->addComment(startpos, tokenLength(), startlineno, startcolumn); + if (driver) driver->addComment(startpos+2, tokenLength()-2, startlineno, startcolumn+2); } else if (isLineTerminator()) { shiftWindowsLineBreak(); yylineno++; } else if (current == '*' && next1 == '/') { state = Start; shift(1); - if (driver) driver->addComment(startpos, tokenLength()+1, startlineno, startcolumn); + if (driver) driver->addComment(startpos+2, tokenLength()-3, startlineno, startcolumn+2); } break; diff --git a/tools/linguist/lupdate/qdeclarative.cpp b/tools/linguist/lupdate/qdeclarative.cpp index 8b19140..e6c2b98 100644 --- a/tools/linguist/lupdate/qdeclarative.cpp +++ b/tools/linguist/lupdate/qdeclarative.cpp @@ -402,9 +402,7 @@ bool loadQml(Translator &translator, const QString &filename, ConversionData &cd // build up a list of comments that contain translation information. for (int i = 0; i < driver.comments().size(); ++i) { AST::SourceLocation loc = driver.comments().at(i); - QString commentStr = code.mid(loc.offset+2, loc.length-2); - if (commentStr.endsWith(QLatin1String("*/"))) - commentStr.chop(2); + QString commentStr = code.mid(loc.offset, loc.length); if (trCalls.comments.isEmpty() || trCalls.comments.last().lastLine != int(loc.startLine)) { Comment comment; -- cgit v0.12 From 1d77ce9a00b959befd56428152a52db16743db42 Mon Sep 17 00:00:00 2001 From: Aaron McCarthy Date: Tue, 31 Aug 2010 11:03:28 +1000 Subject: Fix EasyWLAN handling. RCmManager is not sharable between threads, use a function local instance instead. Task-number: QTBUG-13064 --- .../bearer/symbian/qnetworksession_impl.cpp | 82 +++++++++++++++++++-- src/plugins/bearer/symbian/qnetworksession_impl.h | 11 ++- src/plugins/bearer/symbian/symbianengine.cpp | 86 ++++++++++------------ src/plugins/bearer/symbian/symbianengine.h | 17 +++-- 4 files changed, 129 insertions(+), 67 deletions(-) diff --git a/src/plugins/bearer/symbian/qnetworksession_impl.cpp b/src/plugins/bearer/symbian/qnetworksession_impl.cpp index 32eb61a..19f13c2 100644 --- a/src/plugins/bearer/symbian/qnetworksession_impl.cpp +++ b/src/plugins/bearer/symbian/qnetworksession_impl.cpp @@ -48,6 +48,14 @@ #include #include +#ifdef SNAP_FUNCTIONALITY_AVAILABLE +#include +#endif + +#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) +#include +#endif + #ifndef QT_NO_BEARERMANAGEMENT QT_BEGIN_NAMESPACE @@ -113,7 +121,7 @@ QNetworkSessionPrivateImpl::~QNetworkSessionPrivateImpl() #endif } -void QNetworkSessionPrivateImpl::configurationStateChanged(TUint32 accessPointId, TUint32 connMonId, QNetworkSession::State newState) +void QNetworkSessionPrivateImpl::configurationStateChanged(quint32 accessPointId, quint32 connMonId, QNetworkSession::State newState) { if (iHandleStateNotificationsFromManager) { #ifdef QT_BEARERMGMT_SYMBIAN_DEBUG @@ -170,8 +178,10 @@ void QNetworkSessionPrivateImpl::syncStateWithInterface() return; if (iFirstSync) { - QObject::connect(engine, SIGNAL(configurationStateChanged(TUint32, TUint32, QNetworkSession::State)), - this, SLOT(configurationStateChanged(TUint32, TUint32, QNetworkSession::State))); + QObject::connect(engine, + SIGNAL(configurationStateChanged(quint32,quint32,QNetworkSession::State)), + this, + SLOT(configurationStateChanged(quint32,quint32,QNetworkSession::State))); // Listen to configuration removals, so that in case the configuration // this session is based on is removed, session knows to enter Invalid -state. QObject::connect(engine, SIGNAL(configurationRemoved(QNetworkConfigurationPrivatePointer)), @@ -902,13 +912,13 @@ QNetworkConfiguration QNetworkSessionPrivateImpl::activeConfiguration(TUint32 ia if (iapId == 0) { _LIT(KSetting, "IAP\\Id"); iConnection.GetIntSetting(KSetting, iapId); -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) +#ifdef SNAP_FUNCTIONALITY_AVAILABLE // Check if this is an Easy WLAN configuration. On Symbian^3 RConnection may report // the used configuration as 'EasyWLAN' IAP ID if someone has just opened the configuration // from WLAN Scan dialog, _and_ that connection is still up. We need to find the // real matching configuration. Function alters the Easy WLAN ID to real IAP ID (only if // easy WLAN): - engine->easyWlanTrueIapId(iapId); + easyWlanTrueIapId(iapId); #endif } @@ -948,7 +958,7 @@ QNetworkConfiguration QNetworkSessionPrivateImpl::activeConfiguration(TUint32 ia } } } else { -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) +#ifdef SNAP_FUNCTIONALITY_AVAILABLE // On Symbian^3 (only, not earlier or Symbian^4) if the SNAP was not reachable, it triggers // user choice type of activity (EasyWLAN). As a result, a new IAP may be created, and // hence if was not found yet. Therefore update configurations and see if there is something new. @@ -1319,7 +1329,7 @@ bool QNetworkSessionPrivateImpl::newState(QNetworkSession::State newState, TUint } } } -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) +#ifdef SNAP_FUNCTIONALITY_AVAILABLE // If the retVal is not true here, it means that the status update may apply to an IAP outside of // SNAP (session is based on SNAP but follows IAP outside of it), which may occur on Symbian^3 EasyWlan. if (retVal == false && activeConfig.isValid() && @@ -1472,6 +1482,64 @@ void QNetworkSessionPrivateImpl::restoreDefaultIf() setdefaultif(&ifr); } +#if defined(SNAP_FUNCTIONALITY_AVAILABLE) +bool QNetworkSessionPrivateImpl::easyWlanTrueIapId(TUint32 &trueIapId) const +{ + RCmManager iCmManager; + TRAPD(err, iCmManager.OpenL()); + if (err != KErrNone) + return false; + + // Check if this is easy wlan id in the first place + if (trueIapId != iCmManager.EasyWlanIdL()) { + iCmManager.Close(); + return false; + } + + iCmManager.Close(); + + // Loop through all connections that connection monitor is aware + // and check for IAPs based on easy WLAN + TRequestStatus status; + TUint connectionCount; + iConnectionMonitor.GetConnectionCount(connectionCount, status); + User::WaitForRequest(status); + TUint connectionId; + TUint subConnectionCount; + TUint apId; + if (status.Int() == KErrNone) { + for (TUint i = 1; i <= connectionCount; i++) { + iConnectionMonitor.GetConnectionInfo(i, connectionId, subConnectionCount); + iConnectionMonitor.GetUintAttribute(connectionId, subConnectionCount, + KIAPId, apId, status); + User::WaitForRequest(status); + if (apId == trueIapId) { + TBuf<50>easyWlanNetworkName; + iConnectionMonitor.GetStringAttribute(connectionId, 0, KNetworkName, + easyWlanNetworkName, status); + User::WaitForRequest(status); + if (status.Int() != KErrNone) + continue; + + const QString ssid = QString::fromUtf16(easyWlanNetworkName.Ptr(), + easyWlanNetworkName.Length()); + + QNetworkConfigurationPrivatePointer ptr = engine->configurationFromSsid(ssid); + if (ptr) { +#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG + qDebug() << "QNCM easyWlanTrueIapId(), found true IAP ID: " + << toSymbianConfig(ptr)->numericIdentifier(); +#endif + trueIapId = toSymbianConfig(ptr)->numericIdentifier(); + return true; + } + } + } + } + return false; +} +#endif + ConnectionProgressNotifier::ConnectionProgressNotifier(QNetworkSessionPrivateImpl& owner, RConnection& connection) : CActive(CActive::EPriorityUserInput), iOwner(owner), iConnection(connection) { diff --git a/src/plugins/bearer/symbian/qnetworksession_impl.h b/src/plugins/bearer/symbian/qnetworksession_impl.h index 1b0e968..51f2e70 100644 --- a/src/plugins/bearer/symbian/qnetworksession_impl.h +++ b/src/plugins/bearer/symbian/qnetworksession_impl.h @@ -64,9 +64,6 @@ #ifdef SNAP_FUNCTIONALITY_AVAILABLE #include #endif -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) - #include -#endif QT_BEGIN_NAMESPACE @@ -132,7 +129,8 @@ protected: // From CActive void DoCancel(); private Q_SLOTS: - void configurationStateChanged(TUint32 accessPointId, TUint32 connMonId, QNetworkSession::State newState); + void configurationStateChanged(quint32 accessPointId, quint32 connMonId, + QNetworkSession::State newState); void configurationRemoved(QNetworkConfigurationPrivatePointer config); void configurationAdded(QNetworkConfigurationPrivatePointer config); @@ -148,6 +146,11 @@ private: QNetworkInterface interface(TUint iapId) const; #endif +#if defined(SNAP_FUNCTIONALITY_AVAILABLE) + bool easyWlanTrueIapId(TUint32 &trueIapId) const; +#endif + + private: // data SymbianEngine *engine; diff --git a/src/plugins/bearer/symbian/symbianengine.cpp b/src/plugins/bearer/symbian/symbianengine.cpp index 9593461..2e2b671 100644 --- a/src/plugins/bearer/symbian/symbianengine.cpp +++ b/src/plugins/bearer/symbian/symbianengine.cpp @@ -692,7 +692,7 @@ void SymbianEngine::updateActiveAccessPoints() User::WaitForRequest(status); QString ident = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(apId)); QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(ident); -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) +#ifdef SNAP_FUNCTIONALITY_AVAILABLE if (!ptr) { // If IAP was not found, check if the update was about EasyWLAN ptr = configurationFromEasyWlan(apId, connectionId); @@ -1054,7 +1054,7 @@ void SymbianEngine::EventL(const CConnMonEventBase& aEvent) QString ident = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(apId)); QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(ident); -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) +#ifdef SNAP_FUNCTIONALITY_AVAILABLE if (!ptr) { // Check if status was regarding EasyWLAN ptr = configurationFromEasyWlan(apId, connectionId); @@ -1079,7 +1079,7 @@ void SymbianEngine::EventL(const CConnMonEventBase& aEvent) User::WaitForRequest(status); QString ident = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(apId)); QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(ident); -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) +#ifdef SNAP_FUNCTIONALITY_AVAILABLE if (!ptr) { // Check for EasyWLAN ptr = configurationFromEasyWlan(apId, connectionId); @@ -1189,7 +1189,7 @@ void SymbianEngine::EventL(const CConnMonEventBase& aEvent) User::WaitForRequest(status); QString ident = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(apId)); QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(ident); -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) +#ifdef SNAP_FUNCTIONALITY_AVAILABLE if (!ptr) { // If IAP was not found, check if the update was about EasyWLAN ptr = configurationFromEasyWlan(apId, connectionId); @@ -1210,11 +1210,39 @@ void SymbianEngine::EventL(const CConnMonEventBase& aEvent) } } -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) +/* + Returns the network configuration that matches the given SSID. +*/ +QNetworkConfigurationPrivatePointer SymbianEngine::configurationFromSsid(const QString &ssid) +{ + QMutexLocker locker(&mutex); + + // Browser through all items and check their name for match + QHash::ConstIterator i = + accessPointConfigurations.constBegin(); + while (i != accessPointConfigurations.constEnd()) { + QNetworkConfigurationPrivatePointer ptr = i.value(); + + QMutexLocker configLocker(&ptr->mutex); + + if (ptr->name == ssid) { +#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG + qDebug() << "QNCM EasyWlan uses real SSID: " << ssid; +#endif + return ptr; + } + ++i; + } + + return QNetworkConfigurationPrivatePointer(); +} + +#ifdef SNAP_FUNCTIONALITY_AVAILABLE // Tries to derive configuration from EasyWLAN. // First checks if the interface brought up was EasyWLAN, then derives the real SSID, // and looks up configuration based on that one. -QNetworkConfigurationPrivatePointer SymbianEngine::configurationFromEasyWlan(TUint32 apId, TUint connectionId) +QNetworkConfigurationPrivatePointer SymbianEngine::configurationFromEasyWlan(TUint32 apId, + TUint connectionId) { if (apId == iCmManager.EasyWlanIdL()) { TRequestStatus status; @@ -1223,11 +1251,12 @@ QNetworkConfigurationPrivatePointer SymbianEngine::configurationFromEasyWlan(TUi easyWlanNetworkName, status ); User::WaitForRequest(status); if (status.Int() == KErrNone) { - QString realSSID = QString::fromUtf16(easyWlanNetworkName.Ptr(), easyWlanNetworkName.Length()); + const QString realSSID = QString::fromUtf16(easyWlanNetworkName.Ptr(), + easyWlanNetworkName.Length()); // Browser through all items and check their name for match - QHash >::const_iterator i = - accessPointConfigurations.constBegin(); + QHash::ConstIterator i = + accessPointConfigurations.constBegin(); while (i != accessPointConfigurations.constEnd()) { QNetworkConfigurationPrivatePointer ptr = i.value(); @@ -1245,45 +1274,6 @@ QNetworkConfigurationPrivatePointer SymbianEngine::configurationFromEasyWlan(TUi } return QNetworkConfigurationPrivatePointer(); } - -bool SymbianEngine::easyWlanTrueIapId(TUint32& trueIapId) -{ - // Check if this is easy wlan id in the first place - if (trueIapId != iCmManager.EasyWlanIdL()) - return false; - - // Loop through all connections that connection monitor is aware - // and check for IAPs based on easy WLAN - TRequestStatus status; - TUint connectionCount; - iConnectionMonitor.GetConnectionCount(connectionCount, status); - User::WaitForRequest(status); - TUint connectionId; - TUint subConnectionCount; - TUint apId; - if (status.Int() == KErrNone) { - for (TUint i = 1; i <= connectionCount; i++) { - iConnectionMonitor.GetConnectionInfo(i, connectionId, subConnectionCount); - iConnectionMonitor.GetUintAttribute(connectionId, subConnectionCount, - KIAPId, apId, status); - User::WaitForRequest(status); - if (apId == trueIapId) { - QNetworkConfigurationPrivatePointer ptr = - configurationFromEasyWlan(apId, connectionId); - if (ptr) { -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNCM easyWlanTrueIapId(), found true IAP ID: " - << toSymbianConfig(ptr)->numericIdentifier(); -#endif - trueIapId = toSymbianConfig(ptr)->numericIdentifier(); - return true; - } - } - } - } - return false; -} - #endif // Sessions may use this function to report configuration state changes, diff --git a/src/plugins/bearer/symbian/symbianengine.h b/src/plugins/bearer/symbian/symbianengine.h index 1fe6395..7c1076e 100644 --- a/src/plugins/bearer/symbian/symbianengine.h +++ b/src/plugins/bearer/symbian/symbianengine.h @@ -138,10 +138,15 @@ public: QStringList accessPointConfigurationIdentifiers(); + QNetworkConfigurationPrivatePointer configurationFromSsid(const QString &ssid); + + // For QNetworkSessionPrivateImpl to indicate about state changes + void configurationStateChangeReport(TUint32 accessPointId, QNetworkSession::State newState); + Q_SIGNALS: void onlineStateChanged(bool isOnline); - void configurationStateChanged(TUint32 accessPointId, TUint32 connMonId, + void configurationStateChanged(quint32 accessPointId, quint32 connMonId, QNetworkSession::State newState); public Q_SLOTS: @@ -187,12 +192,9 @@ protected: private: // MConnectionMonitorObserver void EventL(const CConnMonEventBase& aEvent); - // For QNetworkSessionPrivate to indicate about state changes - void configurationStateChangeReport(TUint32 accessPointId, - QNetworkSession::State newState); -#ifdef OCC_FUNCTIONALITY_AVAILABLE - QNetworkConfigurationPrivatePointer configurationFromEasyWlan(TUint32 apId, TUint connectionId); - bool easyWlanTrueIapId(TUint32& trueIapId); +#ifdef SNAP_FUNCTIONALITY_AVAILABLE + QNetworkConfigurationPrivatePointer configurationFromEasyWlan(TUint32 apId, + TUint connectionId); #endif private: // Data @@ -212,7 +214,6 @@ private: // Data friend class QNetworkSessionPrivate; friend class AccessPointsAvailabilityScanner; - friend class QNetworkSessionPrivateImpl; #ifdef SNAP_FUNCTIONALITY_AVAILABLE RCmManager iCmManager; -- cgit v0.12 From 744ff7738333c35e7d621c61d72422cf3a8e7fe4 Mon Sep 17 00:00:00 2001 From: Aaron McCarthy Date: Wed, 1 Sep 2010 15:24:25 +1000 Subject: Destroy QNetworkConfigurationManager global static from qApp dtor. The order of global static destruction is not well defined. Ensure that the QNetworkConfigurationManager global static is destroyed from the QCoreApplication destructor before its dependencies are destroyed with the rest of the global statics. Task-number: QTBUG-13304 --- src/network/bearer/qnetworkconfigmanager.cpp | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/network/bearer/qnetworkconfigmanager.cpp b/src/network/bearer/qnetworkconfigmanager.cpp index 65014a6..23d7800 100644 --- a/src/network/bearer/qnetworkconfigmanager.cpp +++ b/src/network/bearer/qnetworkconfigmanager.cpp @@ -45,12 +45,33 @@ #include "qbearerengine_p.h" #include +#include #ifndef QT_NO_BEARERMANAGEMENT QT_BEGIN_NAMESPACE -Q_GLOBAL_STATIC(QNetworkConfigurationManagerPrivate, connManager); +#define Q_GLOBAL_STATIC_QAPP_DESTRUCTION(TYPE, NAME) \ + Q_GLOBAL_STATIC_INIT(TYPE, NAME); \ + static void NAME##_cleanup() \ + { \ + delete this_##NAME.pointer; \ + this_##NAME.pointer = 0; \ + this_##NAME.destroyed = true; \ + } \ + static TYPE *NAME() \ + { \ + if (!this_##NAME.pointer && !this_##NAME.destroyed) { \ + TYPE *x = new TYPE; \ + if (!this_##NAME.pointer.testAndSetOrdered(0, x)) \ + delete x; \ + else \ + qAddPostRoutine(NAME##_cleanup); \ + } \ + return this_##NAME.pointer; \ + } + +Q_GLOBAL_STATIC_QAPP_DESTRUCTION(QNetworkConfigurationManagerPrivate, connManager); QNetworkConfigurationManagerPrivate *qNetworkConfigurationManagerPrivate() { -- cgit v0.12 From 1ec0155c191e2818f56815ee4ddbf5d8982f1267 Mon Sep 17 00:00:00 2001 From: Sami Merila Date: Wed, 1 Sep 2010 11:14:10 +0300 Subject: QS60Style: Itemviews are drawn incorrectly When running QS60Style on hardware, all the itemview items without any special background (i.e. not "pressed", not "highlighted", not "alternate") are drawn with "pressed button" graphics. This is due that the internal drawing function gets called without any enum value set and it seem to pick the second enumeration constant from theme element list. The enumeration constant is not defined to match to any integer value. As a solution, style will not call the drawing function when theme element is not defined. Task-number: QTBUG-11601 Reviewed-by: Liang Qi --- src/gui/styles/qs60style.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/gui/styles/qs60style.cpp b/src/gui/styles/qs60style.cpp index e28403b..0ba1bc6 100644 --- a/src/gui/styles/qs60style.cpp +++ b/src/gui/styles/qs60style.cpp @@ -2340,16 +2340,20 @@ void QS60Style::drawPrimitive(PrimitiveElement element, const QStyleOption *opti tableView = true; QS60StylePrivate::SkinElements element; + bool themeGraphicDefined = false; QRect elementRect = option->rect; //draw item is drawn as pressed, if it already has focus. if (isPressed && (hasFocus || isSelected)) { + themeGraphicDefined = true; element = tableView ? QS60StylePrivate::SE_TableItemPressed : QS60StylePrivate::SE_ListItemPressed; } else if (hasFocus || (isSelected && selectionBehavior != QAbstractItemView::SelectItems)) { element = QS60StylePrivate::SE_ListHighlight; elementRect = highlightRect; + themeGraphicDefined = true; } - QS60StylePrivate::drawSkinElement(element, painter, elementRect, flags); + if (themeGraphicDefined) + QS60StylePrivate::drawSkinElement(element, painter, elementRect, flags); } else { QCommonStyle::drawPrimitive(element, option, painter, widget); } -- cgit v0.12 From 1f5d88dd327be635966ed9e3811c8803a163b2a4 Mon Sep 17 00:00:00 2001 From: Jens Bache-Wiig Date: Wed, 1 Sep 2010 10:39:54 +0200 Subject: Fix some missing proxy calles for CleanLooks These were simply left out as an oversight. Task-number: QTBUG-13318 --- src/gui/styles/qcleanlooksstyle.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/gui/styles/qcleanlooksstyle.cpp b/src/gui/styles/qcleanlooksstyle.cpp index ada5293..306219d 100644 --- a/src/gui/styles/qcleanlooksstyle.cpp +++ b/src/gui/styles/qcleanlooksstyle.cpp @@ -2157,7 +2157,7 @@ void QCleanlooksStyle::drawControl(ControlElement element, const QStyleOption *o } if (button->features & QStyleOptionButton::HasMenu) - ir = ir.adjusted(0, 0, -pixelMetric(PM_MenuButtonIndicator, button, widget), 0); + ir = ir.adjusted(0, 0, -proxy()->pixelMetric(PM_MenuButtonIndicator, button, widget), 0); proxy()->drawItemText(painter, ir, tf, button->palette, (button->state & State_Enabled), button->text, QPalette::ButtonText); } @@ -4014,8 +4014,8 @@ QRect QCleanlooksStyle::subControlRect(ComplexControl control, const QStyleOptio switch (subControl) { case SC_SliderHandle: { if (slider->orientation == Qt::Horizontal) { - rect.setHeight(pixelMetric(PM_SliderThickness)); - rect.setWidth(pixelMetric(PM_SliderLength)); + rect.setHeight(proxy()->pixelMetric(PM_SliderThickness)); + rect.setWidth(proxy()->pixelMetric(PM_SliderLength)); int centerY = slider->rect.center().y() - rect.height() / 2; if (slider->tickPosition & QSlider::TicksAbove) centerY += tickSize; @@ -4023,8 +4023,8 @@ QRect QCleanlooksStyle::subControlRect(ComplexControl control, const QStyleOptio centerY -= tickSize; rect.moveTop(centerY); } else { - rect.setWidth(pixelMetric(PM_SliderThickness)); - rect.setHeight(pixelMetric(PM_SliderLength)); + rect.setWidth(proxy()->pixelMetric(PM_SliderThickness)); + rect.setHeight(proxy()->pixelMetric(PM_SliderLength)); int centerX = slider->rect.center().x() - rect.width() / 2; if (slider->tickPosition & QSlider::TicksAbove) centerX += tickSize; -- cgit v0.12 From 6f143533666ff88c359cb7ad929e35b4decb556f Mon Sep 17 00:00:00 2001 From: Victor Ostashevsky Date: Wed, 1 Sep 2010 10:47:54 +0200 Subject: Enable loading/generating translations by assistant and linguist tools QTranslator is installed in tools (qcollectiongenerator, qhelpconverter, qhelpgenerator, lconvert, lrelease, lupdate). Build targets that updates .ts files are changed to include strings from this tools. Merge-request: 2456 Reviewed-by: Oswald Buddenhagen --- tools/assistant/tools/qcollectiongenerator/main.cpp | 20 +++++++++++++++++--- tools/assistant/tools/qhelpconverter/main.cpp | 15 +++++++++++++++ tools/assistant/tools/qhelpgenerator/main.cpp | 18 +++++++++++++++++- tools/linguist/lconvert/main.cpp | 13 ++++++++++++- tools/linguist/lrelease/main.cpp | 8 +++++++- tools/linguist/lupdate/main.cpp | 12 ++++++++++++ translations/translations.pri | 4 ++-- 7 files changed, 82 insertions(+), 8 deletions(-) diff --git a/tools/assistant/tools/qcollectiongenerator/main.cpp b/tools/assistant/tools/qcollectiongenerator/main.cpp index b3f6bd9..41bf281 100644 --- a/tools/assistant/tools/qcollectiongenerator/main.cpp +++ b/tools/assistant/tools/qcollectiongenerator/main.cpp @@ -49,9 +49,11 @@ #include #include #include -#include #include #include +#include +#include +#include #include #include @@ -350,6 +352,20 @@ int main(int argc, char *argv[]) bool showHelp = false; bool showVersion = false; + QCoreApplication app(argc, argv); + QTranslator translator; + QTranslator qtTranslator; + QTranslator qt_helpTranslator; + QString sysLocale = QLocale::system().name(); + QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath); + if (translator.load(QLatin1String("assistant_") + sysLocale, resourceDir) + && qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir) + && qt_helpTranslator.load(QLatin1String("qt_help_") + sysLocale, resourceDir)) { + app.installTranslator(&translator); + app.installTranslator(&qtTranslator); + app.installTranslator(&qt_helpTranslator); + } + for (int i=1; i +#include +#include +#include #include #include "conversionwizard.h" @@ -49,6 +52,18 @@ QT_USE_NAMESPACE int main(int argc, char *argv[]) { QApplication app(argc, argv); + QTranslator translator; + QTranslator qtTranslator; + QTranslator qt_helpTranslator; + QString sysLocale = QLocale::system().name(); + QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath); + if (translator.load(QLatin1String("assistant_") + sysLocale, resourceDir) + && qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir) + && qt_helpTranslator.load(QLatin1String("qt_help_") + sysLocale, resourceDir)) { + app.installTranslator(&translator); + app.installTranslator(&qtTranslator); + app.installTranslator(&qt_helpTranslator); + } ConversionWizard w; if (argc == 2) { diff --git a/tools/assistant/tools/qhelpgenerator/main.cpp b/tools/assistant/tools/qhelpgenerator/main.cpp index a309f42..7ea7154 100644 --- a/tools/assistant/tools/qhelpgenerator/main.cpp +++ b/tools/assistant/tools/qhelpgenerator/main.cpp @@ -44,6 +44,9 @@ #include #include #include +#include +#include +#include #include @@ -60,6 +63,20 @@ int main(int argc, char *argv[]) bool showVersion = false; bool checkLinks = false; + QCoreApplication app(argc, argv); + QTranslator translator; + QTranslator qtTranslator; + QTranslator qt_helpTranslator; + QString sysLocale = QLocale::system().name(); + QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath); + if (translator.load(QLatin1String("assistant_") + sysLocale, resourceDir) + && qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir) + && qt_helpTranslator.load(QLatin1String("qt_help_") + sysLocale, resourceDir)) { + app.installTranslator(&translator); + app.installTranslator(&qtTranslator); + app.installTranslator(&qt_helpTranslator); + } + for (int i = 1; i < argc; ++i) { arg = QString::fromLocal8Bit(argv[i]); if (arg == QLatin1String("-o")) { @@ -142,7 +159,6 @@ int main(int argc, char *argv[]) return -1; } - QCoreApplication app(argc, argv); HelpGenerator generator; bool success = true; if (checkLinks) diff --git a/tools/linguist/lconvert/main.cpp b/tools/linguist/lconvert/main.cpp index 094406c..e7c1d9a 100644 --- a/tools/linguist/lconvert/main.cpp +++ b/tools/linguist/lconvert/main.cpp @@ -45,6 +45,8 @@ #include #include #include +#include +#include #include @@ -134,8 +136,17 @@ struct File int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); - QStringList args = app.arguments(); + QTranslator translator; + QTranslator qtTranslator; + QString sysLocale = QLocale::system().name(); + QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath); + if (translator.load(QLatin1String("linguist_") + sysLocale, resourceDir) + && qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir)) { + app.installTranslator(&translator); + app.installTranslator(&qtTranslator); + } + QStringList args = app.arguments(); QList inFiles; QString inFormat(QLatin1String("auto")); QString outFileName; diff --git a/tools/linguist/lrelease/main.cpp b/tools/linguist/lrelease/main.cpp index b5cff90..003d379 100644 --- a/tools/linguist/lrelease/main.cpp +++ b/tools/linguist/lrelease/main.cpp @@ -181,8 +181,14 @@ int main(int argc, char **argv) #else QCoreApplication app(argc, argv); QTranslator translator; - if (translator.load(QLatin1String("lrelease_") + QLocale::system().name())) + QTranslator qtTranslator; + QString sysLocale = QLocale::system().name(); + QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath); + if (translator.load(QLatin1String("linguist_") + sysLocale, resourceDir) + && qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir)) { app.installTranslator(&translator); + app.installTranslator(&qtTranslator); + } #endif ConversionData cd; diff --git a/tools/linguist/lupdate/main.cpp b/tools/linguist/lupdate/main.cpp index a575192..0ff5288 100644 --- a/tools/linguist/lupdate/main.cpp +++ b/tools/linguist/lupdate/main.cpp @@ -52,6 +52,8 @@ #include #include #include +#include +#include #include @@ -410,6 +412,16 @@ static void processProjects( int main(int argc, char **argv) { QCoreApplication app(argc, argv); + QTranslator translator; + QTranslator qtTranslator; + QString sysLocale = QLocale::system().name(); + QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath); + if (translator.load(QLatin1String("linguist_") + sysLocale, resourceDir) + && qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir)) { + app.installTranslator(&translator); + app.installTranslator(&qtTranslator); + } + m_defaultExtensions = QLatin1String("java,jui,ui,c,c++,cc,cpp,cxx,ch,h,h++,hh,hpp,hxx,js,qs,qml"); QStringList args = app.arguments(); diff --git a/translations/translations.pri b/translations/translations.pri index fbc1596..1576bd5 100644 --- a/translations/translations.pri +++ b/translations/translations.pri @@ -47,8 +47,8 @@ addTsTargets(qt, -I../include -I../include/Qt \ xmlpatterns \ ) addTsTargets(designer, ../tools/designer/designer.pro) -addTsTargets(linguist, ../tools/linguist/linguist/linguist.pro) -addTsTargets(assistant, ../tools/assistant/tools/assistant/assistant.pro) +addTsTargets(linguist, ../tools/linguist/linguist.pro) +addTsTargets(assistant, ../tools/assistant/tools/tools.pro) addTsTargets(qt_help, ../tools/assistant/lib/lib.pro) addTsTargets(qtconfig, ../tools/qtconfig/qtconfig.pro) addTsTargets(qvfb, ../tools/qvfb/qvfb.pro) -- cgit v0.12 From dea941e773e297cab3a62391d21e4e1acdd93bb3 Mon Sep 17 00:00:00 2001 From: Victor Ostashevsky Date: Wed, 1 Sep 2010 11:47:35 +0200 Subject: Wrap translatable messages with tr() in assistant, designer and linguist Merge-request: 2456 Reviewed-by: Oswald Buddenhagen --- tools/assistant/tools/assistant/bookmarkitem.cpp | 5 +- tools/assistant/tools/assistant/cmdlineparser.cpp | 6 +- tools/assistant/tools/assistant/cmdlineparser.h | 1 - tools/assistant/tools/assistant/mainwindow.cpp | 2 +- .../assistant/tools/qcollectiongenerator/main.cpp | 55 +++++++------- .../assistant/tools/qhelpconverter/filterpage.cpp | 2 +- .../assistant/tools/qhelpconverter/finishpage.cpp | 3 +- .../assistant/tools/qhelpconverter/helpwindow.cpp | 2 +- tools/assistant/tools/qhelpgenerator/main.cpp | 24 ++++--- tools/assistant/tools/shared/helpgenerator.cpp | 4 +- .../src/components/taskmenu/itemlisteditor.cpp | 22 +++--- tools/designer/src/lib/shared/plugindialog.cpp | 4 +- .../src/plugins/phononwidgets/seeksliderplugin.cpp | 4 +- .../plugins/phononwidgets/videoplayerplugin.cpp | 4 +- .../plugins/phononwidgets/volumesliderplugin.cpp | 4 +- .../qdeclarativeview/qdeclarativeview_plugin.cpp | 4 +- .../src/plugins/qwebview/qwebview_plugin.cpp | 4 +- tools/linguist/lconvert/main.cpp | 8 ++- tools/linguist/linguist/phrase.cpp | 7 +- tools/linguist/lrelease/main.cpp | 44 ++++++++---- tools/linguist/lupdate/cpp.cpp | 83 +++++++++++----------- tools/linguist/lupdate/java.cpp | 29 ++++---- tools/linguist/lupdate/main.cpp | 20 +++--- tools/linguist/lupdate/merge.cpp | 18 +++-- tools/linguist/lupdate/qdeclarative.cpp | 7 +- tools/linguist/lupdate/qscript.cpp | 52 ++++++++------ tools/linguist/lupdate/qscript.g | 51 +++++++------ tools/linguist/lupdate/ui.cpp | 19 ++--- 28 files changed, 269 insertions(+), 219 deletions(-) diff --git a/tools/assistant/tools/assistant/bookmarkitem.cpp b/tools/assistant/tools/assistant/bookmarkitem.cpp index 2e81e38..2c92113 100644 --- a/tools/assistant/tools/assistant/bookmarkitem.cpp +++ b/tools/assistant/tools/assistant/bookmarkitem.cpp @@ -41,6 +41,7 @@ #include "bookmarkitem.h" +#include #include QT_BEGIN_NAMESPACE @@ -147,7 +148,9 @@ BookmarkItem::insertChildren(bool isFolder, int position, int count) for (int row = 0; row < count; ++row) { m_children.insert(position, new BookmarkItem(DataVector() - << QObject::tr(isFolder ? "New Folder" : "Untitled") + << (isFolder + ? QCoreApplication::translate("BookmarkItem", "New Folder") + : QCoreApplication::translate("BookmarkItem", "Untitled")) << (isFolder ? "Folder" : "about:blank") << false, this)); } diff --git a/tools/assistant/tools/assistant/cmdlineparser.cpp b/tools/assistant/tools/assistant/cmdlineparser.cpp index b6c0beb..1cf2915 100644 --- a/tools/assistant/tools/assistant/cmdlineparser.cpp +++ b/tools/assistant/tools/assistant/cmdlineparser.cpp @@ -48,7 +48,7 @@ QT_BEGIN_NAMESPACE -const QString CmdLineParser::m_helpMessage = QLatin1String( +static const char helpMessage[] = QT_TRANSLATE_NOOP("CmdLineParser", "Usage: assistant [Options]\n\n" "-collectionFile file Uses the specified collection\n" " file instead of the default one\n" @@ -138,10 +138,10 @@ CmdLineParser::Result CmdLineParser::parse() } if (!m_error.isEmpty()) { - showMessage(m_error + QLatin1String("\n\n\n") + m_helpMessage, true); + showMessage(m_error + QLatin1String("\n\n\n") + tr(helpMessage), true); return Error; } else if (showHelp) { - showMessage(m_helpMessage, false); + showMessage(tr(helpMessage), false); return Help; } return Ok; diff --git a/tools/assistant/tools/assistant/cmdlineparser.h b/tools/assistant/tools/assistant/cmdlineparser.h index 5573081..db66494 100644 --- a/tools/assistant/tools/assistant/cmdlineparser.h +++ b/tools/assistant/tools/assistant/cmdlineparser.h @@ -93,7 +93,6 @@ private: QStringList m_arguments; int m_pos; - static const QString m_helpMessage; QString m_collectionFile; QString m_cloneFile; QString m_helpFile; diff --git a/tools/assistant/tools/assistant/mainwindow.cpp b/tools/assistant/tools/assistant/mainwindow.cpp index 913e342..65a58c0 100644 --- a/tools/assistant/tools/assistant/mainwindow.cpp +++ b/tools/assistant/tools/assistant/mainwindow.cpp @@ -831,7 +831,7 @@ void MainWindow::showAboutDialog() aboutDia.setWindowTitle(aboutDia.documentTitle()); } else { QByteArray resources; - aboutDia.setText(QString::fromLatin1("
" + aboutDia.setText(tr("
" "

%1

" "

Version %2

" "

Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).

") diff --git a/tools/assistant/tools/qcollectiongenerator/main.cpp b/tools/assistant/tools/qcollectiongenerator/main.cpp index 41bf281..46e301c 100644 --- a/tools/assistant/tools/qcollectiongenerator/main.cpp +++ b/tools/assistant/tools/qcollectiongenerator/main.cpp @@ -60,6 +60,10 @@ QT_USE_NAMESPACE +class QCG { + Q_DECLARE_TR_FUNCTIONS(QCollectionGenerator) +}; + class CollectionConfigReader : public QXmlStreamReader { public: @@ -125,9 +129,7 @@ private: void CollectionConfigReader::raiseErrorWithLine() { - raiseError(QCoreApplication::translate("QCollectionGenerator", - "Unknown token at line %1.") - .arg(lineNumber())); + raiseError(QCG::tr("Unknown token at line %1.").arg(lineNumber())); } void CollectionConfigReader::readData(const QByteArray &contents) @@ -146,9 +148,8 @@ void CollectionConfigReader::readData(const QByteArray &contents) && attributes().value(QLatin1String("version")) == QLatin1String("1.0")) readConfig(); else - raiseError(QCoreApplication::translate("QCollectionGenerator", - "Unknown token at line %1. " - "Expected \"QtHelpCollectionProject\"!") + raiseError(QCG::tr("Unknown token at line %1. " + "Expected \"QtHelpCollectionProject\".") .arg(lineNumber())); } } @@ -171,7 +172,7 @@ void CollectionConfigReader::readConfig() } } if (!ok && !hasError()) - raiseError(QLatin1String("Missing end tags.")); + raiseError(QCG::tr("Missing end tags.")); } void CollectionConfigReader::readAssistantSettings() @@ -313,7 +314,7 @@ void CollectionConfigReader::readFiles() } } if (input.isEmpty() || output.isEmpty()) { - raiseError(QLatin1String("Missing input or output file for help file generation!")); + raiseError(QCG::tr("Missing input or output file for help file generation.")); return; } m_filesToGenerate.insert(input, output); @@ -373,8 +374,7 @@ int main(int argc, char *argv[]) QFileInfo fi(QString::fromLocal8Bit(argv[i])); collectionFile = fi.absoluteFilePath(); } else { - error = QCoreApplication::translate("QCollectionGenerator", - "Missing output file name!"); + error = QCG::tr("Missing output file name."); } } else if (arg == QLatin1String("-h")) { showHelp = true; @@ -388,16 +388,15 @@ int main(int argc, char *argv[]) } if (showVersion) { - fprintf(stdout, "Qt Collection Generator version 1.0 (Qt %s)\n", - QT_VERSION_STR); + fputs(qPrintable(QCG::tr("Qt Collection Generator version 1.0 (Qt %1)\n") + .arg(QT_VERSION_STR)), stdout); return 0; } if (configFile.isEmpty() && !showHelp) - error = QCoreApplication::translate("QCollectionGenerator", - "Missing collection config file!"); + error = QCG::tr("Missing collection config file."); - QString help = QCoreApplication::translate("QCollectionGenerator", "\nUsage:\n\n" + QString help = QCG::tr("\nUsage:\n\n" "qcollectiongenerator [options]\n\n" " -o Generates a collection file\n" " called . If\n" @@ -407,7 +406,7 @@ int main(int argc, char *argv[]) " qcollectiongenerator.\n\n"); if (showHelp) { - fprintf(stdout, "%s", qPrintable(help)); + fputs(qPrintable(help), stdout); return 0; }else if (!error.isEmpty()) { fprintf(stderr, "%s\n\n%s", qPrintable(error), qPrintable(help)); @@ -416,7 +415,7 @@ int main(int argc, char *argv[]) QFile file(configFile); if (!file.open(QIODevice::ReadOnly)) { - fprintf(stderr, "Could not open %s!\n", qPrintable(configFile)); + fputs(qPrintable(QCG::tr("Could not open %1.\n").arg(configFile)), stderr); return -1; } @@ -426,17 +425,18 @@ int main(int argc, char *argv[]) + fi.baseName() + QLatin1String(".qhc"); } - fprintf(stdout, "Reading collection config file...\n"); + fputs(qPrintable(QCG::tr("Reading collection config file...\n")), stdout); CollectionConfigReader config; config.readData(file.readAll()); if (config.hasError()) { - fprintf(stderr, "Collection config file error: %s\n", qPrintable(config.errorString())); + fputs(qPrintable(QCG::tr("Collection config file error: %1\n") + .arg(config.errorString())), stderr); return -1; } QMap::const_iterator it = config.filesToGenerate().constBegin(); while (it != config.filesToGenerate().constEnd()) { - fprintf(stdout, "Generating help for %s...\n", qPrintable(it.key())); + fputs(qPrintable(QCG::tr("Generating help for %1...\n").arg(it.key())), stdout); QHelpProjectData helpData; if (!helpData.readData(absoluteFileName(basePath, it.key()))) { fprintf(stderr, "%s\n", qPrintable(helpData.errorMessage())); @@ -451,12 +451,13 @@ int main(int argc, char *argv[]) ++it; } - fprintf(stdout, "Creating collection file...\n"); + fputs(qPrintable(QCG::tr("Creating collection file...\n")), stdout); QFileInfo colFi(collectionFile); if (colFi.exists()) { if (!colFi.dir().remove(colFi.fileName())) { - fprintf(stderr, "The file %s cannot be overwritten!\n", qPrintable(collectionFile)); + fputs(qPrintable(QCG::tr("The file %1 cannot be overwritten.\n") + .arg(collectionFile)), stderr); return -1; } } @@ -514,7 +515,7 @@ int main(int argc, char *argv[]) if (!config.applicationIcon().isEmpty()) { QFile icon(absoluteFileName(basePath, config.applicationIcon())); if (!icon.open(QIODevice::ReadOnly)) { - fprintf(stderr, "Cannot open %s!\n", qPrintable(icon.fileName())); + fputs(qPrintable(QCG::tr("Cannot open %1.\n").arg(icon.fileName())), stderr); return -1; } CollectionConfiguration::setApplicationIcon(helpEngine, icon.readAll()); @@ -535,7 +536,7 @@ int main(int argc, char *argv[]) if (!config.aboutIcon().isEmpty()) { QFile icon(absoluteFileName(basePath, config.aboutIcon())); if (!icon.open(QIODevice::ReadOnly)) { - fprintf(stderr, "Cannot open %s!\n", qPrintable(icon.fileName())); + fputs(qPrintable(QCG::tr("Cannot open %1.\n").arg(icon.fileName())), stderr); return -1; } CollectionConfiguration::setAboutIcon(helpEngine, icon.readAll()); @@ -557,7 +558,7 @@ int main(int argc, char *argv[]) QFileInfo fi(absoluteFileName(basePath, it.value())); QFile f(fi.absoluteFilePath()); if (!f.open(QIODevice::ReadOnly)) { - fprintf(stderr, "Cannot open %s!\n", qPrintable(f.fileName())); + fputs(qPrintable(QCG::tr("Cannot open %1.\n").arg(f.fileName())), stderr); return -1; } QByteArray data = f.readAll(); @@ -579,8 +580,8 @@ int main(int argc, char *argv[]) if (!imgData.contains(src)) imgData.insert(src, img.readAll()); } else { - fprintf(stderr, "Cannot open referenced image file %s!\n", - qPrintable(img.fileName())); + fputs(qPrintable(QCG::tr("Cannot open referenced image file %1.\n") + .arg(img.fileName())), stderr); } } } diff --git a/tools/assistant/tools/qhelpconverter/filterpage.cpp b/tools/assistant/tools/qhelpconverter/filterpage.cpp index 7f86980..c782943 100644 --- a/tools/assistant/tools/qhelpconverter/filterpage.cpp +++ b/tools/assistant/tools/qhelpconverter/filterpage.cpp @@ -127,7 +127,7 @@ void FilterPage::addFilter() { QTreeWidgetItem *item = new QTreeWidgetItem(m_ui.customFilterWidget); item->setFlags(Qt::ItemIsEnabled|Qt::ItemIsEditable|Qt::ItemIsSelectable); - item->setText(0, QLatin1String("unfiltered")); + item->setText(0, tr("unfiltered", "list of available documentation")); item->setText(1, QLatin1String("")); m_ui.customFilterWidget->editItem(item, 0); m_ui.removeButton->setDisabled(false); diff --git a/tools/assistant/tools/qhelpconverter/finishpage.cpp b/tools/assistant/tools/qhelpconverter/finishpage.cpp index 0be3a1b..f0228e3 100644 --- a/tools/assistant/tools/qhelpconverter/finishpage.cpp +++ b/tools/assistant/tools/qhelpconverter/finishpage.cpp @@ -52,8 +52,7 @@ FinishPage::FinishPage(QWidget *parent) : QWizardPage(parent) { setTitle(tr("Converting File")); - setSubTitle(QLatin1String("Creating the new Qt help files from the " - "old .adp file.")); + setSubTitle(tr("Creating the new Qt help files from the old ADP file.")); setFinalPage(true); QVBoxLayout *layout = new QVBoxLayout(this); diff --git a/tools/assistant/tools/qhelpconverter/helpwindow.cpp b/tools/assistant/tools/qhelpconverter/helpwindow.cpp index 9cc1a85..2c7e030 100644 --- a/tools/assistant/tools/qhelpconverter/helpwindow.cpp +++ b/tools/assistant/tools/qhelpconverter/helpwindow.cpp @@ -64,7 +64,7 @@ HelpWindow::HelpWindow(QWidget *parent) layout = new QVBoxLayout(frame); layout->setMargin(2); - QLabel *l = new QLabel(QLatin1String("
Wizard Assistant
")); + QLabel *l = new QLabel(tr("
Wizard Assistant
")); layout->addWidget(l); m_textEdit = new QTextEdit(); m_textEdit->setFrameStyle(QFrame::NoFrame); diff --git a/tools/assistant/tools/qhelpgenerator/main.cpp b/tools/assistant/tools/qhelpgenerator/main.cpp index 7ea7154..637786c 100644 --- a/tools/assistant/tools/qhelpgenerator/main.cpp +++ b/tools/assistant/tools/qhelpgenerator/main.cpp @@ -52,6 +52,10 @@ QT_USE_NAMESPACE +class QHG { + Q_DECLARE_TR_FUNCTIONS(QHelpGenerator) +}; + int main(int argc, char *argv[]) { QString error; @@ -84,8 +88,7 @@ int main(int argc, char *argv[]) QFileInfo fi(QString::fromLocal8Bit(argv[i])); compressedFile = fi.absoluteFilePath(); } else { - error = QCoreApplication::translate("QHelpGenerator", - "Missing output file name!"); + error = QHG::tr("Missing output file name."); } } else if (arg == QLatin1String("-v")) { showVersion = true; @@ -101,16 +104,15 @@ int main(int argc, char *argv[]) } if (showVersion) { - fprintf(stdout, "Qt Help Generator version 1.0 (Qt %s)\n", - QT_VERSION_STR); + fputs(qPrintable(QHG::tr("Qt Help Generator version 1.0 (Qt %1)\n") + .arg(QT_VERSION_STR)), stdout); return 0; } if (projectFile.isEmpty() && !showHelp) - error = QCoreApplication::translate("QHelpGenerator", - "Missing Qt help project file!"); + error = QHG::tr("Missing Qt help project file."); - QString help = QCoreApplication::translate("QHelpGenerator", "\nUsage:\n\n" + QString help = QHG::tr("\nUsage:\n\n" "qhelpgenerator [options]\n\n" " -o Generates a Qt compressed help\n" " file called .\n" @@ -122,7 +124,7 @@ int main(int argc, char *argv[]) " qhelpgenerator.\n\n"); if (showHelp) { - fprintf(stdout, "%s", qPrintable(help)); + fputs(qPrintable(help), stdout); return 0; }else if (!error.isEmpty()) { fprintf(stderr, "%s\n\n%s", qPrintable(error), qPrintable(help)); @@ -131,7 +133,7 @@ int main(int argc, char *argv[]) QFile file(projectFile); if (!file.open(QIODevice::ReadOnly)) { - fprintf(stderr, "Could not open %s!\n", qPrintable(projectFile)); + fputs(qPrintable(QHG::tr("Could not open %1.\n").arg(projectFile)), stderr); return -1; } @@ -147,8 +149,8 @@ int main(int argc, char *argv[]) QDir parentDir = fi.dir(); if (!parentDir.exists()) { if (!parentDir.mkpath(QLatin1String("."))) { - fprintf(stderr, "Could not create output directory: %s\n", - qPrintable(parentDir.path())); + fputs(qPrintable(QHG::tr("Could not create output directory: %1\n") + .arg(parentDir.path())), stderr); } } } diff --git a/tools/assistant/tools/shared/helpgenerator.cpp b/tools/assistant/tools/shared/helpgenerator.cpp index 12008e6..4812bc5 100644 --- a/tools/assistant/tools/shared/helpgenerator.cpp +++ b/tools/assistant/tools/shared/helpgenerator.cpp @@ -73,12 +73,12 @@ QString HelpGenerator::error() const void HelpGenerator::printStatus(const QString &msg) { - fprintf(stdout, "%s\n", qPrintable(msg)); + puts(qPrintable(msg)); } void HelpGenerator::printWarning(const QString &msg) { - fprintf(stdout, "Warning: %s\n", qPrintable(msg)); + puts(qPrintable(tr("Warning: %1").arg(msg))); } QT_END_NAMESPACE diff --git a/tools/designer/src/components/taskmenu/itemlisteditor.cpp b/tools/designer/src/components/taskmenu/itemlisteditor.cpp index 94959fd..9f8e9c8 100644 --- a/tools/designer/src/components/taskmenu/itemlisteditor.cpp +++ b/tools/designer/src/components/taskmenu/itemlisteditor.cpp @@ -114,20 +114,20 @@ void AbstractItemEditor::keyPressEvent(QKeyEvent *e) } static const char * const itemFlagNames[] = { - "Selectable", - "Editable", - "DragEnabled", - "DropEnabled", - "UserCheckable", - "Enabled", - "Tristate", + QT_TRANSLATE_NOOP("AbstractItemEditor", "Selectable"), + QT_TRANSLATE_NOOP("AbstractItemEditor", "Editable"), + QT_TRANSLATE_NOOP("AbstractItemEditor", "DragEnabled"), + QT_TRANSLATE_NOOP("AbstractItemEditor", "DropEnabled"), + QT_TRANSLATE_NOOP("AbstractItemEditor", "UserCheckable"), + QT_TRANSLATE_NOOP("AbstractItemEditor", "Enabled"), + QT_TRANSLATE_NOOP("AbstractItemEditor", "Tristate"), 0 }; static const char * const checkStateNames[] = { - "Unchecked", - "PartiallyChecked", - "Checked", + QT_TRANSLATE_NOOP("AbstractItemEditor", "Unchecked"), + QT_TRANSLATE_NOOP("AbstractItemEditor", "PartiallyChecked"), + QT_TRANSLATE_NOOP("AbstractItemEditor", "Checked"), 0 }; @@ -135,7 +135,7 @@ static QStringList c2qStringList(const char * const in[]) { QStringList out; for (int i = 0; in[i]; i++) - out << QLatin1String(in[i]); + out << AbstractItemEditor::tr(in[i]); return out; } diff --git a/tools/designer/src/lib/shared/plugindialog.cpp b/tools/designer/src/lib/shared/plugindialog.cpp index 3e88043..63ba81c 100644 --- a/tools/designer/src/lib/shared/plugindialog.cpp +++ b/tools/designer/src/lib/shared/plugindialog.cpp @@ -102,7 +102,7 @@ void PluginDialog::populateTreeWidget() const QStringList fileNames = pluginManager->registeredPlugins(); if (!fileNames.isEmpty()) { - QTreeWidgetItem *topLevelItem = setTopLevelItem(QLatin1String("Loaded Plugins")); + QTreeWidgetItem *topLevelItem = setTopLevelItem(tr("Loaded Plugins")); QFont boldFont = topLevelItem->font(0); foreach (const QString &fileName, fileNames) { @@ -125,7 +125,7 @@ void PluginDialog::populateTreeWidget() const QStringList notLoadedPlugins = pluginManager->failedPlugins(); if (!notLoadedPlugins.isEmpty()) { - QTreeWidgetItem *topLevelItem = setTopLevelItem(QLatin1String("Failed Plugins")); + QTreeWidgetItem *topLevelItem = setTopLevelItem(tr("Failed Plugins")); const QFont boldFont = topLevelItem->font(0); foreach (const QString &plugin, notLoadedPlugins) { const QString failureReason = pluginManager->failureReason(plugin); diff --git a/tools/designer/src/plugins/phononwidgets/seeksliderplugin.cpp b/tools/designer/src/plugins/phononwidgets/seeksliderplugin.cpp index c508fa2..7f597ff 100644 --- a/tools/designer/src/plugins/phononwidgets/seeksliderplugin.cpp +++ b/tools/designer/src/plugins/phononwidgets/seeksliderplugin.cpp @@ -66,12 +66,12 @@ QString SeekSliderPlugin::group() const QString SeekSliderPlugin::toolTip() const { - return QString(QLatin1String(toolTipC)); + return tr(toolTipC); } QString SeekSliderPlugin::whatsThis() const { - return QString(QLatin1String(toolTipC)); + return tr(toolTipC); } QString SeekSliderPlugin::includeFile() const diff --git a/tools/designer/src/plugins/phononwidgets/videoplayerplugin.cpp b/tools/designer/src/plugins/phononwidgets/videoplayerplugin.cpp index d4af121..489a08c 100644 --- a/tools/designer/src/plugins/phononwidgets/videoplayerplugin.cpp +++ b/tools/designer/src/plugins/phononwidgets/videoplayerplugin.cpp @@ -72,12 +72,12 @@ QString VideoPlayerPlugin::group() const QString VideoPlayerPlugin::toolTip() const { - return QString(QLatin1String(toolTipC)); + return tr(toolTipC); } QString VideoPlayerPlugin::whatsThis() const { - return QString(QLatin1String(toolTipC)); + return tr(toolTipC); } QString VideoPlayerPlugin::includeFile() const diff --git a/tools/designer/src/plugins/phononwidgets/volumesliderplugin.cpp b/tools/designer/src/plugins/phononwidgets/volumesliderplugin.cpp index becd5d9..24eb829 100644 --- a/tools/designer/src/plugins/phononwidgets/volumesliderplugin.cpp +++ b/tools/designer/src/plugins/phononwidgets/volumesliderplugin.cpp @@ -66,12 +66,12 @@ QString VolumeSliderPlugin::group() const QString VolumeSliderPlugin::toolTip() const { - return QString(QLatin1String(toolTipC)); + return tr(toolTipC); } QString VolumeSliderPlugin::whatsThis() const { - return QString(QLatin1String(toolTipC)); + return tr(toolTipC); } QString VolumeSliderPlugin::includeFile() const diff --git a/tools/designer/src/plugins/qdeclarativeview/qdeclarativeview_plugin.cpp b/tools/designer/src/plugins/qdeclarativeview/qdeclarativeview_plugin.cpp index b352a9b..7148ad0 100644 --- a/tools/designer/src/plugins/qdeclarativeview/qdeclarativeview_plugin.cpp +++ b/tools/designer/src/plugins/qdeclarativeview/qdeclarativeview_plugin.cpp @@ -69,12 +69,12 @@ QString QDeclarativeViewPlugin::group() const QString QDeclarativeViewPlugin::toolTip() const { - return QString(QLatin1String(toolTipC)); + return tr(toolTipC); } QString QDeclarativeViewPlugin::whatsThis() const { - return QString(QLatin1String(toolTipC)); + return tr(toolTipC); } QString QDeclarativeViewPlugin::includeFile() const diff --git a/tools/designer/src/plugins/qwebview/qwebview_plugin.cpp b/tools/designer/src/plugins/qwebview/qwebview_plugin.cpp index 61f7e66..c90e191 100644 --- a/tools/designer/src/plugins/qwebview/qwebview_plugin.cpp +++ b/tools/designer/src/plugins/qwebview/qwebview_plugin.cpp @@ -69,12 +69,12 @@ QString QWebViewPlugin::group() const QString QWebViewPlugin::toolTip() const { - return QString(QLatin1String(toolTipC)); + return tr(toolTipC); } QString QWebViewPlugin::whatsThis() const { - return QString(QLatin1String(toolTipC)); + return tr(toolTipC); } QString QWebViewPlugin::includeFile() const diff --git a/tools/linguist/lconvert/main.cpp b/tools/linguist/lconvert/main.cpp index e7c1d9a..d691548 100644 --- a/tools/linguist/lconvert/main.cpp +++ b/tools/linguist/lconvert/main.cpp @@ -52,6 +52,10 @@ QT_USE_NAMESPACE +class LC { + Q_DECLARE_TR_FUNCTIONS(LConvert) +}; + static int usage(const QStringList &args) { Q_UNUSED(args); @@ -61,7 +65,7 @@ static int usage(const QStringList &args) foreach (Translator::FileFormat format, Translator::registeredFileFormats()) loaders += line.arg(format.extension, -5).arg(format.description); - std::cerr << qPrintable(QString(QLatin1String("\nUsage:\n" + std::cerr << qPrintable(LC::tr("\nUsage:\n" " lconvert [options] [...]\n\n" "lconvert is part of Qt's Linguist tool chain. It can be used as a\n" "stand-alone tool to convert and filter translation data files.\n" @@ -123,7 +127,7 @@ static int usage(const QStringList &args) " 0 on success\n" " 1 on command line parse failures\n" " 2 on read failures\n" - " 3 on write failures\n")).arg(loaders)); + " 3 on write failures\n").arg(loaders)); return 1; } diff --git a/tools/linguist/linguist/phrase.cpp b/tools/linguist/linguist/phrase.cpp index 254daf4..709ec35 100644 --- a/tools/linguist/linguist/phrase.cpp +++ b/tools/linguist/linguist/phrase.cpp @@ -188,10 +188,9 @@ bool QphHandler::characters(const QString &ch) bool QphHandler::fatalError(const QXmlParseException &exception) { if (ferrorCount++ == 0) { - QString msg; - msg.sprintf("Parse error at line %d, column %d (%s).", - exception.lineNumber(), exception.columnNumber(), - exception.message().toLatin1().constData()); + QString msg = PhraseBook::tr("Parse error at line %1, column %2 (%3).") + .arg(exception.lineNumber()).arg(exception.columnNumber()) + .arg(exception.message()); QMessageBox::information(0, QObject::tr("Qt Linguist"), msg); } diff --git a/tools/linguist/lrelease/main.cpp b/tools/linguist/lrelease/main.cpp index 003d379..19377ef 100644 --- a/tools/linguist/lrelease/main.cpp +++ b/tools/linguist/lrelease/main.cpp @@ -65,6 +65,17 @@ static void initBinaryDir( const char *argv0 #endif ); + +struct LR { + static inline QString tr(const char *sourceText, const char *comment = 0) + { + return QCoreApplication::translate("LRelease", sourceText, comment); + } +}; +#else +class LR { + Q_DECLARE_TR_FUNCTIONS(LRelease) +}; #endif static void printOut(const QString & out) @@ -75,7 +86,7 @@ static void printOut(const QString & out) static void printUsage() { - printOut(QCoreApplication::tr( + printOut(LR::tr( "Usage:\n" " lrelease [options] project-file\n" " lrelease [options] ts-files [-qm qm-file]\n\n" @@ -108,7 +119,7 @@ static bool loadTsFile(Translator &tor, const QString &tsFileName, bool /* verbo ConversionData cd; bool ok = tor.load(tsFileName, cd, QLatin1String("auto")); if (!ok) { - std::cerr << "lrelease error: " << qPrintable(cd.error()); + std::cerr << qPrintable(LR::tr("lrelease error: %1").arg(cd.error())); } else { if (!cd.errors().isEmpty()) printOut(cd.error()); @@ -123,17 +134,17 @@ static bool releaseTranslator(Translator &tor, const QString &qmFileName, tor.reportDuplicates(tor.resolveDuplicates(), qmFileName, cd.isVerbose()); if (cd.isVerbose()) - printOut(QCoreApplication::tr( "Updating '%1'...\n").arg(qmFileName)); + printOut(LR::tr("Updating '%1'...\n").arg(qmFileName)); if (removeIdentical) { if (cd.isVerbose()) - printOut(QCoreApplication::tr( "Removing translations equal to source text in '%1'...\n").arg(qmFileName)); + printOut(LR::tr("Removing translations equal to source text in '%1'...\n").arg(qmFileName)); tor.stripIdenticalSourceTranslations(); } QFile file(qmFileName); if (!file.open(QIODevice::WriteOnly)) { - std::cerr << "lrelease error: cannot create '" << qPrintable(qmFileName) - << "': " << qPrintable(file.errorString()) << std::endl; + std::cerr << qPrintable(LR::tr("lrelease error: cannot create '%1': %2\n") + .arg(qmFileName, file.errorString())); return false; } @@ -142,8 +153,8 @@ static bool releaseTranslator(Translator &tor, const QString &qmFileName, file.close(); if (!ok) { - std::cerr << "lrelease error: cannot save '" << qPrintable(qmFileName) - << "': " << qPrintable(cd.error()); + std::cerr << qPrintable(LR::tr("lrelease error: cannot save '%1': %2") + .arg(qmFileName, cd.error())); } else if (!cd.errors().isEmpty()) { printOut(cd.error()); } @@ -227,7 +238,7 @@ int main(int argc, char **argv) cd.m_verbose = true; continue; } else if (!strcmp(argv[i], "-version")) { - printOut(QCoreApplication::tr( "lrelease version %1\n").arg(QLatin1String(QT_VERSION_STR)) ); + printOut(LR::tr("lrelease version %1\n").arg(QLatin1String(QT_VERSION_STR))); return 0; } else if (!strcmp(argv[i], "-qm")) { if (i == argc - 1) { @@ -261,20 +272,23 @@ int main(int argc, char **argv) visitor.setVerbose(cd.isVerbose()); if (!visitor.queryProFile(&pro)) { - std::cerr << "lrelease error: cannot read project file '" - << qPrintable(inputFile) << "'.\n"; + std::cerr << qPrintable(LR::tr( + "lrelease error: cannot read project file '%1'.\n") + .arg(inputFile)); continue; } if (!visitor.accept(&pro)) { - std::cerr << "lrelease error: cannot process project file '" - << qPrintable(inputFile) << "'.\n"; + std::cerr << qPrintable(LR::tr( + "lrelease error: cannot process project file '%1'.\n") + .arg(inputFile)); continue; } QStringList translations = visitor.values(QLatin1String("TRANSLATIONS")); if (translations.isEmpty()) { - std::cerr << "lrelease warning: Met no 'TRANSLATIONS' entry in project file '" - << qPrintable(inputFile) << "'\n"; + std::cerr << qPrintable(LR::tr( + "lrelease warning: Met no 'TRANSLATIONS' entry in project file '%1'\n") + .arg(inputFile)); } else { QDir proDir(fi.absolutePath()); foreach (const QString &trans, translations) diff --git a/tools/linguist/lupdate/cpp.cpp b/tools/linguist/lupdate/cpp.cpp index bc9bb26..970d44b 100644 --- a/tools/linguist/lupdate/cpp.cpp +++ b/tools/linguist/lupdate/cpp.cpp @@ -50,6 +50,7 @@ #include #include #include +#include #include @@ -57,6 +58,10 @@ QT_BEGIN_NAMESPACE +class LU { + Q_DECLARE_TR_FUNCTIONS(LUpdate) +}; + /* qmake ignore Q_OBJECT */ static QString MagicComment(QLatin1String("TRANSLATOR")); @@ -624,8 +629,8 @@ uint CppParser::getToken() || yyBraceDepth != is.braceDepth1st || yyParenDepth != is.parenDepth1st) yyMsg(is.elseLine) - << "Parenthesis/bracket/brace mismatch between " - "#if and #else branches; using #if branch\n"; + << qPrintable(LU::tr("Parenthesis/bracket/brace mismatch between " + "#if and #else branches; using #if branch\n")); } else { is.bracketDepth1st = yyBracketDepth; is.braceDepth1st = yyBraceDepth; @@ -647,8 +652,8 @@ uint CppParser::getToken() || yyBraceDepth != is.braceDepth1st || yyParenDepth != is.parenDepth1st) yyMsg(is.elseLine) - << "Parenthesis/brace mismatch between " - "#if and #else branches; using #if branch\n"; + << qPrintable(LU::tr("Parenthesis/brace mismatch between " + "#if and #else branches; using #if branch\n")); yyBracketDepth = is.bracketDepth1st; yyBraceDepth = is.braceDepth1st; yyParenDepth = is.parenDepth1st; @@ -674,7 +679,7 @@ uint CppParser::getToken() forever { yyCh = getChar(); if (yyCh == EOF) { - yyMsg() << "Unterminated C++ comment\n"; + yyMsg() << qPrintable(LU::tr("Unterminated C++ comment\n")); break; } @@ -804,7 +809,7 @@ uint CppParser::getToken() forever { yyCh = getChar(); if (yyCh == EOF) { - yyMsg() << "Unterminated C++ comment\n"; + yyMsg() << qPrintable(LU::tr("Unterminated C++ comment\n")); break; } *ptr++ = yyCh; @@ -837,7 +842,7 @@ uint CppParser::getToken() yyWord.resize(ptr - (ushort *)yyWord.unicode()); if (yyCh != '"') - yyMsg() << "Unterminated C++ string\n"; + yyMsg() << qPrintable(LU::tr("Unterminated C++ string\n")); else yyCh = getChar(); return Tok_String; @@ -894,8 +899,8 @@ uint CppParser::getToken() if (yyBraceDepth == yyMinBraceDepth) { if (!inDefine) yyMsg(yyCurLineNo) - << "Excess closing brace in C++ code" - " (or abuse of the C++ preprocessor)\n"; + << qPrintable(LU::tr("Excess closing brace in C++ code" + " (or abuse of the C++ preprocessor)\n")); // Avoid things getting messed up even more yyCh = getChar(); return Tok_Semicolon; @@ -912,8 +917,8 @@ uint CppParser::getToken() case ')': if (yyParenDepth == 0) yyMsg(yyCurLineNo) - << "Excess closing parenthesis in C++ code" - " (or abuse of the C++ preprocessor)\n"; + << qPrintable(LU::tr("Excess closing parenthesis in C++ code" + " (or abuse of the C++ preprocessor)\n")); else yyParenDepth--; yyCh = getChar(); @@ -927,8 +932,8 @@ uint CppParser::getToken() case ']': if (yyBracketDepth == 0) yyMsg(yyCurLineNo) - << "Excess closing bracket in C++ code" - " (or abuse of the C++ preprocessor)\n"; + << qPrintable(LU::tr("Excess closing bracket in C++ code" + " (or abuse of the C++ preprocessor)\n")); else yyBracketDepth--; yyCh = getChar(); @@ -1296,7 +1301,7 @@ void CppParser::processInclude(const QString &file, ConversionData &cd, QString cleanFile = QDir::cleanPath(file); if (inclusions.contains(cleanFile)) { - yyMsg() << "circular inclusion of " << qPrintable(cleanFile) << std::endl; + yyMsg() << qPrintable(LU::tr("circular inclusion of %1\n").arg(cleanFile)); return; } @@ -1320,9 +1325,7 @@ void CppParser::processInclude(const QString &file, ConversionData &cd, QFile f(cleanFile); if (!f.open(QIODevice::ReadOnly)) { - yyMsg() - << "Cannot open " << qPrintable(cleanFile) << ": " - << qPrintable(f.errorString()) << std::endl; + yyMsg() << qPrintable(LU::tr("Cannot open %1: %2\n").arg(cleanFile, f.errorString())); return; } @@ -1766,7 +1769,7 @@ void CppParser::parseInternal(ConversionData &cd, QSet &inclusions) if (!tor) goto case_default; if (!sourcetext.isEmpty()) - yyMsg() << "//% cannot be used with tr() / QT_TR_NOOP(). Ignoring\n"; + yyMsg() << qPrintable(LU::tr("//% cannot be used with tr() / QT_TR_NOOP(). Ignoring\n")); utf8 = (yyTok == Tok_trUtf8); line = yyLineNo; yyTok = getToken(); @@ -1787,9 +1790,8 @@ void CppParser::parseInternal(ConversionData &cd, QSet &inclusions) QStringList unresolved; if (!fullyQualify(namespaces, pendingContext, true, &functionContext, &unresolved)) { functionContextUnresolved = unresolved.join(strColons); - yyMsg() << "Qualifying with unknown namespace/class " - << qPrintable(stringifyNamespace(functionContext)) << "::" - << qPrintable(unresolved.first()) << std::endl; + yyMsg() << qPrintable(LU::tr("Qualifying with unknown namespace/class %1::%2\n") + .arg(stringifyNamespace(functionContext)).arg(unresolved.first())); } pendingContext.clear(); } @@ -1797,7 +1799,7 @@ void CppParser::parseInternal(ConversionData &cd, QSet &inclusions) if (functionContextUnresolved.isEmpty()) { int idx = functionContext.length(); if (idx < 2) { - yyMsg() << "tr() cannot be called without context\n"; + yyMsg() << qPrintable(LU::tr("tr() cannot be called without context\n")); break; } Namespace *fctx; @@ -1806,8 +1808,8 @@ void CppParser::parseInternal(ConversionData &cd, QSet &inclusions) context = stringifyNamespace(functionContext); fctx = findNamespace(functionContext)->classDef; if (!fctx->complained) { - yyMsg() << "Class '" << qPrintable(context) - << "' lacks Q_OBJECT macro\n"; + yyMsg() << qPrintable(LU::tr("Class '%1' lacks Q_OBJECT macro\n") + .arg(context)); fctx->complained = true; } goto gotctx; @@ -1835,8 +1837,8 @@ void CppParser::parseInternal(ConversionData &cd, QSet &inclusions) int last = prefix.lastIndexOf(strColons); QString className = prefix.mid(last == -1 ? 0 : last + 2); if (!className.isEmpty() && className == functionName) { - yyMsg() << "It is not recommended to call tr() from within a constructor '" - << qPrintable(className) << "::" << qPrintable(functionName) << "'\n"; + yyMsg() << qPrintable(LU::tr("It is not recommended to call tr() from within a constructor '%1::%2'\n") + .arg(className).arg(functionName)); } #endif prefix.chop(2); @@ -1851,7 +1853,7 @@ void CppParser::parseInternal(ConversionData &cd, QSet &inclusions) context = fctx->trQualification; } if (!fctx->hasTrFunctions && !fctx->complained) { - yyMsg() << "Class '" << qPrintable(context) << "' lacks Q_OBJECT macro\n"; + yyMsg() << qPrintable(LU::tr("Class '%1' lacks Q_OBJECT macro\n").arg(context)); fctx->complained = true; } } else { @@ -1873,7 +1875,7 @@ void CppParser::parseInternal(ConversionData &cd, QSet &inclusions) if (!tor) goto case_default; if (!sourcetext.isEmpty()) - yyMsg() << "//% cannot be used with translate() / QT_TRANSLATE_NOOP(). Ignoring\n"; + yyMsg() << qPrintable(LU::tr("//% cannot be used with translate() / QT_TRANSLATE_NOOP(). Ignoring\n")); utf8 = (yyTok == Tok_translateUtf8); line = yyLineNo; yyTok = getToken(); @@ -1928,7 +1930,7 @@ void CppParser::parseInternal(ConversionData &cd, QSet &inclusions) if (!tor) goto case_default; if (!msgid.isEmpty()) - yyMsg() << "//= cannot be used with qtTrId() / QT_TRID_NOOP(). Ignoring\n"; + yyMsg() << qPrintable(LU::tr("//= cannot be used with qtTrId() / QT_TRID_NOOP(). Ignoring\n")); //utf8 = false; // Maybe use //%% or something like that line = yyLineNo; yyTok = getToken(); @@ -1995,13 +1997,13 @@ void CppParser::parseInternal(ConversionData &cd, QSet &inclusions) if (isspace(c)) continue; if (c != '"') { - yyMsg() << "Unexpected character in meta string\n"; + yyMsg() << qPrintable(LU::tr("Unexpected character in meta string\n")); break; } forever { if (p >= yyWord.length()) { whoops: - yyMsg() << "Unterminated meta string\n"; + yyMsg() << qPrintable(LU::tr("Unterminated meta string\n")); break; } c = yyWord.unicode()[p++].unicode(); @@ -2054,7 +2056,7 @@ void CppParser::parseInternal(ConversionData &cd, QSet &inclusions) case Tok_Arrow: yyTok = getToken(); if (yyTok == Tok_tr || yyTok == Tok_trUtf8) - yyMsg() << "Cannot invoke tr() like this\n"; + yyMsg() << qPrintable(LU::tr("Cannot invoke tr() like this\n")); break; case Tok_ColonColon: if (yyBraceDepth == namespaceDepths.count() && yyParenDepth == 0 && !yyTokColonSeen) @@ -2087,7 +2089,7 @@ void CppParser::parseInternal(ConversionData &cd, QSet &inclusions) prospectiveContext.clear(); prefix.clear(); if (!sourcetext.isEmpty() || !extracomment.isEmpty() || !msgid.isEmpty() || !extra.isEmpty()) { - yyMsg() << "Discarding unconsumed meta data\n"; + yyMsg() << qPrintable(LU::tr("Discarding unconsumed meta data\n")); sourcetext.clear(); extracomment.clear(); msgid.clear(); @@ -2127,16 +2129,16 @@ void CppParser::parseInternal(ConversionData &cd, QSet &inclusions) if (yyBraceDepth != 0) yyMsg(yyBraceLineNo) - << "Unbalanced opening brace in C++ code" - " (or abuse of the C++ preprocessor)\n"; + << qPrintable(LU::tr("Unbalanced opening brace in C++ code" + " (or abuse of the C++ preprocessor)\n")); else if (yyParenDepth != 0) yyMsg(yyParenLineNo) - << "Unbalanced opening parenthesis in C++ code" - " (or abuse of the C++ preprocessor)\n"; + << qPrintable(LU::tr("Unbalanced opening parenthesis in C++ code" + " (or abuse of the C++ preprocessor)\n")); else if (yyBracketDepth != 0) yyMsg(yyBracketLineNo) - << "Unbalanced opening bracket in C++ code" - " (or abuse of the C++ preprocessor)\n"; + << qPrintable(LU::tr("Unbalanced opening bracket in C++ code" + " (or abuse of the C++ preprocessor)\n")); } const ParseResults *CppParser::recordResults(bool isHeader) @@ -2197,8 +2199,7 @@ void loadCPP(Translator &translator, const QStringList &filenames, ConversionDat QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { - cd.appendError(QString::fromLatin1("Cannot open %1: %2") - .arg(filename, file.errorString())); + cd.appendError(LU::tr("Cannot open %1: %2").arg(filename, file.errorString())); continue; } diff --git a/tools/linguist/lupdate/java.cpp b/tools/linguist/lupdate/java.cpp index dc66e2b..165b6a3 100644 --- a/tools/linguist/lupdate/java.cpp +++ b/tools/linguist/lupdate/java.cpp @@ -50,6 +50,7 @@ #include #include #include +#include #include @@ -57,6 +58,10 @@ QT_BEGIN_NAMESPACE +class LU { + Q_DECLARE_TR_FUNCTIONS(LUpdate) +}; + enum { Tok_Eof, Tok_class, Tok_return, Tok_tr, Tok_translate, Tok_Ident, Tok_Package, Tok_Comment, Tok_String, Tok_Colon, Tok_Dot, @@ -196,7 +201,7 @@ static int getToken() while ( !metAsterSlash ) { yyCh = getChar(); if ( yyCh == EOF ) { - yyMsg() << "Unterminated Java comment.\n"; + yyMsg() << qPrintable(LU::tr("Unterminated Java comment.\n")); return Tok_Comment; } @@ -232,7 +237,7 @@ static int getToken() else { int sub(yyCh.toLower().toAscii() - 87); if( sub > 15 || sub < 10) { - yyMsg() << "Invalid Unicode value.\n"; + yyMsg() << qPrintable(LU::tr("Invalid Unicode value.\n")); break; } unicode += sub; @@ -255,7 +260,7 @@ static int getToken() } if ( yyCh != QLatin1Char('"') ) - yyMsg() << "Unterminated string.\n"; + yyMsg() << qPrintable(LU::tr("Unterminated string.\n")); yyCh = getChar(); @@ -368,8 +373,9 @@ static bool matchString( QString &s ) if (yyTok == Tok_String) s += yyString; else { - yyMsg() << "String used in translation can contain only literals" - " concatenated with other literals, not expressions or numbers.\n"; + yyMsg() << qPrintable(LU::tr( + "String used in translation can contain only literals" + " concatenated with other literals, not expressions or numbers.\n")); return false; } yyTok = getToken(); @@ -477,7 +483,7 @@ static void parse( Translator *tor ) yyScope.push(new Scope(yyIdent, Scope::Clazz, yyLineNo)); } else { - yyMsg() << "'class' must be followed by a class name.\n"; + yyMsg() << qPrintable(LU::tr("'class' must be followed by a class name.\n")); break; } while (!match(Tok_LeftBrace)) { @@ -549,7 +555,7 @@ static void parse( Translator *tor ) case Tok_RightBrace: if ( yyScope.isEmpty() ) { - yyMsg() << "Excess closing brace.\n"; + yyMsg() << qPrintable(LU::tr("Excess closing brace.\n")); } else delete (yyScope.pop()); @@ -578,7 +584,7 @@ static void parse( Translator *tor ) yyPackage.append(QLatin1String(".")); break; default: - yyMsg() << "'package' must be followed by package name.\n"; + yyMsg() << qPrintable(LU::tr("'package' must be followed by package name.\n")); break; } yyTok = getToken(); @@ -591,9 +597,9 @@ static void parse( Translator *tor ) } if ( !yyScope.isEmpty() ) - yyMsg(yyScope.top()->line) << "Unbalanced opening brace.\n"; + yyMsg(yyScope.top()->line) << qPrintable(LU::tr("Unbalanced opening brace.\n")); else if ( yyParenDepth != 0 ) - yyMsg(yyParenLineNo) << "Unbalanced opening parenthesis.\n"; + yyMsg(yyParenLineNo) << qPrintable(LU::tr("Unbalanced opening parenthesis.\n")); } @@ -601,8 +607,7 @@ bool loadJava(Translator &translator, const QString &filename, ConversionData &c { QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { - cd.appendError(QString::fromLatin1("Cannot open %1: %2") - .arg(filename, file.errorString())); + cd.appendError(LU::tr("Cannot open %1: %2").arg(filename, file.errorString())); return false; } diff --git a/tools/linguist/lupdate/main.cpp b/tools/linguist/lupdate/main.cpp index 0ff5288..d96e205 100644 --- a/tools/linguist/lupdate/main.cpp +++ b/tools/linguist/lupdate/main.cpp @@ -81,7 +81,7 @@ static void recursiveFileInfoList(const QDir &dir, static void printUsage() { - printOut(QObject::tr( + printOut(LU::tr( "Usage:\n" " lupdate [options] [project-file]...\n" " lupdate [options] [source-file|path|@lst-file]... -ts ts-files|@lst-file\n\n" @@ -188,7 +188,7 @@ static void updateTsFiles(const Translator &fetchedTor, const QStringList &tsFil else if (options & AbsoluteLocations) tor.setLocationsType(Translator::AbsoluteLocations); if (options & Verbose) - printOut(QObject::tr("Updating '%1'...\n").arg(fn)); + printOut(LU::tr("Updating '%1'...\n").arg(fn)); UpdateOptions theseOptions = options; if (tor.locationsType() == Translator::NoLocations) // Could be set from file @@ -203,7 +203,7 @@ static void updateTsFiles(const Translator &fetchedTor, const QStringList &tsFil } if (options & PluralOnly) { if (options & Verbose) - printOut(QObject::tr("Stripping non plural forms in '%1'...\n").arg(fn)); + printOut(LU::tr("Stripping non plural forms in '%1'...\n").arg(fn)); out.stripNonPluralForms(); } if (options & NoObsolete) @@ -361,12 +361,12 @@ static void processProjects( if (visitor.contains(QLatin1String("TRANSLATIONS"))) { if (parentTor) { if (topLevel) { - std::cerr << "lupdate warning: TS files from command line " - "will override TRANSLATIONS in " << qPrintable(proFile) << ".\n"; + std::cerr << qPrintable(LU::tr("lupdate warning: TS files from command line " + "will override TRANSLATIONS in %1.\n").arg(proFile)); goto noTrans; } else if (nestComplain) { - std::cerr << "lupdate warning: TS files from command line " - "prevent recursing into " << qPrintable(proFile) << ".\n"; + std::cerr << qPrintable(LU::tr("lupdate warning: TS files from command line " + "prevent recursing into %1.\n").arg(proFile)); continue; } } @@ -397,8 +397,8 @@ static void processProjects( noTrans: if (!parentTor) { if (topLevel) - std::cerr << "lupdate warning: no TS files specified. Only diagnostics " - "will be produced for '" << qPrintable(proFile) << "'.\n"; + std::cerr << qPrintable(LU::tr("lupdate warning: no TS files specified. Only diagnostics " + "will be produced for '%1'.\n").arg(proFile)); Translator tor; processProject(nestComplain, pfi, visitor, options, codecForSource, targetLanguage, sourceLanguage, &tor, fail); @@ -625,7 +625,7 @@ int main(int argc, char **argv) proFiles << file; } else if (fi.isDir()) { if (options & Verbose) - printOut(QObject::tr("Scanning directory '%1'...\n").arg(file)); + printOut(LU::tr("Scanning directory '%1'...\n").arg(file)); QDir dir = QDir(fi.filePath()); projectRoots.insert(dir.absolutePath() + QLatin1Char('/')); if (extensionsNameFilters.isEmpty()) { diff --git a/tools/linguist/lupdate/merge.cpp b/tools/linguist/lupdate/merge.cpp index fffdf9b..87c150c 100644 --- a/tools/linguist/lupdate/merge.cpp +++ b/tools/linguist/lupdate/merge.cpp @@ -44,15 +44,19 @@ #include "simtexth.h" #include "translator.h" +#include #include #include #include #include #include - QT_BEGIN_NAMESPACE +class LU { + Q_DECLARE_TR_FUNCTIONS(LUpdate) +}; + static bool isDigitFriendly(QChar c) { return c.isPunct() || c.isSpace(); @@ -485,24 +489,24 @@ Translator merge(const Translator &tor, const Translator &virginTor, if (options & Verbose) { int totalFound = neww + known; - err += QObject::tr(" Found %n source text(s) (%1 new and %2 already existing)\n", 0, totalFound).arg(neww).arg(known); + err += LU::tr(" Found %n source text(s) (%1 new and %2 already existing)\n", 0, totalFound).arg(neww).arg(known); if (obsoleted) { if (options & NoObsolete) { - err += QObject::tr(" Removed %n obsolete entries\n", 0, obsoleted); + err += LU::tr(" Removed %n obsolete entries\n", 0, obsoleted); } else { - err += QObject::tr(" Kept %n obsolete entries\n", 0, obsoleted); + err += LU::tr(" Kept %n obsolete entries\n", 0, obsoleted); } } if (sameNumberHeuristicCount) - err += QObject::tr(" Number heuristic provided %n translation(s)\n", + err += LU::tr(" Number heuristic provided %n translation(s)\n", 0, sameNumberHeuristicCount); if (sameTextHeuristicCount) - err += QObject::tr(" Same-text heuristic provided %n translation(s)\n", + err += LU::tr(" Same-text heuristic provided %n translation(s)\n", 0, sameTextHeuristicCount); if (similarTextHeuristicCount) - err += QObject::tr(" Similar-text heuristic provided %n translation(s)\n", + err += LU::tr(" Similar-text heuristic provided %n translation(s)\n", 0, similarTextHeuristicCount); } return outTor; diff --git a/tools/linguist/lupdate/qdeclarative.cpp b/tools/linguist/lupdate/qdeclarative.cpp index 2377416..ffcbf20 100644 --- a/tools/linguist/lupdate/qdeclarative.cpp +++ b/tools/linguist/lupdate/qdeclarative.cpp @@ -65,6 +65,10 @@ QT_BEGIN_NAMESPACE +class LU { + Q_DECLARE_TR_FUNCTIONS(LUpdate) +}; + using namespace QDeclarativeJS; class FindTrCalls: protected AST::Visitor @@ -241,8 +245,7 @@ bool loadQml(Translator &translator, const QString &filename, ConversionData &cd cd.m_sourceFileName = filename; QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { - cd.appendError(QString::fromLatin1("Cannot open %1: %2") - .arg(filename, file.errorString())); + cd.appendError(LU::tr("Cannot open %1: %2").arg(filename, file.errorString())); return false; } diff --git a/tools/linguist/lupdate/qscript.cpp b/tools/linguist/lupdate/qscript.cpp index 7ca0987..5323022 100644 --- a/tools/linguist/lupdate/qscript.cpp +++ b/tools/linguist/lupdate/qscript.cpp @@ -47,6 +47,7 @@ #include +#include #include #include #include @@ -62,6 +63,10 @@ QT_BEGIN_NAMESPACE +class LU { + Q_DECLARE_TR_FUNCTIONS(LUpdate) +}; + class QScriptGrammar { public: @@ -1486,7 +1491,7 @@ int QScript::Lexer::lex() else { setDone(Bad); err = IllegalCharacter; - errmsg = QLatin1String("Illegal character"); + errmsg = LU::tr("Illegal character"); } } break; @@ -1497,7 +1502,7 @@ int QScript::Lexer::lex() } else if (current == 0 || isLineTerminator()) { setDone(Bad); err = UnclosedStringLiteral; - errmsg = QLatin1String("Unclosed string at end of line"); + errmsg = LU::tr("Unclosed string at end of line"); } else if (current == '\\') { state = InEscapeSequence; } else { @@ -1523,7 +1528,7 @@ int QScript::Lexer::lex() } else { setDone(Bad); err = IllegalEscapeSequence; - errmsg = QLatin1String("Illegal escape squence"); + errmsg = LU::tr("Illegal escape squence"); } } else if (current == 'x') state = InHexEscape; @@ -1562,7 +1567,7 @@ int QScript::Lexer::lex() } else { setDone(Bad); err = IllegalUnicodeEscapeSequence; - errmsg = QLatin1String("Illegal unicode escape sequence"); + errmsg = LU::tr("Illegal unicode escape sequence"); } break; case InSingleLineComment: @@ -1590,7 +1595,7 @@ int QScript::Lexer::lex() if (current == 0) { setDone(Bad); err = UnclosedComment; - errmsg = QLatin1String("Unclosed comment at end of file"); + errmsg = LU::tr("Unclosed comment at end of file"); } else if (isLineTerminator()) { shiftWindowsLineBreak(); yylineno++; @@ -1678,7 +1683,7 @@ int QScript::Lexer::lex() } else { setDone(Bad); err = IllegalExponentIndicator; - errmsg = QLatin1String("Illegal syntax for exponential number"); + errmsg = LU::tr("Illegal syntax for exponential number"); } break; case InExponent: @@ -1704,7 +1709,7 @@ int QScript::Lexer::lex() && isIdentLetter(current)) { state = Bad; err = IllegalIdentifier; - errmsg = QLatin1String("Identifier cannot start with numeric literal"); + errmsg = LU::tr("Identifier cannot start with numeric literal"); } // terminate string @@ -2023,7 +2028,7 @@ bool QScript::Lexer::scanRegExp(RegExpBodyPrefix prefix) while (1) { if (isLineTerminator() || current == 0) { - errmsg = QLatin1String("Unterminated regular expression literal"); + errmsg = LU::tr("Unterminated regular expression literal"); return false; } else if (current != '/' || lastWasEscape == true) @@ -2267,14 +2272,14 @@ case 66: { QString name = sym(1).toString(); if ((name == QLatin1String("qsTranslate")) || (name == QLatin1String("QT_TRANSLATE_NOOP"))) { if (!sourcetext.isEmpty()) - yyMsg(identLineNo) << "//% cannot be used with " << qPrintable(name) << "(). Ignoring\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("//% cannot be used with %1(). Ignoring\n").arg(name)); QVariantList args = sym(2).toList(); if (args.size() < 2) { - yyMsg(identLineNo) << qPrintable(name) << "() requires at least two arguments.\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("%1() requires at least two arguments.\n").arg(name)); } else { if ((args.at(0).type() != QVariant::String) || (args.at(1).type() != QVariant::String)) { - yyMsg(identLineNo) << qPrintable(name) << "(): both arguments must be literal strings.\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("%1(): both arguments must be literal strings.\n").arg(name)); } else { QString context = args.at(0).toString(); QString text = args.at(1).toString(); @@ -2290,13 +2295,13 @@ case 66: { extra.clear(); } else if ((name == QLatin1String("qsTr")) || (name == QLatin1String("QT_TR_NOOP"))) { if (!sourcetext.isEmpty()) - yyMsg(identLineNo) << "//% cannot be used with " << qPrintable(name) << "(). Ignoring\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("//% cannot be used with %1(). Ignoring\n").arg(name)); QVariantList args = sym(2).toList(); if (args.size() < 1) { - yyMsg(identLineNo) << qPrintable(name) << "() requires at least one argument.\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("%1() requires at least one argument.\n").arg(name)); } else { if (args.at(0).type() != QVariant::String) { - yyMsg(identLineNo) << qPrintable(name) << "(): text to translate must be a literal string.\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("%1(): text to translate must be a literal string.\n").arg(name)); } else { QString context = QFileInfo(fileName()).baseName(); QString text = args.at(0).toString(); @@ -2312,13 +2317,13 @@ case 66: { extra.clear(); } else if ((name == QLatin1String("qsTrId")) || (name == QLatin1String("QT_TRID_NOOP"))) { if (!msgid.isEmpty()) - yyMsg(identLineNo) << "//= cannot be used with " << qPrintable(name) << "(). Ignoring\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("//= cannot be used with %1(). Ignoring\n").arg(name)); QVariantList args = sym(2).toList(); if (args.size() < 1) { - yyMsg(identLineNo) << qPrintable(name) << "() requires at least one argument.\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("%1() requires at least one argument.\n").arg(name)); } else { if (args.at(0).type() != QVariant::String) { - yyMsg(identLineNo) << qPrintable(name) << "(): identifier must be a literal string.\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("%1(): identifier must be a literal string.\n").arg(name)); } else { msgid = args.at(0).toString(); bool plural = (args.size() > 1); @@ -2386,7 +2391,7 @@ case 94: { case 185: if (!sourcetext.isEmpty() || !extracomment.isEmpty() || !msgid.isEmpty() || !extra.isEmpty()) { - yyMsg() << "Discarding unconsumed meta data\n"; + yyMsg() << qPrintable(LU::tr("Discarding unconsumed meta data\n")); sourcetext.clear(); extracomment.clear(); msgid.clear(); @@ -2448,7 +2453,9 @@ case 94: { for (int s = 0; s < shifts; ++s) { if (first) - error_message += QLatin1String ("Expected "); + //: Beginning of the string that contains + //: comma-separated list of expected tokens + error_message += LU::tr("Expected "); else error_message += QLatin1String (", "); @@ -2502,13 +2509,13 @@ void QScriptParser::processComment(const QChar *chars, int length) if (isspace(c)) continue; if (c != '"') { - yyMsg() << "Unexpected character in meta string\n"; + yyMsg() << qPrintable(LU::tr("Unexpected character in meta string\n")); break; } forever { if (p >= length) { whoops: - yyMsg() << "Unterminated meta string\n"; + yyMsg() << qPrintable(LU::tr("Unterminated meta string\n")); break; } c = chars[p++].unicode(); @@ -2534,8 +2541,7 @@ bool loadQScript(Translator &translator, const QString &filename, ConversionData { QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { - cd.appendError(QString::fromLatin1("Cannot open %1: %2") - .arg(filename, file.errorString())); + cd.appendError(LU::tr("Cannot open %1: %2").arg(filename, file.errorString())); return false; } QTextStream ts(&file); diff --git a/tools/linguist/lupdate/qscript.g b/tools/linguist/lupdate/qscript.g index e4c2d22..3655f2e 100644 --- a/tools/linguist/lupdate/qscript.g +++ b/tools/linguist/lupdate/qscript.g @@ -84,6 +84,7 @@ /. #include +#include #include #include #include @@ -99,6 +100,10 @@ QT_BEGIN_NAMESPACE +class LU { + Q_DECLARE_TR_FUNCTIONS(LUpdate) +}; + static void recordMessage( Translator *tor, const QString &context, const QString &text, const QString &comment, const QString &extracomment, const QString &msgid, const TranslatorMessage::ExtraData &extra, @@ -817,7 +822,7 @@ int QScript::Lexer::lex() else { setDone(Bad); err = IllegalCharacter; - errmsg = QLatin1String("Illegal character"); + errmsg = LU::tr("Illegal character"); } } break; @@ -828,7 +833,7 @@ int QScript::Lexer::lex() } else if (current == 0 || isLineTerminator()) { setDone(Bad); err = UnclosedStringLiteral; - errmsg = QLatin1String("Unclosed string at end of line"); + errmsg = LU::tr("Unclosed string at end of line"); } else if (current == '\\') { state = InEscapeSequence; } else { @@ -854,7 +859,7 @@ int QScript::Lexer::lex() } else { setDone(Bad); err = IllegalEscapeSequence; - errmsg = QLatin1String("Illegal escape squence"); + errmsg = LU::tr("Illegal escape squence"); } } else if (current == 'x') state = InHexEscape; @@ -893,7 +898,7 @@ int QScript::Lexer::lex() } else { setDone(Bad); err = IllegalUnicodeEscapeSequence; - errmsg = QLatin1String("Illegal unicode escape sequence"); + errmsg = LU::tr("Illegal unicode escape sequence"); } break; case InSingleLineComment: @@ -921,7 +926,7 @@ int QScript::Lexer::lex() if (current == 0) { setDone(Bad); err = UnclosedComment; - errmsg = QLatin1String("Unclosed comment at end of file"); + errmsg = LU::tr("Unclosed comment at end of file"); } else if (isLineTerminator()) { shiftWindowsLineBreak(); yylineno++; @@ -1009,7 +1014,7 @@ int QScript::Lexer::lex() } else { setDone(Bad); err = IllegalExponentIndicator; - errmsg = QLatin1String("Illegal syntax for exponential number"); + errmsg = LU::tr("Illegal syntax for exponential number"); } break; case InExponent: @@ -1035,7 +1040,7 @@ int QScript::Lexer::lex() && isIdentLetter(current)) { state = Bad; err = IllegalIdentifier; - errmsg = QLatin1String("Identifier cannot start with numeric literal"); + errmsg = LU::tr("Identifier cannot start with numeric literal"); } // terminate string @@ -1354,7 +1359,7 @@ bool QScript::Lexer::scanRegExp(RegExpBodyPrefix prefix) while (1) { if (isLineTerminator() || current == 0) { - errmsg = QLatin1String("Unterminated regular expression literal"); + errmsg = LU::tr("Unterminated regular expression literal"); return false; } else if (current != '/' || lastWasEscape == true) @@ -1683,14 +1688,14 @@ case $rule_number: { QString name = sym(1).toString(); if ((name == QLatin1String("qsTranslate")) || (name == QLatin1String("QT_TRANSLATE_NOOP"))) { if (!sourcetext.isEmpty()) - yyMsg(identLineNo) << "//% cannot be used with " << qPrintable(name) << "(). Ignoring\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("//% cannot be used with %1(). Ignoring\n").arg(name)); QVariantList args = sym(2).toList(); if (args.size() < 2) { - yyMsg(identLineNo) << qPrintable(name) << "() requires at least two arguments.\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("%1() requires at least two arguments.\n").arg(name)); } else { if ((args.at(0).type() != QVariant::String) || (args.at(1).type() != QVariant::String)) { - yyMsg(identLineNo) << qPrintable(name) << "(): both arguments must be literal strings.\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("%1(): both arguments must be literal strings.\n").arg(name)); } else { QString context = args.at(0).toString(); QString text = args.at(1).toString(); @@ -1706,13 +1711,13 @@ case $rule_number: { extra.clear(); } else if ((name == QLatin1String("qsTr")) || (name == QLatin1String("QT_TR_NOOP"))) { if (!sourcetext.isEmpty()) - yyMsg(identLineNo) << "//% cannot be used with " << qPrintable(name) << "(). Ignoring\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("//% cannot be used with %1(). Ignoring\n").arg(name)); QVariantList args = sym(2).toList(); if (args.size() < 1) { - yyMsg(identLineNo) << qPrintable(name) << "() requires at least one argument.\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("%1() requires at least one argument.\n").arg(name)); } else { if (args.at(0).type() != QVariant::String) { - yyMsg(identLineNo) << qPrintable(name) << "(): text to translate must be a literal string.\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("%1(): text to translate must be a literal string.\n").arg(name)); } else { QString context = QFileInfo(fileName()).baseName(); QString text = args.at(0).toString(); @@ -1728,13 +1733,13 @@ case $rule_number: { extra.clear(); } else if ((name == QLatin1String("qsTrId")) || (name == QLatin1String("QT_TRID_NOOP"))) { if (!msgid.isEmpty()) - yyMsg(identLineNo) << "//= cannot be used with " << qPrintable(name) << "(). Ignoring\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("//= cannot be used with %1(). Ignoring\n").arg(name)); QVariantList args = sym(2).toList(); if (args.size() < 1) { - yyMsg(identLineNo) << qPrintable(name) << "() requires at least one argument.\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("%1() requires at least one argument.\n").arg(name)); } else { if (args.at(0).type() != QVariant::String) { - yyMsg(identLineNo) << qPrintable(name) << "(): identifier must be a literal string.\n"; + yyMsg(identLineNo) << qPrintable(LU::tr("%1(): identifier must be a literal string.\n").arg(name)); } else { msgid = args.at(0).toString(); bool plural = (args.size() > 1); @@ -1950,7 +1955,7 @@ Statement: DebuggerStatement ; /. case $rule_number: if (!sourcetext.isEmpty() || !extracomment.isEmpty() || !msgid.isEmpty() || !extra.isEmpty()) { - yyMsg() << "Discarding unconsumed meta data\n"; + yyMsg() << qPrintable(LU::tr("Discarding unconsumed meta data\n")); sourcetext.clear(); extracomment.clear(); msgid.clear(); @@ -2096,6 +2101,9 @@ PropertyNameAndValueListOpt: PropertyNameAndValueList ; { if (first) error_message += QLatin1String ("Expected "); + //: Beginning of the string that contains + //: comma-separated list of expected tokens + error_message += LU::tr("Expected "); else error_message += QLatin1String (", "); @@ -2149,13 +2157,13 @@ void QScriptParser::processComment(const QChar *chars, int length) if (isspace(c)) continue; if (c != '"') { - yyMsg() << "Unexpected character in meta string\n"; + yyMsg() << qPrintable(LU::tr("Unexpected character in meta string\n")); break; } forever { if (p >= length) { whoops: - yyMsg() << "Unterminated meta string\n"; + yyMsg() << qPrintable(LU::tr("Unterminated meta string\n")); break; } c = chars[p++].unicode(); @@ -2181,8 +2189,7 @@ bool loadQScript(Translator &translator, const QString &filename, ConversionData { QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { - cd.appendError(QString::fromLatin1("Cannot open %1: %2") - .arg(filename, file.errorString())); + cd.appendError(LU::tr("Cannot open %1: %2").arg(filename, file.errorString())); return false; } QTextStream ts(&file); diff --git a/tools/linguist/lupdate/ui.cpp b/tools/linguist/lupdate/ui.cpp index 9e22922..797ab1f 100644 --- a/tools/linguist/lupdate/ui.cpp +++ b/tools/linguist/lupdate/ui.cpp @@ -43,6 +43,7 @@ #include +#include #include #include #include @@ -55,6 +56,10 @@ QT_BEGIN_NAMESPACE +class LU { + Q_DECLARE_TR_FUNCTIONS(LUpdate) +}; + class UiReader : public QXmlDefaultHandler { public: @@ -152,11 +157,10 @@ bool UiReader::characters(const QString &ch) bool UiReader::fatalError(const QXmlParseException &exception) { - QString msg; - msg.sprintf("XML error: Parse error at line %d, column %d (%s).", - exception.lineNumber(), exception.columnNumber(), - exception.message().toLatin1().data()); - m_cd.appendError(msg); + QString msg = LU::tr("XML error: Parse error at line %1, column %2 (%3).") + .arg(exception.lineNumber()).arg(exception.columnNumber()) + .arg(exception.message()); + m_cd.appendError(msg); return false; } @@ -181,8 +185,7 @@ bool loadUI(Translator &translator, const QString &filename, ConversionData &cd) cd.m_sourceFileName = filename; QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { - cd.appendError(QString::fromLatin1("Cannot open %1: %2") - .arg(filename, file.errorString())); + cd.appendError(LU::tr("Cannot open %1: %2").arg(filename, file.errorString())); return false; } QXmlInputSource in(&file); @@ -196,7 +199,7 @@ bool loadUI(Translator &translator, const QString &filename, ConversionData &cd) reader.setErrorHandler(&handler); bool result = reader.parse(in); if (!result) - cd.appendError(QLatin1String("Parse error in UI file")); + cd.appendError(LU::tr("Parse error in UI file")); reader.setContentHandler(0); reader.setErrorHandler(0); return result; -- cgit v0.12 From dd1a7c2186348157c4a255f56f280006c8d8c17d Mon Sep 17 00:00:00 2001 From: Miikka Heikkinen Date: Wed, 1 Sep 2010 13:02:15 +0300 Subject: QT_PLUGINS_BASE_DIR needs to be defined after load(qt_config) QT_LIBINFIX is defined in qconfig.pri, so qt_config needs to be loaded before that is used. Reviewed-by: TrustMe --- mkspecs/common/symbian/symbian.conf | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mkspecs/common/symbian/symbian.conf b/mkspecs/common/symbian/symbian.conf index 04b81b0..61cc7d9 100644 --- a/mkspecs/common/symbian/symbian.conf +++ b/mkspecs/common/symbian/symbian.conf @@ -117,11 +117,12 @@ QMAKE_GZIP = gzip -9f QT_ARCH = symbian +load(qt_config) + # These directories must match what configure uses for QT_INSTALL_PLUGINS and QT_INSTALL_IMPORTS QT_PLUGINS_BASE_DIR = /resource/qt$${QT_LIBINFIX}/plugins QT_IMPORTS_BASE_DIR = /resource/qt/imports -load(qt_config) load(symbian/platform_paths) # The Symbian^3 PDK does not necessarily contain the required sis files. -- cgit v0.12 From bc0c6e9bb53f935c659dda90c7968d7738705f38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 1 Sep 2010 08:57:36 +0200 Subject: Use NEON and preloading for 16 bit small / medium sized image blits. This gives a nice speedup for blitting of small and medium sized images by using preloading and avoiding function call overhead to memcpy for each scanline. For larger image widths memcpy becomes more efficient. Speedups of up to 40 % for 64 pixel wide images were measured. For image widths between 2 and 16 the speedup ranges between 12 % and 28 %. Task-number: QT-3401 Reviewed-by: Benjamin Poulain --- src/gui/painting/qblendfunctions.cpp | 8 +-- src/gui/painting/qdrawhelper.cpp | 1 + src/gui/painting/qdrawhelper_neon.cpp | 98 +++++++++++++++++++++++++++++++++++ src/gui/painting/qdrawhelper_neon_p.h | 5 ++ 4 files changed, 108 insertions(+), 4 deletions(-) diff --git a/src/gui/painting/qblendfunctions.cpp b/src/gui/painting/qblendfunctions.cpp index 24908ce..0edf256 100644 --- a/src/gui/painting/qblendfunctions.cpp +++ b/src/gui/painting/qblendfunctions.cpp @@ -254,10 +254,10 @@ void qt_scale_image_argb32_on_rgb16(uchar *destPixels, int dbpl, } } -static void qt_blend_rgb16_on_rgb16(uchar *dst, int dbpl, - const uchar *src, int sbpl, - int w, int h, - int const_alpha) +void qt_blend_rgb16_on_rgb16(uchar *dst, int dbpl, + const uchar *src, int sbpl, + int w, int h, + int const_alpha) { #ifdef QT_DEBUG_DRAW printf("qt_blend_rgb16_on_rgb16: dst=(%p, %d), src=(%p, %d), dim=(%d, %d) alpha=%d\n", diff --git a/src/gui/painting/qdrawhelper.cpp b/src/gui/painting/qdrawhelper.cpp index 5223458..5e1509d 100644 --- a/src/gui/painting/qdrawhelper.cpp +++ b/src/gui/painting/qdrawhelper.cpp @@ -8014,6 +8014,7 @@ void qInitDrawhelperAsm() qBlendFunctions[QImage::Format_ARGB32_Premultiplied][QImage::Format_ARGB32_Premultiplied] = qt_blend_argb32_on_argb32_neon; qBlendFunctions[QImage::Format_RGB16][QImage::Format_ARGB32_Premultiplied] = qt_blend_argb32_on_rgb16_neon; qBlendFunctions[QImage::Format_ARGB32_Premultiplied][QImage::Format_RGB16] = qt_blend_rgb16_on_argb32_neon; + qBlendFunctions[QImage::Format_RGB16][QImage::Format_RGB16] = qt_blend_rgb16_on_rgb16_neon; qScaleFunctions[QImage::Format_RGB16][QImage::Format_ARGB32_Premultiplied] = qt_scale_image_argb32_on_rgb16_neon; qScaleFunctions[QImage::Format_RGB16][QImage::Format_RGB16] = qt_scale_image_rgb16_on_rgb16_neon; diff --git a/src/gui/painting/qdrawhelper_neon.cpp b/src/gui/painting/qdrawhelper_neon.cpp index ed15c5c..0afd077 100644 --- a/src/gui/painting/qdrawhelper_neon.cpp +++ b/src/gui/painting/qdrawhelper_neon.cpp @@ -167,6 +167,14 @@ pixman_composite_scanline_over_asm_neon (int32_t w, const uint32_t *dst, const uint32_t *src); +extern "C" void +pixman_composite_src_0565_0565_asm_neon (int32_t w, + int32_t h, + uint16_t *dst, + int32_t dst_stride, + uint16_t *src, + int32_t src_stride); + // qblendfunctions.cpp void qt_blend_argb32_on_rgb16_const_alpha(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, @@ -200,6 +208,96 @@ void qt_blend_rgb16_on_argb32_neon(uchar *destPixels, int dbpl, pixman_composite_src_0565_8888_asm_neon(w, h, dst, dbpl, src, sbpl); } +// qblendfunctions.cpp +void qt_blend_rgb16_on_rgb16(uchar *dst, int dbpl, + const uchar *src, int sbpl, + int w, int h, + int const_alpha); + +template +static inline void scanLineBlit16(quint16 *dst, quint16 *src, int dstride) +{ + if (N >= 2) { + ((quint32 *)dst)[0] = ((quint32 *)src)[0]; + __builtin_prefetch(dst + dstride, 1, 0); + } + for (int i = 1; i < N/2; ++i) + ((quint32 *)dst)[i] = ((quint32 *)src)[i]; + if (N & 1) + dst[N-1] = src[N-1]; +} + +template +static inline void blockBlit16(quint16 *dst, quint16 *src, int dstride, int sstride, int h) +{ + union { + quintptr address; + quint16 *pointer; + } u; + + u.pointer = dst; + + if (u.address & 2) { + while (h--) { + // align dst + dst[0] = src[0]; + if (Width > 1) + scanLineBlit16(dst + 1, src + 1, dstride); + dst += dstride; + src += sstride; + } + } else { + while (h--) { + scanLineBlit16(dst, src, dstride); + + dst += dstride; + src += sstride; + } + } +} + +void qt_blend_rgb16_on_rgb16_neon(uchar *destPixels, int dbpl, + const uchar *srcPixels, int sbpl, + int w, int h, + int const_alpha) +{ + // testing show that the default memcpy is faster for widths 150 and up + if (const_alpha != 256 || w >= 150) { + qt_blend_rgb16_on_rgb16(destPixels, dbpl, srcPixels, sbpl, w, h, const_alpha); + return; + } + + int dstride = dbpl / 2; + int sstride = sbpl / 2; + + quint16 *dst = (quint16 *) destPixels; + quint16 *src = (quint16 *) srcPixels; + + switch (w) { +#define BLOCKBLIT(n) case n: blockBlit16(dst, src, dstride, sstride, h); return; + BLOCKBLIT(1); + BLOCKBLIT(2); + BLOCKBLIT(3); + BLOCKBLIT(4); + BLOCKBLIT(5); + BLOCKBLIT(6); + BLOCKBLIT(7); + BLOCKBLIT(8); + BLOCKBLIT(9); + BLOCKBLIT(10); + BLOCKBLIT(11); + BLOCKBLIT(12); + BLOCKBLIT(13); + BLOCKBLIT(14); + BLOCKBLIT(15); +#undef BLOCKBLIT + default: + break; + } + + pixman_composite_src_0565_0565_asm_neon (w, h, dst, dstride, src, sstride); +} + extern "C" void blend_8_pixels_argb32_on_rgb16_neon(quint16 *dst, const quint32 *src, int const_alpha); void qt_blend_argb32_on_rgb16_neon(uchar *destPixels, int dbpl, diff --git a/src/gui/painting/qdrawhelper_neon_p.h b/src/gui/painting/qdrawhelper_neon_p.h index 451edbc..d25b7ec 100644 --- a/src/gui/painting/qdrawhelper_neon_p.h +++ b/src/gui/painting/qdrawhelper_neon_p.h @@ -84,6 +84,11 @@ void qt_blend_rgb16_on_argb32_neon(uchar *destPixels, int dbpl, int w, int h, int const_alpha); +void qt_blend_rgb16_on_rgb16_neon(uchar *destPixels, int dbpl, + const uchar *srcPixels, int sbpl, + int w, int h, + int const_alpha); + void qt_alphamapblit_quint16_neon(QRasterBuffer *rasterBuffer, int x, int y, quint32 color, const uchar *bitmap, -- cgit v0.12 From dcb98430f6add24c9d54253bd35d35010cc75c23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Trond=20Kjern=C3=A5sen?= Date: Wed, 1 Sep 2010 12:33:55 +0200 Subject: Fix a crash when passing a null pixmap to QPainter::drawPixmapFragments(). Task-number: QTBUG-13331 Reviewed-by: Samuel --- src/gui/painting/qpainter.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/painting/qpainter.cpp b/src/gui/painting/qpainter.cpp index 4e10671..c6046ac 100644 --- a/src/gui/painting/qpainter.cpp +++ b/src/gui/painting/qpainter.cpp @@ -9028,7 +9028,7 @@ void QPainter::drawPixmapFragments(const PixmapFragment *fragments, int fragment { Q_D(QPainter); - if (!d->engine) + if (!d->engine || pixmap.isNull()) return; #ifndef QT_NO_DEBUG -- cgit v0.12 From 25622198904580c6eb93996f74c2e7b62afa77c7 Mon Sep 17 00:00:00 2001 From: Jiang Jiang Date: Mon, 30 Aug 2010 14:03:37 +0200 Subject: Fix compiling issue for FreeType version earlier than 2.1.10 FT_GlyphSlot_Embolden was introduced since FreeType 2.1.10 and we started using it since 4.7. Some systems (including RHEL/CentOS 4) only provide earlier versions will get a compiling error if they use -system-freetype to build Qt. This patch fix it by providing a graceful degradation when the function is not available. Task-number: QTBUG-13274 Reviewed-by: Eskil --- src/gui/text/qfontengine_ft.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/gui/text/qfontengine_ft.cpp b/src/gui/text/qfontengine_ft.cpp index 2c4fbab..60db8b6 100644 --- a/src/gui/text/qfontengine_ft.cpp +++ b/src/gui/text/qfontengine_ft.cpp @@ -94,6 +94,13 @@ QT_BEGIN_NAMESPACE #define Y_SIZE(face,i) ((face)->available_sizes[i].height << 6) #endif +/* FreeType 2.1.10 starts to provide FT_GlyphSlot_Embolden */ +#if (FREETYPE_MAJOR*10000+FREETYPE_MINOR*100+FREETYPE_PATCH) >= 20110 +#define Q_FT_GLYPHSLOT_EMBOLDEN(slot) FT_GlyphSlot_Embolden(slot) +#else +#define Q_FT_GLYPHSLOT_EMBOLDEN(slot) +#endif + #define FLOOR(x) ((x) & -64) #define CEIL(x) (((x)+63) & -64) #define TRUNC(x) ((x) >> 6) @@ -794,7 +801,7 @@ QFontEngineFT::Glyph *QFontEngineFT::loadGlyphMetrics(QGlyphSet *set, uint glyph } FT_GlyphSlot slot = face->glyph; - if (embolden) FT_GlyphSlot_Embolden(slot); + if (embolden) Q_FT_GLYPHSLOT_EMBOLDEN(slot); int left = slot->metrics.horiBearingX; int right = slot->metrics.horiBearingX + slot->metrics.width; int top = slot->metrics.horiBearingY; @@ -940,7 +947,7 @@ QFontEngineFT::Glyph *QFontEngineFT::loadGlyph(QGlyphSet *set, uint glyph, Glyph return 0; FT_GlyphSlot slot = face->glyph; - if (embolden) FT_GlyphSlot_Embolden(slot); + if (embolden) Q_FT_GLYPHSLOT_EMBOLDEN(slot); FT_Library library = qt_getFreetype(); info.xOff = TRUNC(ROUND(slot->advance.x)); -- cgit v0.12 From a28de57a7d8556f0ba20031f956070ef8a654038 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Wed, 1 Sep 2010 11:06:46 +0200 Subject: QDeclarative: Fix spelling mistake. --- src/declarative/util/qdeclarativeanimation.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/declarative/util/qdeclarativeanimation.cpp b/src/declarative/util/qdeclarativeanimation.cpp index 267642d..3c09747 100644 --- a/src/declarative/util/qdeclarativeanimation.cpp +++ b/src/declarative/util/qdeclarativeanimation.cpp @@ -332,7 +332,7 @@ void QDeclarativeAbstractAnimation::setAlwaysRunToEnd(bool f) stopped - either by setting the \c running property to false, or by calling the \c stop() method. - In the following example, the rectangle will spin indefinately. + In the following example, the rectangle will spin indefinitely. \code Rectangle { -- cgit v0.12 From 08854de08165027acd3973876f1fffd6a1ed120f Mon Sep 17 00:00:00 2001 From: Morten Engvoldsen Date: Wed, 1 Sep 2010 14:52:45 +0200 Subject: Doc: removing bug breaking the article into pages. These pages was not linked anywhere. --- doc/src/getting-started/gettingstartedqml.qdoc | 36 ++++++++++---------------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/doc/src/getting-started/gettingstartedqml.qdoc b/doc/src/getting-started/gettingstartedqml.qdoc index a19d281..405e791 100644 --- a/doc/src/getting-started/gettingstartedqml.qdoc +++ b/doc/src/getting-started/gettingstartedqml.qdoc @@ -404,13 +404,9 @@ \image qml-texteditor2_menubar.png - */ + \section1 Building a Text Editor - /*! - \page qml-textEditor3.html - \title Building a Text Editor - - \section1 Declaring a TextArea + \section2 Declaring a TextArea Our text editor is not a text editor if it didn't contain an editable text area. QML's \l {TextEdit}{TextEdit} element allows the declaration of a multi-line @@ -451,7 +447,7 @@ } \endcode - \section1 Combining Components for the Text Editor + \section2 Combining Components for the Text Editor We are now ready to create the layout of our text editor using QML. The text editor has two components, the menu bar we created and the text area. QML allows @@ -494,12 +490,8 @@ \image qml-texteditor3_texteditor.png - */ - - /*! - \page qml-textEditor4 - \title Decorating the Text Editor - \section1 Implementing a Drawer Interface + \section1 Decorating the Text Editor + \section2 Implementing a Drawer Interface Our text editor looks simple and we need to decorate it. Using QML, we can declare transitions and animate our text editor. Our menu bar is occupying one-third of the @@ -652,7 +644,7 @@ The first color starts at \c 0.0 and the last color is at \c 1.0. - \section2 Where to Go from Here + \section3 Where to Go from Here We are finished building the user interface of a very simple text editor. Going forward, the user interface is complete, and we can implement the @@ -661,7 +653,7 @@ \image qml-texteditor4_texteditor.png - \section1 Extending QML using Qt C++ + \section2 Extending QML using Qt C++ Now that we have our text editor layout, we may now implement the text editor functionalities in C++. Using QML with C++ enables us to create our application @@ -672,7 +664,7 @@ we shall implement the load and save functions in C++ and export it as a plugin. This way, we only need to load the QML file directly instead of running an executable. - \section2 Exposing C++ Classes to QML + \section3 Exposing C++ Classes to QML We will be implementing file loading and saving using Qt and C++. C++ classes and functions can be used in QML by registering them. The class also needs to be @@ -687,7 +679,7 @@ \o A \c qmldir file telling the qmlviewer tool where to find the plugin \endlist - \section2 Building a Qt Plugin + \section3 Building a Qt Plugin To build a plugin, we need to set the following in a Qt project file. First, the necessary sources, headers, and Qt modules need to be added into our @@ -721,7 +713,7 @@ parent's \c plugins directory. - \section2 Registering a Class into QML + \section3 Registering a Class into QML \code In dialogPlugin.h: @@ -771,7 +763,7 @@ file to generate the necessary meta-object code. - \section2 Creating QML Properties in a C++ class + \section3 Creating QML Properties in a C++ class We can create QML elements and properties using C++ and \l {The Meta-Object System}{Qt's Meta-Object System}. We can implement @@ -925,7 +917,7 @@ \c make to build and transfer the plugin to the \c plugins directory. - \section2 Importing a Plugin in QML + \section3 Importing a Plugin in QML The qmlviewer tool imports files that are in the same directory as the application. We can also create a \c qmldir file containing the locations of @@ -948,7 +940,7 @@ \c TARGET field in the project file. The compiled plugin is in the \c plugins directory. - \section2 Integrating a File Dialog into the File Menu + \section3 Integrating a File Dialog into the File Menu Our \c FileMenu needs to display the \c FileDialog element, containing a list of the text files in a directory thus allowing the user to select the file by @@ -1038,7 +1030,7 @@ \image qml-texteditor5_filemenu.png - \section1 Text Editor Completion + \section2 Text Editor Completion \image qml-texteditor5_newfile.png -- cgit v0.12 From 51f8b65b585a198a62daa4403374441b667966ce Mon Sep 17 00:00:00 2001 From: axis Date: Wed, 25 Aug 2010 15:41:32 +0200 Subject: Added catching of errors in timers. According to the bug report this may happen in SMP systems and systems with certain schedulers. This patch does not actually fix the bug which causes the timer error, but avoids the timer firing if it happens, and gives a chance to handle the error. Task: QT-3591 RevBy: mread --- src/corelib/kernel/qeventdispatcher_symbian.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/corelib/kernel/qeventdispatcher_symbian.cpp b/src/corelib/kernel/qeventdispatcher_symbian.cpp index 1bad8ed..5cc6ae3 100644 --- a/src/corelib/kernel/qeventdispatcher_symbian.cpp +++ b/src/corelib/kernel/qeventdispatcher_symbian.cpp @@ -232,8 +232,12 @@ void QTimerActiveObject::DoCancel() void QTimerActiveObject::RunL() { - int error; - QT_TRYCATCH_ERROR(error, Run()); + int error = KErrNone; + if (iStatus == KErrNone) { + QT_TRYCATCH_ERROR(error, Run()); + } else { + error = iStatus.Int(); + } // All Symbian error codes are negative. if (error < 0) { CActiveScheduler::Current()->Error(error); // stop and report here, as this timer will be deleted on scope exit -- cgit v0.12 From c5901037f0d3ccd45b0c79b38ef5b04552dad0aa Mon Sep 17 00:00:00 2001 From: axis Date: Fri, 27 Aug 2010 10:31:39 +0200 Subject: Revert "Long-press shortcuts for symbols on QWERTY keyboard don't work" This reverts commit 05eacd9ad40f8adb5aaa12a8b90113a73b43f642. Conflicts: src/gui/inputmethod/qcoefepinputcontext_p.h src/gui/inputmethod/qcoefepinputcontext_s60.cpp --- src/gui/inputmethod/qcoefepinputcontext_p.h | 1 - src/gui/inputmethod/qcoefepinputcontext_s60.cpp | 15 +-------------- src/gui/widgets/qlinecontrol.cpp | 2 +- 3 files changed, 2 insertions(+), 16 deletions(-) diff --git a/src/gui/inputmethod/qcoefepinputcontext_p.h b/src/gui/inputmethod/qcoefepinputcontext_p.h index d5243c3..cc14e89 100644 --- a/src/gui/inputmethod/qcoefepinputcontext_p.h +++ b/src/gui/inputmethod/qcoefepinputcontext_p.h @@ -151,7 +151,6 @@ private: int m_inlinePosition; MFepInlineTextFormatRetriever *m_formatRetriever; MFepPointerEventHandlerDuringInlineEdit *m_pointerHandler; - int m_cursorPos; QBasicTimer m_tempPreeditStringTimeout; bool m_hasTempPreeditString; }; diff --git a/src/gui/inputmethod/qcoefepinputcontext_s60.cpp b/src/gui/inputmethod/qcoefepinputcontext_s60.cpp index c4d60a5..73396b6 100644 --- a/src/gui/inputmethod/qcoefepinputcontext_s60.cpp +++ b/src/gui/inputmethod/qcoefepinputcontext_s60.cpp @@ -79,7 +79,6 @@ QCoeFepInputContext::QCoeFepInputContext(QObject *parent) m_inlinePosition(0), m_formatRetriever(0), m_pointerHandler(0), - m_cursorPos(0), m_hasTempPreeditString(false) { m_fepState->SetObjectProvider(this); @@ -596,8 +595,6 @@ void QCoeFepInputContext::StartFepInlineEditL(const TDesC& aInitialInlineText, commitTemporaryPreeditString(); - m_cursorPos = w->inputMethodQuery(Qt::ImCursorPosition).toInt(); - QList attributes; m_cursorVisibility = aCursorVisibility ? 1 : 0; @@ -820,23 +817,13 @@ void QCoeFepInputContext::commitCurrentString(bool cancelFepTransaction) { int longPress = 0; - if (m_preeditString.size() == 0) { - QWidget *w = focusWidget(); - if (!cancelFepTransaction && w) { - // We must replace the last character only if the input box has already accepted one - if (w->inputMethodQuery(Qt::ImCursorPosition).toInt() != m_cursorPos) - longPress = 1; - } - } - QList attributes; QInputMethodEvent event(QLatin1String(""), attributes); - event.setCommitString(m_preeditString, 0-longPress, longPress); + event.setCommitString(m_preeditString, 0, 0); m_preeditString.clear(); sendEvent(event); m_hasTempPreeditString = false; - longPress = 0; if (cancelFepTransaction) { CCoeFep* fep = CCoeEnv::Static()->Fep(); diff --git a/src/gui/widgets/qlinecontrol.cpp b/src/gui/widgets/qlinecontrol.cpp index d027b91..b6dfd13 100644 --- a/src/gui/widgets/qlinecontrol.cpp +++ b/src/gui/widgets/qlinecontrol.cpp @@ -419,7 +419,7 @@ void QLineControl::processInputMethodEvent(QInputMethodEvent *event) int c = m_cursor; // cursor position after insertion of commit string - if (event->replacementStart() == 0) + if (event->replacementStart() <= 0) c += event->commitString().length() + qMin(-event->replacementStart(), event->replacementLength()); m_cursor += event->replacementStart(); -- cgit v0.12 From abcfda3554ef2d1c1ab994a5215a9aa6b107c64a Mon Sep 17 00:00:00 2001 From: Jens Bache-Wiig Date: Wed, 1 Sep 2010 15:01:51 +0200 Subject: Add some more changes for 4.7.0 --- dist/changes-4.7.0 | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/dist/changes-4.7.0 b/dist/changes-4.7.0 index 01ebf63..a5939e3 100644 --- a/dist/changes-4.7.0 +++ b/dist/changes-4.7.0 @@ -88,7 +88,10 @@ QtGui - QComboBox * [QTBUG-8796] Made ForegroundRole work for all styles. - + + - QCommandLinkButton + * [QTBUG-5995] Fixed text and icon alignment issues. + - QPrinter * Obsoleted the slightly confusing setNumCopies() and numCopies() functions, and replaced them with setCopyCount(), copyCount() and @@ -133,6 +136,9 @@ QtGui * [QTBUG-7982] Added QImage::bitPlaneCount(). * [QTBUG-9072] Fixed alpha check for 1-bit-per-pixel images. + - QLineEdit + * [QTBUG-9823] Placeholder text is now correctly aligned with text. + - QPicture * [QTBUG-4974] Printing QPictures containing text to a high resolution QPrinter would in many cases cause incorrect character spacing. @@ -286,8 +292,9 @@ Qt for Linux/X11 ---------------- - QGtkStyle * Fixed rtl issues with sliders (QTBUG-8986) - * Fixed missing pressed appearance on scroll bar handles. (QTBUG-10396) - + * Fixed missing pressed appearance on scroll bar handles. (QTBUG-10396) + * Fixed crash when creating QGtkStyle before QApplication. (QTBUG-10758) + - QFontDatabase * [QTBUG-4428] Fixed regression when using bitmap fonts on some Linux systems. @@ -303,7 +310,12 @@ Qt for Linux/X11 Qt for Windows -------------- - Popup windows now implicitly activate when shown. (QTBUG-7386) - + - QComboBox [QTBUG-7552] Fix an issue where only "..." would be shown for + QComboBox with certain DPI settings. + - Fixed a problem where menus exec'ed on system tray icons did not + disappear. (QTBUG-7386) + - Improved look and feel for QWizard on Windows 7 and Vista. (QTBUG-9873), + (QTBUG-11974) and (QTBUG-6120) - QLocalSocket * Pipe handle leak fixed, when closing a QLocalSocket that still has unwritten data. (QTBUG-7815) @@ -315,7 +327,9 @@ Qt for Mac OS X --------------- - QMacStyle * Removed frame around statusbar items. (QTBUG-3574) - * More native appearance of item view headers and frames. (QTBUG-10047) + * More native appearance of item view headers and frames. (QTBUG-10047) + * Increased spacing between tree view items. (QTBUG-10190) + * Removed frame around status bar items. (QTBUG-3574) - QFontEngine * Enable fractional metrics for the font engine on Mac in all -- cgit v0.12 From 52cf47565e402dc682038ccaf8d725401802b603 Mon Sep 17 00:00:00 2001 From: axis Date: Tue, 31 Aug 2010 13:15:28 +0200 Subject: Cleaned up position tracking in the Symbian input methods. This fixed a case where using password mode would lead to Qt believing that the cursor was one step to the left of where it really was. This would have the effect of replacing the last character instead of appending to it, and even crashing if the cursor was all the way to the left. The code is also much cleaner this way, but it meant that QTBUG-9867 had to be solved differently this time. We do this by assuming that and empty FEP update means "erase last character", which seems to work well in practice. Also added a long overdue autotest for the FEP input methods. Most tests pass, but some don't, which I will try to fix later. Task: QTBUG-9867 Task: QTBUG-12949 RevBy: Miikka Heikkinen AutoTest: Included --- src/gui/inputmethod/qcoefepinputcontext_p.h | 10 +- src/gui/inputmethod/qcoefepinputcontext_s60.cpp | 19 +- src/gui/kernel/qt_s60_p.h | 4 +- tests/auto/qinputcontext/qinputcontext.pro | 4 + tests/auto/qinputcontext/tst_qinputcontext.cpp | 659 +++++++++++++++++++++++- 5 files changed, 679 insertions(+), 17 deletions(-) diff --git a/src/gui/inputmethod/qcoefepinputcontext_p.h b/src/gui/inputmethod/qcoefepinputcontext_p.h index cc14e89..2fd6d16 100644 --- a/src/gui/inputmethod/qcoefepinputcontext_p.h +++ b/src/gui/inputmethod/qcoefepinputcontext_p.h @@ -66,10 +66,10 @@ QT_BEGIN_NAMESPACE -class QCoeFepInputContext : public QInputContext, - public MCoeFepAwareTextEditor, - public MCoeFepAwareTextEditor_Extension1, - public MObjectProvider +class Q_AUTOTEST_EXPORT QCoeFepInputContext : public QInputContext, + public MCoeFepAwareTextEditor, + public MCoeFepAwareTextEditor_Extension1, + public MObjectProvider { Q_OBJECT @@ -153,6 +153,8 @@ private: MFepPointerEventHandlerDuringInlineEdit *m_pointerHandler; QBasicTimer m_tempPreeditStringTimeout; bool m_hasTempPreeditString; + + friend class tst_QInputContext; }; QT_END_NAMESPACE diff --git a/src/gui/inputmethod/qcoefepinputcontext_s60.cpp b/src/gui/inputmethod/qcoefepinputcontext_s60.cpp index 73396b6..135b894 100644 --- a/src/gui/inputmethod/qcoefepinputcontext_s60.cpp +++ b/src/gui/inputmethod/qcoefepinputcontext_s60.cpp @@ -240,7 +240,6 @@ bool QCoeFepInputContext::filterEvent(const QEvent *event) && focusWidget()->inputMethodHints() & Qt::ImhHiddenText && !keyEvent->text().isEmpty()) { // Send some temporary preedit text in order to make text visible for a moment. - m_cursorPos = focusWidget()->inputMethodQuery(Qt::ImCursorPosition).toInt(); m_preeditString = keyEvent->text(); QList attributes; QInputMethodEvent imEvent(m_preeditString, attributes); @@ -296,10 +295,6 @@ void QCoeFepInputContext::commitTemporaryPreeditString() return; commitCurrentString(false); - - //update cursor position, now this pre-edit text has been committed. - //this prevents next keypress overwriting it (QTBUG-11673) - m_cursorPos = focusWidget()->inputMethodQuery(Qt::ImCursorPosition).toInt(); } void QCoeFepInputContext::mouseHandler( int x, QMouseEvent *event) @@ -609,9 +604,10 @@ void QCoeFepInputContext::StartFepInlineEditL(const TDesC& aInitialInlineText, // Let's remove the selected text if aInitialInlineText is empty and there is selected text if (m_preeditString.isEmpty()) { int anchor = w->inputMethodQuery(Qt::ImAnchorPosition).toInt(); - int replacementLength = qAbs(m_cursorPos-anchor); + int cursorPos = w->inputMethodQuery(Qt::ImCursorPosition).toInt(); + int replacementLength = qAbs(cursorPos-anchor); if (replacementLength > 0) { - int replacementStart = m_cursorPos < anchor ? 0 : -replacementLength; + int replacementStart = cursorPos < anchor ? 0 : -replacementLength; QList clearSelectionAttributes; QInputMethodEvent clearSelectionEvent(QLatin1String(""), clearSelectionAttributes); clearSelectionEvent.setCommitString(QLatin1String(""), replacementStart, replacementLength); @@ -644,8 +640,13 @@ void QCoeFepInputContext::UpdateFepInlineTextL(const TDesC& aNewInlineText, m_inlinePosition, m_cursorVisibility, QVariant())); - m_preeditString = qt_TDesC2QString(aNewInlineText); - QInputMethodEvent event(m_preeditString, attributes); + QString newPreeditString = qt_TDesC2QString(aNewInlineText); + QInputMethodEvent event(newPreeditString, attributes); + if (newPreeditString.isEmpty() && m_preeditString.isEmpty()) { + // In Symbian world this means "erase last character". + event.setCommitString("", -1, 1); + } + m_preeditString = newPreeditString; sendEvent(event); } diff --git a/src/gui/kernel/qt_s60_p.h b/src/gui/kernel/qt_s60_p.h index ad6a99a..4b60842 100644 --- a/src/gui/kernel/qt_s60_p.h +++ b/src/gui/kernel/qt_s60_p.h @@ -87,7 +87,7 @@ const TInt KInternalStatusPaneChange = 0x50000000; //this macro exists because EColor16MAP enum value doesn't exist in Symbian OS 9.2 #define Q_SYMBIAN_ECOLOR16MAP TDisplayMode(13) -class QS60ThreadLocalData +class Q_AUTOTEST_EXPORT QS60ThreadLocalData { public: QS60ThreadLocalData(); @@ -171,7 +171,7 @@ public: #endif }; -QS60Data* qGlobalS60Data(); +Q_AUTOTEST_EXPORT QS60Data* qGlobalS60Data(); #define S60 qGlobalS60Data() class QAbstractLongTapObserver diff --git a/tests/auto/qinputcontext/qinputcontext.pro b/tests/auto/qinputcontext/qinputcontext.pro index b3ea8c2..ec6831e 100644 --- a/tests/auto/qinputcontext/qinputcontext.pro +++ b/tests/auto/qinputcontext/qinputcontext.pro @@ -1,2 +1,6 @@ load(qttest_p4) SOURCES += tst_qinputcontext.cpp + +symbian { + LIBS += -lws32 -lcone +} diff --git a/tests/auto/qinputcontext/tst_qinputcontext.cpp b/tests/auto/qinputcontext/tst_qinputcontext.cpp index 644b463..23cfd9e 100644 --- a/tests/auto/qinputcontext/tst_qinputcontext.cpp +++ b/tests/auto/qinputcontext/tst_qinputcontext.cpp @@ -48,17 +48,26 @@ #include #include #include +#include + +#ifdef Q_OS_SYMBIAN +#include +#include + +#include +#include +#endif class tst_QInputContext : public QObject { Q_OBJECT public: - tst_QInputContext() {} + tst_QInputContext() : m_phoneIsQwerty(false) {} virtual ~tst_QInputContext() {} public slots: - void initTestCase() {} + void initTestCase(); void cleanupTestCase() {} void init() {} void cleanup() {} @@ -69,8 +78,176 @@ private slots: void closeSoftwareInputPanel(); void selections(); void focusProxy(); + void symbianTestCoeFepInputContext_data(); + void symbianTestCoeFepInputContext(); + +private: + bool m_phoneIsQwerty; }; +#ifdef Q_OS_SYMBIAN +class KeyEvent : public TWsEvent +{ +public: + KeyEvent(QWidget *w, TInt type, TInt scanCode, TUint code, TUint modifiers, TInt repeats) { + iHandle = w->effectiveWinId()->DrawableWindow()->WindowGroupId(); + iType = type; + SetTimeNow(); + TKeyEvent *keyEvent = reinterpret_cast(iEventData); + keyEvent->iScanCode = scanCode; + keyEvent->iCode = code; + keyEvent->iModifiers = modifiers; + keyEvent->iRepeats = repeats; + } +}; + +class FepReplayEvent +{ +public: + enum Type { + Pause, + Key, + CompleteKey + }; + + FepReplayEvent(int msecsToPause) + : m_type(Pause) + , m_msecsToPause(msecsToPause) + { + } + + FepReplayEvent(TInt keyType, TInt scanCode, TUint code, TUint modifiers, TInt repeats) + : m_type(Key) + , m_keyType(keyType) + , m_scanCode(scanCode) + , m_code(code) + , m_modifiers(modifiers) + , m_repeats(repeats) + { + } + + FepReplayEvent(TInt scanCode, TUint code, TUint modifiers, TInt repeats) + : m_type(CompleteKey) + , m_scanCode(scanCode) + , m_code(code) + , m_modifiers(modifiers) + , m_repeats(repeats) + { + } + + void sendEvent(QWidget *w, TInt type, TInt scanCode, TUint code, TUint modifiers, TInt repeats) + { + KeyEvent event(w, type, scanCode, code, modifiers, repeats); + S60->wsSession().SendEventToWindowGroup(w->effectiveWinId()->DrawableWindow()->WindowGroupId(), event); + } + + void pause(int msecs) + { + // Don't use qWait here. The polling nature of that function screws up the test. + QTimer timer; + QEventLoop loop; + QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); + timer.setSingleShot(true); + timer.start(msecs); + loop.exec(); + } + + // For some reason, the test fails if using processEvents instead of an event loop + // with a zero timer to quit it, so use the timer. +#define KEY_WAIT 0 + + void replay(QWidget *w) + { + if (m_type == Pause) { + pause(m_msecsToPause); + } else if (m_type == Key) { + sendEvent(w, m_keyType, m_scanCode, m_code, m_modifiers, m_repeats); + if (m_keyType != EEventKeyDown) + // EEventKeyDown events should have no pause before the EEventKey event. + pause(KEY_WAIT); + } else if (m_type == CompleteKey) { + sendEvent(w, EEventKeyDown, m_scanCode, 0, m_modifiers, m_repeats); + // EEventKeyDown events should have no pause before the EEventKey event. + sendEvent(w, EEventKey, m_scanCode, m_code, m_modifiers, m_repeats); + pause(KEY_WAIT); + sendEvent(w, EEventKeyUp, m_scanCode, 0, m_modifiers, m_repeats); + pause(KEY_WAIT); + } + } + +private: + Type m_type; + int m_msecsToPause; + TInt m_keyType; + TInt m_scanCode; + TUint m_code; + TUint m_modifiers; + TInt m_repeats; +}; + +Q_DECLARE_METATYPE(QList) +Q_DECLARE_METATYPE(Qt::InputMethodHints) +Q_DECLARE_METATYPE(QLineEdit::EchoMode); + +#endif // Q_OS_SYMBIAN + +void tst_QInputContext::initTestCase() +{ +#ifdef Q_OS_SYMBIAN + // Sanity test. Checks FEP for: + // - T9 mode is default (it will attempt to fix this) + // - Language is English (it cannot fix this; bail out if not correct) + QWidget w; + QLayout *layout = new QVBoxLayout; + w.setLayout(layout); + QLineEdit *lineedit = new QLineEdit; + layout->addWidget(lineedit); + lineedit->setFocus(); +#ifdef QT_KEYPAD_NAVIGATION + lineedit->setEditFocus(true); +#endif + w.show(); + + QDesktopWidget desktop; + QRect screenSize = desktop.screenGeometry(&w); + if (screenSize.width() > screenSize.height()) { + // Crude way of finding out we are running on a qwerty phone. + m_phoneIsQwerty = true; + return; + } + + for (int iterations = 0; iterations < 16; iterations++) { + QTest::qWait(500); + + QList keyEvents; + + keyEvents << FepReplayEvent('9', '9', 0, 0); + keyEvents << FepReplayEvent('6', '6', 0, 0); + keyEvents << FepReplayEvent('8', '8', 0, 0); + keyEvents << FepReplayEvent(EStdKeyRightArrow, EKeyRightArrow, 0, 0); + + foreach(FepReplayEvent event, keyEvents) { + event.replay(lineedit); + } + + QApplication::processEvents(); + + if (lineedit->text().endsWith("you", Qt::CaseInsensitive)) { + // Success! + return; + } + + // Try changing modes. + // After 8 iterations, try to press the mode switch twice before typing. + for (int c = 0; c <= iterations / 8; c++) { + FepReplayEvent(EStdKeyHash, '#', 0, 0).replay(lineedit); + } + } + + QFAIL("FEP sanity test failed. Either the phone is not set to English, or the test was unable to enable T9"); +#endif +} + void tst_QInputContext::maximumTextLength() { QLineEdit le; @@ -285,5 +462,483 @@ void tst_QInputContext::focusProxy() QCOMPARE(gic->focusWidget(), &proxy); } +void tst_QInputContext::symbianTestCoeFepInputContext_data() +{ +#ifdef Q_OS_SYMBIAN + QTest::addColumn ("inputMethodEnabled"); + QTest::addColumn ("inputMethodHints"); + QTest::addColumn ("maxLength"); // Zero for no limit + QTest::addColumn ("echoMode"); + QTest::addColumn > ("keyEvents"); + QTest::addColumn ("finalString"); + QTest::addColumn ("preeditString"); + QList events; + + events << FepReplayEvent(EStdKeyBackspace, EKeyBackspace, 0, 0); + events << FepReplayEvent(EStdKeyBackspace, EKeyBackspace, 0, 0); + events << FepReplayEvent('5', '5', 0, 0); + events << FepReplayEvent('4', '4', 0, 0); + events << FepReplayEvent('6', '6', 0, 0); + events << FepReplayEvent(EStdKeyBackspace, EKeyBackspace, 0, 0); + events << FepReplayEvent(EStdKeyBackspace, EKeyBackspace, 0, 0); + events << FepReplayEvent('1', '1', 0, 0); + events << FepReplayEvent(EStdKeyBackspace, EKeyBackspace, 0, 0); + events << FepReplayEvent('2', '2', 0, 0); + events << FepReplayEvent('1', '1', 0, 0); + QTest::newRow("Numbers (no FEP)") + << false + << Qt::InputMethodHints(Qt::ImhNone) + << 0 + << QLineEdit::Normal + << events + << QString("521") + << QString(""); + QTest::newRow("Numbers and password mode (no FEP)") + << false + << Qt::InputMethodHints(Qt::ImhNone) + << 0 + << QLineEdit::Password + << events + << QString("521") + << QString(""); + QTest::newRow("Numbers") + << true + << Qt::InputMethodHints(Qt::ImhDigitsOnly) + << 0 + << QLineEdit::Normal + << events + << QString("521") + << QString(""); + QTest::newRow("Numbers max length (no FEP)") + << false + << Qt::InputMethodHints(Qt::ImhNone) + << 2 + << QLineEdit::Normal + << events + << QString("21") + << QString(""); + QTest::newRow("Numbers max length") + << true + << Qt::InputMethodHints(Qt::ImhDigitsOnly) + << 2 + << QLineEdit::Normal + << events + << QString("21") + << QString(""); + events.clear(); + + events << FepReplayEvent(EEventKeyDown, '5', 0, 0, 0); + events << FepReplayEvent(EEventKey, '5', '5', 0, 0); + events << FepReplayEvent(EEventKey, '5', '5', 0, 1); + events << FepReplayEvent(EEventKey, '5', '5', 0, 1); + events << FepReplayEvent(EEventKeyUp, '5', 0, 0, 0); + QTest::newRow("Numbers and autorepeat (no FEP)") + << false + << Qt::InputMethodHints(Qt::ImhNone) + << 0 + << QLineEdit::Normal + << events + << QString("555") + << QString(""); + events.clear(); + + events << FepReplayEvent(EStdKeyBackspace, EKeyBackspace, 0, 0); + events << FepReplayEvent('2', '2', 0, 0); + events << FepReplayEvent('3', '3', 0, 0); + events << FepReplayEvent('4', '4', 0, 0); + events << FepReplayEvent('4', '4', 0, 0); + events << FepReplayEvent('5', '5', 0, 0); + events << FepReplayEvent('5', '5', 0, 0); + events << FepReplayEvent(EStdKeyBackspace, EKeyBackspace, 0, 0); + QTest::newRow("Multitap") + << true + << Qt::InputMethodHints(Qt::ImhNoPredictiveText) + << 0 + << QLineEdit::Normal + << events + << QString("Adh") + << QString(""); + QTest::newRow("Multitap with no auto uppercase") + << true + << Qt::InputMethodHints(Qt::ImhNoPredictiveText | Qt::ImhNoAutoUppercase) + << 0 + << QLineEdit::Normal + << events + << QString("adh") + << QString(""); + QTest::newRow("Multitap with uppercase") + << true + << Qt::InputMethodHints(Qt::ImhNoPredictiveText | Qt::ImhPreferUppercase) + << 0 + << QLineEdit::Normal + << events + << QString("ADH") + << QString(""); + QTest::newRow("Multitap with lowercase") + << true + << Qt::InputMethodHints(Qt::ImhNoPredictiveText | Qt::ImhPreferLowercase) + << 0 + << QLineEdit::Normal + << events + << QString("adh") + << QString(""); + QTest::newRow("Multitap with forced uppercase") + << true + << Qt::InputMethodHints(Qt::ImhNoPredictiveText | Qt::ImhUppercaseOnly) + << 0 + << QLineEdit::Normal + << events + << QString("ADH") + << QString(""); + QTest::newRow("Multitap with forced lowercase") + << true + << Qt::InputMethodHints(Qt::ImhNoPredictiveText | Qt::ImhLowercaseOnly) + << 0 + << QLineEdit::Normal + << events + << QString("adh") + << QString(""); + events.clear(); + + events << FepReplayEvent(EStdKeyHash, '#', 0, 0); + events << FepReplayEvent('2', '2', 0, 0); + events << FepReplayEvent('2', '2', 0, 0); + events << FepReplayEvent('3', '3', 0, 0); + events << FepReplayEvent('4', '4', 0, 0); + events << FepReplayEvent('4', '4', 0, 0); + events << FepReplayEvent('5', '5', 0, 0); + events << FepReplayEvent('5', '5', 0, 0); + events << FepReplayEvent(EStdKeyBackspace, EKeyBackspace, 0, 0); + QTest::newRow("Multitap with mode switch") + << true + << Qt::InputMethodHints(Qt::ImhNoPredictiveText) + << 0 + << QLineEdit::Normal + << events + << QString("bdh") + << QString(""); + events.clear(); + + events << FepReplayEvent('7', '7', 0, 0); + events << FepReplayEvent('7', '7', 0, 0); + events << FepReplayEvent('8', '8', 0, 0); + events << FepReplayEvent('9', '9', 0, 0); + events << FepReplayEvent('9', '9', 0, 0); + QTest::newRow("Multitap with unfinished text") + << true + << Qt::InputMethodHints(Qt::ImhNoPredictiveText) + << 0 + << QLineEdit::Normal + << events + << QString("Qt") + << QString("x"); + events << FepReplayEvent(2000); + QTest::newRow("Multitap with committed text") + << true + << Qt::InputMethodHints(Qt::ImhNoPredictiveText) + << 0 + << QLineEdit::Normal + << events + << QString("Qtx") + << QString(""); + events.clear(); + + events << FepReplayEvent('4', '4', 0, 0); + events << FepReplayEvent('4', '4', 0, 0); + // Simulate holding down hash key. + events << FepReplayEvent(EEventKeyDown, EStdKeyHash, 0, 0, 0); + events << FepReplayEvent(EEventKey, EStdKeyHash, '#', 0, 0); + events << FepReplayEvent(500); + events << FepReplayEvent(EEventKey, EStdKeyHash, '#', 0, 1); + events << FepReplayEvent(EEventKey, EStdKeyHash, '#', 0, 1); + events << FepReplayEvent(EEventKey, EStdKeyHash, '#', 0, 1); + events << FepReplayEvent(EEventKeyUp, EStdKeyHash, 0, 0, 0); + events << FepReplayEvent('7', '7', 0, 0); + events << FepReplayEvent('7', '7', 0, 0); + events << FepReplayEvent('8', '8', 0, 0); + // QTBUG-9867: Switch back as well to make sure we don't get extra symbols + events << FepReplayEvent(EEventKeyDown, EStdKeyHash, 0, 0, 0); + events << FepReplayEvent(EEventKey, EStdKeyHash, '#', 0, 0); + events << FepReplayEvent(500); + events << FepReplayEvent(EEventKey, EStdKeyHash, '#', 0, 1); + events << FepReplayEvent(EEventKey, EStdKeyHash, '#', 0, 1); + events << FepReplayEvent(EEventKey, EStdKeyHash, '#', 0, 1); + events << FepReplayEvent(EEventKeyUp, EStdKeyHash, 0, 0, 0); + events << FepReplayEvent('9', '9', 0, 0); + events << FepReplayEvent('6', '6', 0, 0); + events << FepReplayEvent('8', '8', 0, 0); + events << FepReplayEvent(2000); + events << FepReplayEvent(EStdKeyDevice3, EKeyDevice3, 0, 0); // Select key + QTest::newRow("Multitap and numbers") + << true + << Qt::InputMethodHints(Qt::ImhNoPredictiveText) + << 0 + << QLineEdit::Normal + << events + << QString("H778wmt") + << QString(""); + QTest::newRow("T9 and numbers") + << true + << Qt::InputMethodHints(Qt::ImhPreferLowercase) + << 0 + << QLineEdit::Normal + << events + << QString("hi778you") + << QString(""); + events.clear(); + + events << FepReplayEvent('4', '4', 0, 0); + events << FepReplayEvent('4', '4', 0, 0); + events << FepReplayEvent(EStdKeyDevice3, EKeyDevice3, 0, 0); // Select key + QTest::newRow("T9") + << true + << Qt::InputMethodHints(Qt::ImhPreferLowercase) + << 0 + << QLineEdit::Normal + << events + << QString("hi") + << QString(""); + QTest::newRow("T9 with uppercase") + << true + << Qt::InputMethodHints(Qt::ImhPreferUppercase) + << 0 + << QLineEdit::Normal + << events + << QString("HI") + << QString(""); + QTest::newRow("T9 with forced lowercase") + << true + << Qt::InputMethodHints(Qt::ImhLowercaseOnly) + << 0 + << QLineEdit::Normal + << events + << QString("hi") + << QString(""); + QTest::newRow("T9 with forced uppercase") + << true + << Qt::InputMethodHints(Qt::ImhUppercaseOnly) + << 0 + << QLineEdit::Normal + << events + << QString("HI") + << QString(""); + QTest::newRow("T9 with maxlength") + << true + << Qt::InputMethodHints(Qt::ImhLowercaseOnly) + << 1 + << QLineEdit::Normal + << events + << QString("i") + << QString(""); + events.clear(); + + events << FepReplayEvent('4', '4', 0, 0); + events << FepReplayEvent('4', '4', 0, 0); + events << FepReplayEvent(EStdKeyLeftArrow, EKeyLeftArrow, 0, 0); + events << FepReplayEvent(EStdKeyLeftArrow, EKeyLeftArrow, 0, 0); + events << FepReplayEvent('9', '9', 0, 0); + events << FepReplayEvent('6', '6', 0, 0); + events << FepReplayEvent('8', '8', 0, 0); + events << FepReplayEvent('0', '0', 0, 0); + events << FepReplayEvent(EStdKeyRightArrow, EKeyRightArrow, 0, 0); + events << FepReplayEvent(EStdKeyRightArrow, EKeyRightArrow, 0, 0); + events << FepReplayEvent('8', '8', 0, 0); + events << FepReplayEvent('8', '8', 0, 0); + QTest::newRow("T9 with movement and unfinished text") + << true + << Qt::InputMethodHints(Qt::ImhPreferLowercase) + << 0 + << QLineEdit::Normal + << events + << QString("you hi") + << QString("tv"); + QTest::newRow("T9 with movement, password and unfinished text") + << true + << Qt::InputMethodHints(Qt::ImhPreferLowercase) + << 0 + << QLineEdit::Password + << events + << QString("wmt h") + << QString("u"); + QTest::newRow("T9 with movement, maxlength, password and unfinished text") + << true + << Qt::InputMethodHints(Qt::ImhPreferLowercase) + << 2 + << QLineEdit::Password + << events + << QString("wh") + << QString(""); + QTest::newRow("T9 with movement, maxlength and unfinished text") + << true + << Qt::InputMethodHints(Qt::ImhPreferLowercase) + << 2 + << QLineEdit::Normal + << events + << QString("hi") + << QString(""); + QTest::newRow("Multitap with movement and unfinished text") + << true + << Qt::InputMethodHints(Qt::ImhNoPredictiveText | Qt::ImhPreferLowercase) + << 0 + << QLineEdit::Normal + << events + << QString("wmt h") + << QString("u"); + QTest::newRow("Multitap with movement, maxlength and unfinished text") + << true + << Qt::InputMethodHints(Qt::ImhNoPredictiveText | Qt::ImhPreferLowercase) + << 2 + << QLineEdit::Normal + << events + << QString("wh") + << QString(""); + QTest::newRow("Numbers with movement") + << true + << Qt::InputMethodHints(Qt::ImhDigitsOnly) + << 0 + << QLineEdit::Normal + << events + << QString("96804488") + << QString(""); + QTest::newRow("Numbers with movement and maxlength") + << true + << Qt::InputMethodHints(Qt::ImhDigitsOnly) + << 2 + << QLineEdit::Normal + << events + << QString("44") + << QString(""); + QTest::newRow("Numbers with movement, password and unfinished text") + << true + << Qt::InputMethodHints(Qt::ImhDigitsOnly) + << 0 + << QLineEdit::Password + << events + << QString("9680448") + << QString("8"); + QTest::newRow("Numbers with movement, maxlength, password and unfinished text") + << true + << Qt::InputMethodHints(Qt::ImhDigitsOnly) + << 2 + << QLineEdit::Password + << events + << QString("44") + << QString(""); + events << FepReplayEvent(EStdKeyRightArrow, EKeyRightArrow, 0, 0); + QTest::newRow("T9 with movement") + << true + << Qt::InputMethodHints(Qt::ImhPreferLowercase) + << 0 + << QLineEdit::Normal + << events + << QString("you htvi") + << QString(""); + QTest::newRow("T9 with movement and password") + << true + << Qt::InputMethodHints(Qt::ImhPreferLowercase) + << 0 + << QLineEdit::Password + << events + << QString("wmt hu") + << QString(""); + QTest::newRow("T9 with movement, maxlength and password") + << true + << Qt::InputMethodHints(Qt::ImhPreferLowercase) + << 2 + << QLineEdit::Password + << events + << QString("wh") + << QString(""); + QTest::newRow("Multitap with movement") + << true + << Qt::InputMethodHints(Qt::ImhNoPredictiveText | Qt::ImhPreferLowercase) + << 0 + << QLineEdit::Normal + << events + << QString("wmt hu") + << QString(""); + QTest::newRow("Multitap with movement and maxlength") + << true + << Qt::InputMethodHints(Qt::ImhNoPredictiveText | Qt::ImhPreferLowercase) + << 2 + << QLineEdit::Normal + << events + << QString("wh") + << QString(""); + QTest::newRow("Numbers with movement and password") + << true + << Qt::InputMethodHints(Qt::ImhDigitsOnly) + << 0 + << QLineEdit::Password + << events + << QString("96804488") + << QString(""); + QTest::newRow("Numbers with movement, maxlength and password") + << true + << Qt::InputMethodHints(Qt::ImhDigitsOnly) + << 2 + << QLineEdit::Password + << events + << QString("44") + << QString(""); + events.clear(); +#endif +} + +void tst_QInputContext::symbianTestCoeFepInputContext() +{ +#ifndef Q_OS_SYMBIAN + QSKIP("This is a Symbian-only test", SkipAll); +#else + QCoeFepInputContext *ic = qobject_cast(qApp->inputContext()); + if (!ic) { + QSKIP("coefep is not the active input context; skipping test", SkipAll); + } + + QFETCH(bool, inputMethodEnabled); + QFETCH(Qt::InputMethodHints, inputMethodHints); + QFETCH(int, maxLength); + QFETCH(QLineEdit::EchoMode, echoMode); + QFETCH(QList, keyEvents); + QFETCH(QString, finalString); + QFETCH(QString, preeditString); + + if (inputMethodEnabled && m_phoneIsQwerty) { + QSKIP("Skipping advanced input method tests on QWERTY phones", SkipSingle); + } + + QWidget w; + QLayout *layout = new QVBoxLayout; + w.setLayout(layout); + QLineEdit *lineedit = new QLineEdit; + layout->addWidget(lineedit); + lineedit->setFocus(); +#ifdef QT_KEYPAD_NAVIGATION + lineedit->setEditFocus(true); +#endif + w.show(); + + lineedit->setAttribute(Qt::WA_InputMethodEnabled, inputMethodEnabled); + lineedit->setInputMethodHints(inputMethodHints); + if (maxLength > 0) + lineedit->setMaxLength(maxLength); + lineedit->setEchoMode(echoMode); + + QTest::qWait(200); + + foreach(FepReplayEvent event, keyEvents) { + event.replay(lineedit); + } + + QApplication::processEvents(); + + QCOMPARE(lineedit->text(), finalString); + QEXPECT_FAIL("Numbers with movement, maxlength, password and unfinished text" + , "Fails due to QTBUG-12949" + , Continue); + QCOMPARE(ic->m_preeditString, preeditString); +#endif +} + QTEST_MAIN(tst_QInputContext) #include "tst_qinputcontext.moc" -- cgit v0.12 From f0ec1d2ec229f5a2c47dfa9392a2625da25fc69f Mon Sep 17 00:00:00 2001 From: axis Date: Wed, 1 Sep 2010 11:47:09 +0200 Subject: Fixed a case where a newly created native widget would lose focus. If a native control was created for a child widget, it would receive the FocusChanged signal in its QSymbianControl with a value of not- focused. This would lead the code to deactivate the whole toplevel window. This was fixed by having Qt traverse the widget chain up to the toplevel and check if parent widgets are also not focused. AutoTest: Included and passed RevBy: Denis Dzyubenko RevBy: mread --- src/gui/kernel/qapplication_s60.cpp | 29 ++++++++++++++++++-------- tests/auto/qinputcontext/tst_qinputcontext.cpp | 1 - tests/auto/qwidget/tst_qwidget.cpp | 25 ++++++++++++++++++++++ 3 files changed, 45 insertions(+), 10 deletions(-) diff --git a/src/gui/kernel/qapplication_s60.cpp b/src/gui/kernel/qapplication_s60.cpp index 7c5e790..7408360 100644 --- a/src/gui/kernel/qapplication_s60.cpp +++ b/src/gui/kernel/qapplication_s60.cpp @@ -1242,17 +1242,28 @@ void QSymbianControl::FocusChanged(TDrawNow /* aDrawNow */) S60->setStatusPaneAndButtonGroupVisibility(statusPaneVisibility, buttonGroupVisibility); #endif } else if (QApplication::activeWindow() == qwidget->window()) { - if (CCoeEnv::Static()->AppUi()->IsDisplayingMenuOrDialog() || S60->menuBeingConstructed) { - QWidget *fw = QApplication::focusWidget(); - if (fw) { - QFocusEvent event(QEvent::FocusOut, Qt::PopupFocusReason); - QCoreApplication::sendEvent(fw, &event); - } - m_symbianPopupIsOpen = true; - return; + bool focusedControlFound = false; + WId winId = 0; + for (QWidget *w = qwidget->parentWidget(); w && (winId = w->internalWinId()); w = w->parentWidget()) { + if (winId->IsFocused() && winId->IsVisible()) { + focusedControlFound = true; + break; + } else if (w->isWindow()) + break; } + if (!focusedControlFound) { + if (CCoeEnv::Static()->AppUi()->IsDisplayingMenuOrDialog() || S60->menuBeingConstructed) { + QWidget *fw = QApplication::focusWidget(); + if (fw) { + QFocusEvent event(QEvent::FocusOut, Qt::PopupFocusReason); + QCoreApplication::sendEvent(fw, &event); + } + m_symbianPopupIsOpen = true; + return; + } - QApplication::setActiveWindow(0); + QApplication::setActiveWindow(0); + } } // else { We don't touch the active window unless we were explicitly activated or deactivated } } diff --git a/tests/auto/qinputcontext/tst_qinputcontext.cpp b/tests/auto/qinputcontext/tst_qinputcontext.cpp index 23cfd9e..c90cc5b 100644 --- a/tests/auto/qinputcontext/tst_qinputcontext.cpp +++ b/tests/auto/qinputcontext/tst_qinputcontext.cpp @@ -448,7 +448,6 @@ void tst_QInputContext::focusProxy() QInputContext *gic = qApp->inputContext(); QVERIFY(gic); - qDebug() << gic->focusWidget() << &proxy; QCOMPARE(gic->focusWidget(), &proxy); // then change the focus proxy and check that input context is valid diff --git a/tests/auto/qwidget/tst_qwidget.cpp b/tests/auto/qwidget/tst_qwidget.cpp index ef05b91..098ce3c 100644 --- a/tests/auto/qwidget/tst_qwidget.cpp +++ b/tests/auto/qwidget/tst_qwidget.cpp @@ -402,6 +402,8 @@ private slots: #endif // QT_MAC_USE_COCOA #endif + void nativeChildFocus(); + private: bool ensureScreenSize(int width, int height); QWidget *testWidget; @@ -10531,5 +10533,28 @@ void tst_QWidget::taskQTBUG_11373() #endif // QT_MAC_USE_COCOA #endif +void tst_QWidget::nativeChildFocus() +{ + QWidget w; + QLayout *layout = new QVBoxLayout; + w.setLayout(layout); + QLineEdit *p1 = new QLineEdit; + QLineEdit *p2 = new QLineEdit; + layout->addWidget(p1); + layout->addWidget(p2); + p1->setObjectName("p1"); + p2->setObjectName("p2"); + w.show(); + w.activateWindow(); + p1->setFocus(); + p1->setAttribute(Qt::WA_NativeWindow); + p2->setAttribute(Qt::WA_NativeWindow); + QApplication::processEvents(); + QTest::qWaitForWindowShown(&w); + + QCOMPARE(QApplication::activeWindow(), &w); + QCOMPARE(QApplication::focusWidget(), p1); +} + QTEST_MAIN(tst_QWidget) #include "tst_qwidget.moc" -- cgit v0.12 From 5ca6264933af60b3cd376b7f08bea008fa69b515 Mon Sep 17 00:00:00 2001 From: axis Date: Wed, 1 Sep 2010 13:53:32 +0200 Subject: Fixed input context trying to squeeze content into a full widget. Problem was reproduced on N97. If the FEP detects that the widget is full while still editing text, it will try to send those events as key events instead. Since this screws up the content in the widget, we stop those events from reaching the widget in the input context. AutoTest: Passed Task: QTBUG-12949 RevBy: Miikka Heikkinen --- src/gui/inputmethod/qcoefepinputcontext_s60.cpp | 7 +++++++ tests/auto/qinputcontext/tst_qinputcontext.cpp | 3 --- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/gui/inputmethod/qcoefepinputcontext_s60.cpp b/src/gui/inputmethod/qcoefepinputcontext_s60.cpp index 135b894..add3d17 100644 --- a/src/gui/inputmethod/qcoefepinputcontext_s60.cpp +++ b/src/gui/inputmethod/qcoefepinputcontext_s60.cpp @@ -236,6 +236,13 @@ bool QCoeFepInputContext::filterEvent(const QEvent *event) break; } + QString widgetText = focusWidget()->inputMethodQuery(Qt::ImSurroundingText).toString(); + int maxLength = focusWidget()->inputMethodQuery(Qt::ImMaximumTextLength).toInt(); + if (!keyEvent->text().isEmpty() && widgetText.size() + m_preeditString.size() >= maxLength) { + // Don't send key events with string content if the widget is "full". + return true; + } + if (keyEvent->type() == QEvent::KeyPress && focusWidget()->inputMethodHints() & Qt::ImhHiddenText && !keyEvent->text().isEmpty()) { diff --git a/tests/auto/qinputcontext/tst_qinputcontext.cpp b/tests/auto/qinputcontext/tst_qinputcontext.cpp index c90cc5b..93813f9 100644 --- a/tests/auto/qinputcontext/tst_qinputcontext.cpp +++ b/tests/auto/qinputcontext/tst_qinputcontext.cpp @@ -932,9 +932,6 @@ void tst_QInputContext::symbianTestCoeFepInputContext() QApplication::processEvents(); QCOMPARE(lineedit->text(), finalString); - QEXPECT_FAIL("Numbers with movement, maxlength, password and unfinished text" - , "Fails due to QTBUG-12949" - , Continue); QCOMPARE(ic->m_preeditString, preeditString); #endif } -- cgit v0.12 From 8bc0dce2c74c28acd36daa73e84f7c9d79760e4a Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Wed, 1 Sep 2010 17:25:00 +0200 Subject: QString usage cleanups - tr() already returns a QString, duh - use multi-arg arg() (heh) --- demos/browser/downloadmanager.cpp | 2 +- examples/sql/masterdetail/mainwindow.cpp | 6 ++--- examples/tools/treemodelcompleter/mainwindow.cpp | 2 +- examples/xmlpatterns/filetree/mainwindow.cpp | 2 +- src/3rdparty/phonon/gstreamer/mediaobject.cpp | 6 ++--- tests/auto/qkeysequence/tst_qkeysequence.cpp | 28 +++++++++++----------- tools/activeqt/testcon/changeproperties.cpp | 8 +++---- tools/qdoc3/main.cpp | 2 +- .../shared/qtpropertybrowser/qtpropertymanager.cpp | 24 +++++++++---------- 9 files changed, 40 insertions(+), 40 deletions(-) diff --git a/demos/browser/downloadmanager.cpp b/demos/browser/downloadmanager.cpp index 876ec1d..ab68209 100644 --- a/demos/browser/downloadmanager.cpp +++ b/demos/browser/downloadmanager.cpp @@ -282,7 +282,7 @@ void DownloadItem::updateInfoLabel() remaining = tr("- %4 %5 remaining") .arg(timeRemaining) .arg(timeRemainingString); - info = QString(tr("%1 of %2 (%3/sec) %4")) + info = tr("%1 of %2 (%3/sec) %4") .arg(dataString(m_bytesReceived)) .arg(bytesTotal == 0 ? tr("?") : dataString(bytesTotal)) .arg(dataString((int)speed)) diff --git a/examples/sql/masterdetail/mainwindow.cpp b/examples/sql/masterdetail/mainwindow.cpp index b8c9df6..2ef8ad0 100644 --- a/examples/sql/masterdetail/mainwindow.cpp +++ b/examples/sql/masterdetail/mainwindow.cpp @@ -189,9 +189,9 @@ void MainWindow::deleteAlbum() QMessageBox::StandardButton button; button = QMessageBox::question(this, tr("Delete Album"), - QString(tr("Are you sure you want to " \ - "delete '%1' by '%2'?")) - .arg(title).arg(artist), + tr("Are you sure you want to " + "delete '%1' by '%2'?") + .arg(title, artist), QMessageBox::Yes | QMessageBox::No); if (button == QMessageBox::Yes) { diff --git a/examples/tools/treemodelcompleter/mainwindow.cpp b/examples/tools/treemodelcompleter/mainwindow.cpp index 0448e9d..cfe003a 100644 --- a/examples/tools/treemodelcompleter/mainwindow.cpp +++ b/examples/tools/treemodelcompleter/mainwindow.cpp @@ -241,6 +241,6 @@ void MainWindow::changeCase(int cs) void MainWindow::updateContentsLabel(const QString& sep) { - contentsLabel->setText(QString(tr("Type path from model above with items at each level separated by a '%1'")).arg(sep)); + contentsLabel->setText(tr("Type path from model above with items at each level separated by a '%1'").arg(sep)); } diff --git a/examples/xmlpatterns/filetree/mainwindow.cpp b/examples/xmlpatterns/filetree/mainwindow.cpp index 5b9b0c3..85348f3 100644 --- a/examples/xmlpatterns/filetree/mainwindow.cpp +++ b/examples/xmlpatterns/filetree/mainwindow.cpp @@ -140,7 +140,7 @@ void MainWindow::loadDirectory(const QString &directory) QXmlFormatter formatter(query, &buffer); query.evaluateTo(&formatter); - treeInfo->setText((QString(tr("Model of %1 output as XML.")).arg(directory))); + treeInfo->setText(tr("Model of %1 output as XML.").arg(directory)); fileTree->setText(QString::fromLatin1(output.constData())); evaluateResult(); //! [6] diff --git a/src/3rdparty/phonon/gstreamer/mediaobject.cpp b/src/3rdparty/phonon/gstreamer/mediaobject.cpp index 3e0addc..23a60c0 100644 --- a/src/3rdparty/phonon/gstreamer/mediaobject.cpp +++ b/src/3rdparty/phonon/gstreamer/mediaobject.cpp @@ -219,9 +219,9 @@ void MediaObject::noMorePadsAvailable () if ( status != GST_INSTALL_PLUGINS_STARTED_OK ) { if( status == GST_INSTALL_PLUGINS_HELPER_MISSING ) - setError(QString(tr("Missing codec helper script assistant.")), Phonon::FatalError ); + setError(tr("Missing codec helper script assistant."), Phonon::FatalError ); else - setError(QString(tr("Plugin codec installation failed for codec: %0")) + setError(tr("Plugin codec installation failed for codec: %0") .arg(m_missingCodecs[0].split("|")[3]), error); } m_missingCodecs.clear(); @@ -232,7 +232,7 @@ void MediaObject::noMorePadsAvailable () m_hasVideo = false; emit hasVideoChanged(false); } - setError(QString(tr("A required codec is missing. You need to install the following codec(s) to play this content: %0")).arg(codecs), error); + setError(tr("A required codec is missing. You need to install the following codec(s) to play this content: %0").arg(codecs), error); m_missingCodecs.clear(); #endif } diff --git a/tests/auto/qkeysequence/tst_qkeysequence.cpp b/tests/auto/qkeysequence/tst_qkeysequence.cpp index 1faae6a..60f022f 100644 --- a/tests/auto/qkeysequence/tst_qkeysequence.cpp +++ b/tests/auto/qkeysequence/tst_qkeysequence.cpp @@ -532,20 +532,20 @@ void tst_QKeySequence::translated_data() QTest::addColumn("transKey"); QTest::addColumn("compKey"); - QTest::newRow("Shift++") << QString(tr("Shift++")) << QString("Umschalt++"); - QTest::newRow("Ctrl++") << QString(tr("Ctrl++")) << QString("Strg++"); - QTest::newRow("Alt++") << QString(tr("Alt++")) << QString("Alt++"); - QTest::newRow("Meta++") << QString(tr("Meta++")) << QString("Meta++"); - - QTest::newRow("Shift+,, Shift++") << QString(tr("Shift+,, Shift++")) << QString("Umschalt+,, Umschalt++"); - QTest::newRow("Shift+,, Ctrl++") << QString(tr("Shift+,, Ctrl++")) << QString("Umschalt+,, Strg++"); - QTest::newRow("Shift+,, Alt++") << QString(tr("Shift+,, Alt++")) << QString("Umschalt+,, Alt++"); - QTest::newRow("Shift+,, Meta++") << QString(tr("Shift+,, Meta++")) << QString("Umschalt+,, Meta++"); - - QTest::newRow("Ctrl+,, Shift++") << QString(tr("Ctrl+,, Shift++")) << QString("Strg+,, Umschalt++"); - QTest::newRow("Ctrl+,, Ctrl++") << QString(tr("Ctrl+,, Ctrl++")) << QString("Strg+,, Strg++"); - QTest::newRow("Ctrl+,, Alt++") << QString(tr("Ctrl+,, Alt++")) << QString("Strg+,, Alt++"); - QTest::newRow("Ctrl+,, Meta++") << QString(tr("Ctrl+,, Meta++")) << QString("Strg+,, Meta++"); + QTest::newRow("Shift++") << tr("Shift++") << QString("Umschalt++"); + QTest::newRow("Ctrl++") << tr("Ctrl++") << QString("Strg++"); + QTest::newRow("Alt++") << tr("Alt++") << QString("Alt++"); + QTest::newRow("Meta++") << tr("Meta++") << QString("Meta++"); + + QTest::newRow("Shift+,, Shift++") << tr("Shift+,, Shift++") << QString("Umschalt+,, Umschalt++"); + QTest::newRow("Shift+,, Ctrl++") << tr("Shift+,, Ctrl++") << QString("Umschalt+,, Strg++"); + QTest::newRow("Shift+,, Alt++") << tr("Shift+,, Alt++") << QString("Umschalt+,, Alt++"); + QTest::newRow("Shift+,, Meta++") << tr("Shift+,, Meta++") << QString("Umschalt+,, Meta++"); + + QTest::newRow("Ctrl+,, Shift++") << tr("Ctrl+,, Shift++") << QString("Strg+,, Umschalt++"); + QTest::newRow("Ctrl+,, Ctrl++") << tr("Ctrl+,, Ctrl++") << QString("Strg+,, Strg++"); + QTest::newRow("Ctrl+,, Alt++") << tr("Ctrl+,, Alt++") << QString("Strg+,, Alt++"); + QTest::newRow("Ctrl+,, Meta++") << tr("Ctrl+,, Meta++") << QString("Strg+,, Meta++"); qApp->removeTranslator(ourTranslator); qApp->removeTranslator(qtTranslator); diff --git a/tools/activeqt/testcon/changeproperties.cpp b/tools/activeqt/testcon/changeproperties.cpp index e2ad601..00a2cab 100644 --- a/tools/activeqt/testcon/changeproperties.cpp +++ b/tools/activeqt/testcon/changeproperties.cpp @@ -111,10 +111,10 @@ void ChangeProperties::on_buttonSet_clicked() value = qVariantFromValue(col); } else { QMessageBox::warning(this, tr("Can't parse input"), - QString(tr("Failed to create a color from %1\n" + tr("Failed to create a color from %1\n" "The string has to be a valid color name (e.g. 'red')\n" "or a RGB triple of format '#rrggbb'." - ).arg(editValue->text()))); + ).arg(editValue->text())); } } break; @@ -125,10 +125,10 @@ void ChangeProperties::on_buttonSet_clicked() value = qVariantFromValue(fnt); } else { QMessageBox::warning(this, tr("Can't parse input"), - (tr("Failed to create a font from %1\n" + tr("Failed to create a font from %1\n" "The string has to have a format family, or\n" "family,pointsize,stylehint,weight,italic,underline,strikeout,fixedpitch,rawmode." - ).arg(editValue->text()))); + ).arg(editValue->text())); } } break; diff --git a/tools/qdoc3/main.cpp b/tools/qdoc3/main.cpp index fa7efee..2bfe38e 100644 --- a/tools/qdoc3/main.cpp +++ b/tools/qdoc3/main.cpp @@ -148,7 +148,7 @@ static void printHelp() */ static void printVersion() { - QString s = QString(tr("qdoc version ")) + QString(QT_VERSION_STR); + QString s = tr("qdoc version %1").arg(QT_VERSION_STR); Location::information(s); } diff --git a/tools/shared/qtpropertybrowser/qtpropertymanager.cpp b/tools/shared/qtpropertybrowser/qtpropertymanager.cpp index a0bef0a..8c7835c 100644 --- a/tools/shared/qtpropertybrowser/qtpropertymanager.cpp +++ b/tools/shared/qtpropertybrowser/qtpropertymanager.cpp @@ -2643,8 +2643,8 @@ QString QtPointPropertyManager::valueText(const QtProperty *property) const if (it == d_ptr->m_values.constEnd()) return QString(); const QPoint v = it.value(); - return QString(tr("(%1, %2)").arg(QString::number(v.x())) - .arg(QString::number(v.y()))); + return tr("(%1, %2)").arg(QString::number(v.x())) + .arg(QString::number(v.y())); } /*! @@ -2884,8 +2884,8 @@ QString QtPointFPropertyManager::valueText(const QtProperty *property) const return QString(); const QPointF v = it.value().val; const int dec = it.value().decimals; - return QString(tr("(%1, %2)").arg(QString::number(v.x(), 'f', dec)) - .arg(QString::number(v.y(), 'f', dec))); + return tr("(%1, %2)").arg(QString::number(v.x(), 'f', dec)) + .arg(QString::number(v.y(), 'f', dec)); } /*! @@ -3204,8 +3204,8 @@ QString QtSizePropertyManager::valueText(const QtProperty *property) const if (it == d_ptr->m_values.constEnd()) return QString(); const QSize v = it.value().val; - return QString(tr("%1 x %2").arg(QString::number(v.width())) - .arg(QString::number(v.height()))); + return tr("%1 x %2").arg(QString::number(v.width())) + .arg(QString::number(v.height())); } /*! @@ -3569,8 +3569,8 @@ QString QtSizeFPropertyManager::valueText(const QtProperty *property) const return QString(); const QSizeF v = it.value().val; const int dec = it.value().decimals; - return QString(tr("%1 x %2").arg(QString::number(v.width(), 'f', dec)) - .arg(QString::number(v.height(), 'f', dec))); + return tr("%1 x %2").arg(QString::number(v.width(), 'f', dec)) + .arg(QString::number(v.height(), 'f', dec)); } /*! @@ -3962,10 +3962,10 @@ QString QtRectPropertyManager::valueText(const QtProperty *property) const if (it == d_ptr->m_values.constEnd()) return QString(); const QRect v = it.value().val; - return QString(tr("[(%1, %2), %3 x %4]").arg(QString::number(v.x())) - .arg(QString::number(v.y())) - .arg(QString::number(v.width())) - .arg(QString::number(v.height()))); + return tr("[(%1, %2), %3 x %4]").arg(QString::number(v.x())) + .arg(QString::number(v.y())) + .arg(QString::number(v.width())) + .arg(QString::number(v.height())); } /*! -- cgit v0.12 From 068e9ddcce8adbf64e5a75f25754fd56d01f7eff Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Wed, 1 Sep 2010 18:01:09 +0200 Subject: Build fix on Solaris for an autotest Task-number: QTBUG-12993 Reviewed-by: Trust-Me --- tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index 3634ce9..4476084 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -4578,7 +4578,7 @@ void tst_QGraphicsItem::itemChange() QCOMPARE(tester.changes.at(tester.changes.size() - 1), QGraphicsItem::ItemFlagsHaveChanged); QVariant expectedFlags = qVariantFromValue(QGraphicsItem::GraphicsItemFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemSendsGeometryChanges)); QCOMPARE(tester.values.at(tester.values.size() - 2), expectedFlags); - QCOMPARE(tester.values.at(tester.values.size() - 1), qVariantFromValue(QGraphicsItem::ItemIsSelectable)); + QCOMPARE(tester.values.at(tester.values.size() - 1), qVariantFromValue((quint32)QGraphicsItem::ItemIsSelectable)); } { // ItemSelectedChange -- cgit v0.12 From e48e0e7cb0fe51cc676b894cdce9eebeca7d5991 Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Wed, 28 Jul 2010 15:13:34 +0200 Subject: put iterator variables into loop headers Reviewed-by: joerg --- bin/syncqt | 57 +++++++++++++++++++-------------------------------------- 1 file changed, 19 insertions(+), 38 deletions(-) diff --git a/bin/syncqt b/bin/syncqt index 4acb5b5..c9f2223 100755 --- a/bin/syncqt +++ b/bin/syncqt @@ -297,8 +297,7 @@ sub classNames { push @symbols, "QMutable" . $1 . "Iterator"; } - foreach (@symbols) { - my $symbol = $_; + foreach my $symbol (@symbols) { $symbol = (join("::", @namespaces) . "::" . $symbol) if (scalar @namespaces); push @ret, $symbol if ($symbol =~ /^Q[^:]*$/ # no-namespace, starting with Q @@ -696,9 +695,8 @@ my %inject_headers; # find the header by normal means. %inject_headers = ( "$basedir/src/corelib/global" => ( "*qconfig.h" ) ) unless (-e "$basedir/src/corelib/global/qconfig.h"); -foreach (@modules_to_sync) { +foreach my $lib (@modules_to_sync) { #iteration info - my $lib = $_; my $dir = "$modules{$lib}"; my $pathtoheaders = ""; $pathtoheaders = "$moduleheaders{$lib}" if ($moduleheaders{$lib}); @@ -715,8 +713,7 @@ foreach (@modules_to_sync) { #get dependencies if(-e "$dir/" . basename($dir) . ".pro") { if(open(F, "<$dir/" . basename($dir) . ".pro")) { - while() { - my $line = $_; + while(my $line = ) { chomp $line; if($line =~ /^ *QT *\+?= *([^\r\n]*)/) { foreach(split(/ /, "$1")) { @@ -743,8 +740,7 @@ foreach (@modules_to_sync) { #remove the old files if($remove_stale) { my @subdirs = ("$out_basedir/include/$lib"); - foreach (@subdirs) { - my $subdir = "$_"; + foreach my $subdir (@subdirs) { if (opendir DIR, "$subdir") { while(my $t = readdir(DIR)) { my $file = "$subdir/$t"; @@ -753,12 +749,10 @@ foreach (@modules_to_sync) { } else { my @files = ("$file"); #push @files, "$out_basedir/include/Qt/$t" if(-e "$out_basedir/include/Qt/$t"); - foreach (@files) { - my $file = $_; + foreach my $file (@files) { my $remove_file = 0; if(open(F, "<$file")) { - while() { - my $line = $_; + while(my $line = ) { chomp $line; if($line =~ /^\#include \"([^\"]*)\"$/) { my $include = $1; @@ -782,14 +776,12 @@ foreach (@modules_to_sync) { } #create the new ones - foreach (split(/;/, $dir)) { - my $current_dir = "$_"; + foreach my $current_dir (split(/;/, $dir)) { my $headers_dir = $current_dir; $headers_dir .= "/$pathtoheaders" if ($pathtoheaders); #calc subdirs my @subdirs = ($headers_dir); - foreach (@subdirs) { - my $subdir = "$_"; + foreach my $subdir (@subdirs) { opendir DIR, "$subdir" or next; while(my $t = readdir(DIR)) { push @subdirs, "$subdir/$t" if(-d "$subdir/$t" && !($t eq ".") && @@ -801,12 +793,10 @@ foreach (@modules_to_sync) { } #calc files and "copy" them - foreach (@subdirs) { - my $subdir = "$_"; + foreach my $subdir (@subdirs) { my @headers = findFiles("$subdir", "^[-a-z0-9_]*\\.h\$" , 0); push @headers, $inject_headers{$subdir} if (defined $inject_headers{$subdir}); - foreach (@headers) { - my $header = "$_"; + foreach my $header (@headers) { my $shadow = ($header =~ s/^\*//); $header = 0 if("$header" =~ /^ui_.*.h/); foreach (@ignore_headers) { @@ -862,15 +852,15 @@ foreach (@modules_to_sync) { close HEADERFILE; } - foreach(@classes) { + foreach my $full_class (@classes) { my $header_base = basename($header); - my $class = $_; # Strip namespaces: + my $class = $full_class; $class =~ s/^.*:://; # if ($class =~ m/::/) { # class =~ s,::,/,g; # } - $class_lib_map_contents .= "QT_CLASS_LIB($_, $lib, $header_base)\n"; + $class_lib_map_contents .= "QT_CLASS_LIB($full_class, $lib, $header_base)\n"; $header_copies++ if(syncHeader("$out_basedir/include/$lib/$class", "$out_basedir/include/$lib/$header", 0)); # KDE-Compat headers for Phonon @@ -892,8 +882,7 @@ foreach (@modules_to_sync) { #deal with the install directives if($public_header) { my $pri_install_iheader = fixPaths($iheader, $current_dir); - foreach(@classes) { - my $class = $_; + foreach my $class (@classes) { # Strip namespaces: $class =~ s/^.*:://; # if ($class =~ m/::/) { @@ -994,14 +983,10 @@ unless($showonly || !$create_uic_class_map) { } if($check_includes) { - for (keys(%modules)) { - #iteration info - my $lib = $_; - { + for my $lib (keys(%modules)) { #calc subdirs my @subdirs = ($modules{$lib}); - foreach (@subdirs) { - my $subdir = "$_"; + foreach my $subdir (@subdirs) { opendir DIR, "$subdir" or die "Huh, directory ".$subdir." cannot be opened."; while(my $t = readdir(DIR)) { push @subdirs, "$subdir/$t" if(-d "$subdir/$t" && !($t eq ".") && @@ -1012,8 +997,7 @@ if($check_includes) { closedir DIR; } - foreach (@subdirs) { - my $subdir = "$_"; + foreach my $subdir (@subdirs) { my $header_skip_qt_module_test = 0; foreach(@ignore_for_qt_module_check) { foreach (split(/;/, $_)) { @@ -1021,8 +1005,7 @@ if($check_includes) { } } my @headers = findFiles("$subdir", "^[-a-z0-9_]*\\.h\$" , 0); - foreach (@headers) { - my $header = "$_"; + foreach my $header (@headers) { my $header_skip_qt_begin_header_test = 0; my $header_skip_qt_begin_namespace_test = 0; $header = 0 if("$header" =~ /^ui_.*.h/); @@ -1074,8 +1057,7 @@ if($check_includes) { $include = 0; } if($include) { - for (keys(%modules)) { - my $trylib = $_; + for my $trylib (keys(%modules)) { if(-e "$out_basedir/include/$trylib/$include") { print "WARNING: $iheader includes $include when it should include $trylib/$include\n"; } @@ -1124,7 +1106,6 @@ if($check_includes) { } } } - } } } -- cgit v0.12 From 8aa5b8cf04baa11891918ebb57ff0d2d7ada7f78 Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Wed, 28 Jul 2010 15:26:40 +0200 Subject: remove overquoting in perl, "$foo" is basically just slower and less legible than $foo. Reviewed-by: joerg --- bin/syncqt | 160 ++++++++++++++++++++++++++++++------------------------------- 1 file changed, 80 insertions(+), 80 deletions(-) diff --git a/bin/syncqt b/bin/syncqt index c9f2223..60ecf3a 100755 --- a/bin/syncqt +++ b/bin/syncqt @@ -213,7 +213,7 @@ sub classNames { } } return @ret if($line =~ m/^#pragma qt_sync_stop_processing/); - push(@ret, "$1") if($line =~ m/^#pragma qt_class\(([^)]*)\)[\r\n]*$/); + push(@ret, $1) if($line =~ m/^#pragma qt_class\(([^)]*)\)[\r\n]*$/); $line = 0; } if($line) { @@ -323,7 +323,7 @@ sub syncHeader { $header =~ s=\\=/=g; return copyFile($iheader, $header) if($copy); - unless(-e "$header") { + unless(-e $header) { my $header_dir = dirname($header); mkpath $header_dir, !$quiet; @@ -367,7 +367,7 @@ sub fixPaths { $dir =~ s=\\=/=g; } $dir =~ s,/cygdrive/([a-zA-Z])/,$1:/,g; - return basename($file) if("$file_dir" eq "$dir"); + return basename($file) if($file_dir eq $dir); #guts my $match_dir = 0; @@ -429,7 +429,7 @@ sub fileCompare { my $file2contents = fileContents($file2); if (! -e $file1) { return 1; } if (! -e $file2) { return -1; } - return $file1contents ne $file2contents ? (stat("$file2"))[9] <=> (stat("$file1"))[9] : 0; + return $file1contents ne $file2contents ? (stat($file2))[9] <=> (stat($file1))[9] : 0; } ###################################################################### @@ -466,7 +466,7 @@ sub copyFile if ( $knowdiff || ($filecontents ne $ifilecontents) ) { if ( $copy > 0 ) { my $file_dir = dirname($file); - mkpath $file_dir, !$quiet unless(-e "$file_dir"); + mkpath $file_dir, !$quiet unless(-e $file_dir); open(O, "> " . $file) || die "Could not open $file for writing (no write permission?)"; local $/; binmode O; @@ -475,7 +475,7 @@ sub copyFile return 1; } elsif ( $copy < 0 ) { my $ifile_dir = dirname($ifile); - mkpath $ifile_dir, !$quiet unless(-e "$ifile_dir"); + mkpath $ifile_dir, !$quiet unless(-e $ifile_dir); open(O, "> " . $ifile) || die "Could not open $ifile for writing (no write permission?)"; local $/; binmode O; @@ -566,102 +566,102 @@ while ( @ARGV ) { #parse my $arg = shift @ARGV; - if ("$arg" eq "-h" || "$arg" eq "-help" || "$arg" eq "?") { + if ($arg eq "-h" || $arg eq "-help" || $arg eq "?") { $var = "show_help"; $val = "yes"; - } elsif("$arg" eq "-copy") { + } elsif($arg eq "-copy") { $var = "copy"; $val = "yes"; - } elsif("$arg" eq "-o" || "$arg" eq "-outdir") { + } elsif($arg eq "-o" || $arg eq "-outdir") { $var = "output"; $val = shift @ARGV; - } elsif("$arg" eq "-showonly" || "$arg" eq "-remove-stale" || "$arg" eq "-windows" || - "$arg" eq "-relative" || "$arg" eq "-check-includes") { + } elsif($arg eq "-showonly" || $arg eq "-remove-stale" || $arg eq "-windows" || + $arg eq "-relative" || $arg eq "-check-includes") { $var = substr($arg, 1); $val = "yes"; - } elsif("$arg" =~ /^-no-(.*)$/) { + } elsif($arg =~ /^-no-(.*)$/) { $var = $1; $val = "no"; #these are for commandline compat - } elsif("$arg" eq "-inc") { + } elsif($arg eq "-inc") { $var = "output"; $val = shift @ARGV; - } elsif("$arg" eq "-module") { + } elsif($arg eq "-module") { $var = "module"; $val = shift @ARGV; - } elsif("$arg" eq "-separate-module") { + } elsif($arg eq "-separate-module") { $var = "separate-module"; $val = shift @ARGV; - } elsif("$arg" eq "-show") { + } elsif($arg eq "-show") { $var = "showonly"; $val = "yes"; - } elsif("$arg" eq "-quiet") { + } elsif($arg eq "-quiet") { $var = "quiet"; $val = "yes"; - } elsif("$arg" eq "-base-dir") { + } elsif($arg eq "-base-dir") { # skip, it's been dealt with at the top of the file shift @ARGV; next; } #do something - if(!$var || "$var" eq "show_help") { + if(!$var || $var eq "show_help") { print "Unknown option: $arg\n\n" if(!$var); showUsage(); - } elsif ("$var" eq "copy") { - if("$val" eq "yes") { + } elsif ($var eq "copy") { + if($val eq "yes") { $copy_headers++; } elsif($showonly) { $copy_headers--; } - } elsif ("$var" eq "showonly") { - if("$val" eq "yes") { + } elsif ($var eq "showonly") { + if($val eq "yes") { $showonly++; } elsif($showonly) { $showonly--; } - } elsif ("$var" eq "quiet") { - if("$val" eq "yes") { + } elsif ($var eq "quiet") { + if($val eq "yes") { $quiet++; } elsif($quiet) { $quiet--; } - } elsif ("$var" eq "check-includes") { - if("$val" eq "yes") { + } elsif ($var eq "check-includes") { + if($val eq "yes") { $check_includes++; } elsif($check_includes) { $check_includes--; } - } elsif ("$var" eq "remove-stale") { - if("$val" eq "yes") { + } elsif ($var eq "remove-stale") { + if($val eq "yes") { $remove_stale++; } elsif($remove_stale) { $remove_stale--; } - } elsif ("$var" eq "windows") { - if("$val" eq "yes") { + } elsif ($var eq "windows") { + if($val eq "yes") { $force_win++; } elsif($force_win) { $force_win--; } - } elsif ("$var" eq "relative") { - if("$val" eq "yes") { + } elsif ($var eq "relative") { + if($val eq "yes") { $force_relative++; } elsif($force_relative) { $force_relative--; } - } elsif ("$var" eq "module") { + } elsif ($var eq "module") { print "module :$val:\n" unless $quiet; die "No such module: $val" unless(defined $modules{$val}); push @modules_to_sync, $val; - } elsif ("$var" eq "separate-module") { + } elsif ($var eq "separate-module") { my ($module, $prodir, $headerdir) = split(/:/, $val); $modules{$module} = $prodir; push @modules_to_sync, $module; $moduleheaders{$module} = $headerdir; $create_uic_class_map = 0; $create_private_headers = 0; - } elsif ("$var" eq "output") { + } elsif ($var eq "output") { my $outdir = $val; if(checkRelative($outdir)) { $out_basedir = getcwd(); @@ -697,9 +697,9 @@ my %inject_headers; foreach my $lib (@modules_to_sync) { #iteration info - my $dir = "$modules{$lib}"; + my $dir = $modules{$lib}; my $pathtoheaders = ""; - $pathtoheaders = "$moduleheaders{$lib}" if ($moduleheaders{$lib}); + $pathtoheaders = $moduleheaders{$lib} if ($moduleheaders{$lib}); #information used after the syncing my $pri_install_classes = ""; @@ -716,20 +716,20 @@ foreach my $lib (@modules_to_sync) { while(my $line = ) { chomp $line; if($line =~ /^ *QT *\+?= *([^\r\n]*)/) { - foreach(split(/ /, "$1")) { - $master_contents .= "#include \n" if("$_" eq "core"); - $master_contents .= "#include \n" if("$_" eq "gui"); - $master_contents .= "#include \n" if("$_" eq "network"); - $master_contents .= "#include \n" if("$_" eq "svg"); - $master_contents .= "#include \n" if("$_" eq "declarative"); - $master_contents .= "#include \n" if("$_" eq "script"); - $master_contents .= "#include \n" if("$_" eq "scripttools"); - $master_contents .= "#include \n" if("$_" eq "qt3support"); - $master_contents .= "#include \n" if("$_" eq "sql"); - $master_contents .= "#include \n" if("$_" eq "xml"); - $master_contents .= "#include \n" if("$_" eq "xmlpatterns"); - $master_contents .= "#include \n" if("$_" eq "opengl"); - $master_contents .= "#include \n" if("$_" eq "openvg"); + foreach(split(/ /, $1)) { + $master_contents .= "#include \n" if($_ eq "core"); + $master_contents .= "#include \n" if($_ eq "gui"); + $master_contents .= "#include \n" if($_ eq "network"); + $master_contents .= "#include \n" if($_ eq "svg"); + $master_contents .= "#include \n" if($_ eq "declarative"); + $master_contents .= "#include \n" if($_ eq "script"); + $master_contents .= "#include \n" if($_ eq "scripttools"); + $master_contents .= "#include \n" if($_ eq "qt3support"); + $master_contents .= "#include \n" if($_ eq "sql"); + $master_contents .= "#include \n" if($_ eq "xml"); + $master_contents .= "#include \n" if($_ eq "xmlpatterns"); + $master_contents .= "#include \n" if($_ eq "opengl"); + $master_contents .= "#include \n" if($_ eq "openvg"); } } } @@ -741,13 +741,13 @@ foreach my $lib (@modules_to_sync) { if($remove_stale) { my @subdirs = ("$out_basedir/include/$lib"); foreach my $subdir (@subdirs) { - if (opendir DIR, "$subdir") { + if (opendir DIR, $subdir) { while(my $t = readdir(DIR)) { my $file = "$subdir/$t"; - if(-d "$file") { - push @subdirs, "$file" unless($t eq "." || $t eq ".."); + if(-d $file) { + push @subdirs, $file unless($t eq "." || $t eq ".."); } else { - my @files = ("$file"); + my @files = ($file); #push @files, "$out_basedir/include/Qt/$t" if(-e "$out_basedir/include/Qt/$t"); foreach my $file (@files) { my $remove_file = 0; @@ -757,14 +757,14 @@ foreach my $lib (@modules_to_sync) { if($line =~ /^\#include \"([^\"]*)\"$/) { my $include = $1; $include = $subdir . "/" . $include unless(substr($include, 0, 1) eq "/"); - $remove_file = 1 unless(-e "$include"); + $remove_file = 1 unless(-e $include); } else { $remove_file = 0; last; } } close(F); - unlink "$file" if($remove_file); + unlink $file if($remove_file); } } } @@ -782,7 +782,7 @@ foreach my $lib (@modules_to_sync) { #calc subdirs my @subdirs = ($headers_dir); foreach my $subdir (@subdirs) { - opendir DIR, "$subdir" or next; + opendir DIR, $subdir or next; while(my $t = readdir(DIR)) { push @subdirs, "$subdir/$t" if(-d "$subdir/$t" && !($t eq ".") && !($t eq "..") && !($t eq ".obj") && @@ -794,13 +794,13 @@ foreach my $lib (@modules_to_sync) { #calc files and "copy" them foreach my $subdir (@subdirs) { - my @headers = findFiles("$subdir", "^[-a-z0-9_]*\\.h\$" , 0); + my @headers = findFiles($subdir, "^[-a-z0-9_]*\\.h\$" , 0); push @headers, $inject_headers{$subdir} if (defined $inject_headers{$subdir}); foreach my $header (@headers) { my $shadow = ($header =~ s/^\*//); - $header = 0 if("$header" =~ /^ui_.*.h/); + $header = 0 if($header =~ /^ui_.*.h/); foreach (@ignore_headers) { - $header = 0 if("$header" eq "$_"); + $header = 0 if($header eq $_); } if($header) { my $header_copies = 0; @@ -810,7 +810,7 @@ foreach my $lib (@modules_to_sync) { $public_header = 0; } else { foreach (@ignore_for_master_contents) { - $public_header = 0 if("$header" eq "$_"); + $public_header = 0 if($header eq $_); } } @@ -829,7 +829,7 @@ foreach my $lib (@modules_to_sync) { @headers = ( "$out_basedir/include/$lib/$header" ); # write forwarding headers to include/Qt - if ("$lib" ne "phonon" && "$subdir" =~ /^$basedir\/src/) { + if ($lib ne "phonon" && $subdir =~ /^$basedir\/src/) { my $file_name = "$out_basedir/include/Qt/$header"; my $file_op = '>'; my $header_content = ''; @@ -917,8 +917,8 @@ foreach my $lib (@modules_to_sync) { foreach my $master_include (@master_includes) { #generate the "master" include file my @tmp = split(/;/,$modules{$lib}); - $pri_install_files .= fixPaths($master_include, "$tmp[0]") . " "; #get the master file installed too - if($master_include && -e "$master_include") { + $pri_install_files .= fixPaths($master_include, $tmp[0]) . " "; #get the master file installed too + if($master_include && -e $master_include) { open MASTERINCLUDE, "<$master_include"; local $/; binmode MASTERINCLUDE; @@ -932,7 +932,7 @@ foreach my $lib (@modules_to_sync) { mkpath $master_dir, !$quiet; print "header (master) created for $lib\n" unless $quiet; open MASTERINCLUDE, ">$master_include"; - print MASTERINCLUDE "$master_contents"; + print MASTERINCLUDE $master_contents; close MASTERINCLUDE; } } @@ -943,7 +943,7 @@ foreach my $lib (@modules_to_sync) { $headers_pri_contents .= "SYNCQT.HEADER_CLASSES = $pri_install_classes\n"; $headers_pri_contents .= "SYNCQT.PRIVATE_HEADER_FILES = $pri_install_pfiles\n"; my $headers_pri_file = "$out_basedir/include/$lib/headers.pri"; - if(-e "$headers_pri_file") { + if(-e $headers_pri_file) { open HEADERS_PRI_FILE, "<$headers_pri_file"; local $/; binmode HEADERS_PRI_FILE; @@ -957,14 +957,14 @@ foreach my $lib (@modules_to_sync) { mkpath $headers_pri_dir, !$quiet; print "headers.pri file created for $lib\n" unless $quiet; open HEADERS_PRI_FILE, ">$headers_pri_file"; - print HEADERS_PRI_FILE "$headers_pri_contents"; + print HEADERS_PRI_FILE $headers_pri_contents; close HEADERS_PRI_FILE; } } } unless($showonly || !$create_uic_class_map) { my $class_lib_map = "$out_basedir/src/tools/uic/qclass_lib_map.h"; - if(-e "$class_lib_map") { + if(-e $class_lib_map) { open CLASS_LIB_MAP, "<$class_lib_map"; local $/; binmode CLASS_LIB_MAP; @@ -977,7 +977,7 @@ unless($showonly || !$create_uic_class_map) { my $class_lib_map_dir = dirname($class_lib_map); mkpath $class_lib_map_dir, !$quiet; open CLASS_LIB_MAP, ">$class_lib_map"; - print CLASS_LIB_MAP "$class_lib_map_contents"; + print CLASS_LIB_MAP $class_lib_map_contents; close CLASS_LIB_MAP; } } @@ -987,7 +987,7 @@ if($check_includes) { #calc subdirs my @subdirs = ($modules{$lib}); foreach my $subdir (@subdirs) { - opendir DIR, "$subdir" or die "Huh, directory ".$subdir." cannot be opened."; + opendir DIR, $subdir or die "Huh, directory ".$subdir." cannot be opened."; while(my $t = readdir(DIR)) { push @subdirs, "$subdir/$t" if(-d "$subdir/$t" && !($t eq ".") && !($t eq "..") && !($t eq ".obj") && @@ -1001,16 +1001,16 @@ if($check_includes) { my $header_skip_qt_module_test = 0; foreach(@ignore_for_qt_module_check) { foreach (split(/;/, $_)) { - $header_skip_qt_module_test = 1 if ("$subdir" =~ /^$_/); + $header_skip_qt_module_test = 1 if ($subdir =~ /^$_/); } } - my @headers = findFiles("$subdir", "^[-a-z0-9_]*\\.h\$" , 0); + my @headers = findFiles($subdir, "^[-a-z0-9_]*\\.h\$" , 0); foreach my $header (@headers) { my $header_skip_qt_begin_header_test = 0; my $header_skip_qt_begin_namespace_test = 0; - $header = 0 if("$header" =~ /^ui_.*.h/); + $header = 0 if($header =~ /^ui_.*.h/); foreach (@ignore_headers) { - $header = 0 if("$header" eq "$_"); + $header = 0 if($header eq $_); } if($header) { my $public_header = $header; @@ -1018,17 +1018,17 @@ if($check_includes) { $public_header = 0; } else { foreach (@ignore_for_master_contents) { - $public_header = 0 if("$header" eq "$_"); + $public_header = 0 if($header eq $_); } if($public_header) { foreach (@ignore_for_include_check) { - $public_header = 0 if("$header" eq "$_"); + $public_header = 0 if($header eq $_); } foreach(@ignore_for_qt_begin_header_check) { - $header_skip_qt_begin_header_test = 1 if ("$header" eq "$_"); + $header_skip_qt_begin_header_test = 1 if ($header eq $_); } foreach(@ignore_for_qt_begin_namespace_check) { - $header_skip_qt_begin_namespace_test = 1 if ("$header" eq "$_"); + $header_skip_qt_begin_namespace_test = 1 if ($header eq $_); } } } -- cgit v0.12 From b2643a207a23599dbf1aec37cd2b6f8adae1e2dd Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Wed, 1 Sep 2010 19:51:37 +0200 Subject: make syncqt propagate timestamps as well this should reduce the number of unnecessary rebuilds of qt-using code even after re-building qt from scratch - provided the timestamp of qconfig.h is preserved externally. Task-number: QTBUG-12731 --- bin/syncqt | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/bin/syncqt b/bin/syncqt index 60ecf3a..907869d 100755 --- a/bin/syncqt +++ b/bin/syncqt @@ -309,16 +309,17 @@ sub classNames { } ###################################################################### -# Syntax: syncHeader(header, iheader, copy) +# Syntax: syncHeader(header, iheader, copy, timestamp) # Params: header, string, filename to create "symlink" for # iheader, string, destination name of symlink # copy, forces header to be a copy of iheader +# timestamp, the requested modification time if copying # # Purpose: Syncronizes header to iheader # Returns: 1 if successful, else 0. ###################################################################### sub syncHeader { - my ($header, $iheader, $copy) = @_; + my ($header, $iheader, $copy, $ts) = @_; $iheader =~ s=\\=/=g; $header =~ s=\\=/=g; return copyFile($iheader, $header) if($copy); @@ -332,6 +333,7 @@ sub syncHeader { open HEADER, ">$header" || die "Could not open $header for writing!\n"; print HEADER "#include \"$iheader_out\"\n"; close HEADER; + utime(time, $ts, $header) or die "$iheader, $header"; return 1; } return 0; @@ -472,6 +474,7 @@ sub copyFile binmode O; print O $ifilecontents; close O; + utime time, (stat($ifile))[9], $file; return 1; } elsif ( $copy < 0 ) { my $ifile_dir = dirname($ifile); @@ -481,6 +484,7 @@ sub copyFile binmode O; print O $filecontents; close O; + utime time, (stat($file))[9], $ifile; return 1; } } @@ -823,6 +827,7 @@ foreach my $lib (@modules_to_sync) { print "SYMBOL: $_\n"; } } else { + my $ts = (stat($iheader))[9]; #find out all the places it goes.. my @headers; if ($public_header) { @@ -861,18 +866,18 @@ foreach my $lib (@modules_to_sync) { # class =~ s,::,/,g; # } $class_lib_map_contents .= "QT_CLASS_LIB($full_class, $lib, $header_base)\n"; - $header_copies++ if(syncHeader("$out_basedir/include/$lib/$class", "$out_basedir/include/$lib/$header", 0)); + $header_copies++ if(syncHeader("$out_basedir/include/$lib/$class", "$out_basedir/include/$lib/$header", 0, $ts)); # KDE-Compat headers for Phonon if ($lib eq "phonon") { - $header_copies++ if (syncHeader("$out_basedir/include/phonon_compat/Phonon/$class", "$out_basedir/include/$lib/$header", 0)); + $header_copies++ if (syncHeader("$out_basedir/include/phonon_compat/Phonon/$class", "$out_basedir/include/$lib/$header", 0, $ts)); } } } elsif ($create_private_headers) { @headers = ( "$out_basedir/include/$lib/private/$header" ); } foreach(@headers) { #sync them - $header_copies++ if(syncHeader($_, $iheader, $copy_headers)); + $header_copies++ if(syncHeader($_, $iheader, $copy_headers, $ts)); } if($public_header) { -- cgit v0.12 From 661e237be622a5f7886cee7c06f9daa73d4a07d7 Mon Sep 17 00:00:00 2001 From: Alan Alpert Date: Thu, 2 Sep 2010 10:58:32 +1000 Subject: Remove extra strings --- demos/qtdemo/menumanager.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/demos/qtdemo/menumanager.cpp b/demos/qtdemo/menumanager.cpp index 4ae9ca1..fe3c5aa 100644 --- a/demos/qtdemo/menumanager.cpp +++ b/demos/qtdemo/menumanager.cpp @@ -384,9 +384,7 @@ void MenuManager::launchQmlExample(const QString &name) qmlRoot->setProperty("show", QVariant(true)); qmlRoot->setProperty("qmlFile", QUrl::fromLocalFile(file.fileName())); #else - QMessageBox::critical(0, tr("Failed to launch the example"), - tr("This application was built without the QtDeclarative module, and therefore declarative examples have been disabled."), - QMessageBox::Cancel); + exampleError(QProcess::UnknownError); #endif } -- cgit v0.12 From 23393f9650624bcc82942ee69161b6b916fa801e Mon Sep 17 00:00:00 2001 From: Aaron McCarthy Date: Thu, 2 Sep 2010 13:42:39 +1000 Subject: Revert "Restore default if to system default on session close." This reverts commit bce4c42a3d0c7d24009230e09aa58db60db39d40. This change did not have the desired effect on Symbian versions prior to Symbian^3. Conflicts: src/plugins/bearer/symbian/qnetworksession_impl.cpp --- .../bearer/symbian/qnetworksession_impl.cpp | 42 ++++++++-------------- src/plugins/bearer/symbian/qnetworksession_impl.h | 1 - 2 files changed, 14 insertions(+), 29 deletions(-) diff --git a/src/plugins/bearer/symbian/qnetworksession_impl.cpp b/src/plugins/bearer/symbian/qnetworksession_impl.cpp index 19f13c2..2091898 100644 --- a/src/plugins/bearer/symbian/qnetworksession_impl.cpp +++ b/src/plugins/bearer/symbian/qnetworksession_impl.cpp @@ -111,13 +111,15 @@ QNetworkSessionPrivateImpl::~QNetworkSessionPrivateImpl() Cancel(); iSocketServ.Close(); - // Restore default interface to system default - restoreDefaultIf(); + // Close global 'Open C' RConnection + // Clears also possible unsetdefaultif() flags. + setdefaultif(0); iConnectionMonitor.Close(); iOpenCLibrary.Close(); #ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - destroyed (and restoreDefaultIf())"; + qDebug() << "QNS this : " << QString::number((uint)this) + << " - destroyed (and setdefaultif(0))"; #endif } @@ -533,8 +535,15 @@ void QNetworkSessionPrivateImpl::close(bool allowSignals) Cancel(); // closes iConnection iSocketServ.Close(); - // Restore default interface to system default - restoreDefaultIf(); + // Close global 'Open C' RConnection. If OpenC supports, + // close the defaultif for good to avoid difficult timing + // and bouncing issues of network going immediately back up + // because of e.g. select() thread etc. + if (iDynamicUnSetdefaultif) { + iDynamicUnSetdefaultif(); + } else { + setdefaultif(0); + } // If UserChoice, go down immediately. If some other configuration, // go down immediately if there is no reports expected from the platform; @@ -1459,29 +1468,6 @@ void QNetworkSessionPrivateImpl::handleSymbianConnectionStatusChange(TInt aConne } } -void QNetworkSessionPrivateImpl::restoreDefaultIf() -{ - QNetworkConfigurationPrivatePointer config = engine->defaultConfiguration(); - - QMutexLocker locker(&config->mutex); - - ifreq ifr; - memset(&ifr, 0, sizeof(ifreq)); - - switch (config->type) { - case QNetworkConfiguration::InternetAccessPoint: - strcpy(ifr.ifr_name, config->name.toUtf8().constData()); - break; - case QNetworkConfiguration::ServiceNetwork: - ifr.ifr_ifru.snap_id = toSymbianConfig(config)->numericId; - break; - default: - ; - }; - - setdefaultif(&ifr); -} - #if defined(SNAP_FUNCTIONALITY_AVAILABLE) bool QNetworkSessionPrivateImpl::easyWlanTrueIapId(TUint32 &trueIapId) const { diff --git a/src/plugins/bearer/symbian/qnetworksession_impl.h b/src/plugins/bearer/symbian/qnetworksession_impl.h index 51f2e70..8e3e997 100644 --- a/src/plugins/bearer/symbian/qnetworksession_impl.h +++ b/src/plugins/bearer/symbian/qnetworksession_impl.h @@ -141,7 +141,6 @@ private: void handleSymbianConnectionStatusChange(TInt aConnectionStatus, TInt aError, TUint accessPointId = 0); QNetworkConfiguration bestConfigFromSNAP(const QNetworkConfiguration& snapConfig) const; QNetworkConfiguration activeConfiguration(TUint32 iapId = 0) const; - void restoreDefaultIf(); #ifndef QT_NO_NETWORKINTERFACE QNetworkInterface interface(TUint iapId) const; #endif -- cgit v0.12 From 72a1709cbe216220722750c743641bf5ba8a8da9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Thu, 2 Sep 2010 08:11:18 +0200 Subject: Minor performance improvement to QGraphicsItem::update. Reported by other teams in Nokia. Avoid calling discardUpdateRequest() twice, first in update() and then in markDirty(). No-brainer. Task-number: QTBUG-10817 Reviewed-by: Trustme --- src/gui/graphicsview/qgraphicsitem.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 7a622f1..fc122d2 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -5666,9 +5666,6 @@ void QGraphicsItem::update(const QRectF &rect) return; } - if (d_ptr->discardUpdateRequest()) - return; - if (d_ptr->scene) d_ptr->scene->d_func()->markDirty(this, rect); } -- cgit v0.12 From b6d47ea4872e188d8da6886cb1922f1a89245825 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Thu, 2 Sep 2010 17:27:57 +1000 Subject: Don't overflow the unreferenced cost counter QTBUG-13345 --- src/declarative/util/qdeclarativepixmapcache.cpp | 16 +++++++------ .../tst_qdeclarativepixmapcache.cpp | 27 ++++++++++++++++++++++ 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/src/declarative/util/qdeclarativepixmapcache.cpp b/src/declarative/util/qdeclarativepixmapcache.cpp index de2de21..4fc52f5 100644 --- a/src/declarative/util/qdeclarativepixmapcache.cpp +++ b/src/declarative/util/qdeclarativepixmapcache.cpp @@ -155,7 +155,7 @@ protected: private: friend class QDeclarativePixmapReaderThreadObject; void processJobs(); - void processJob(QDeclarativePixmapReply *); + void processJob(QDeclarativePixmapReply *, const QUrl &, const QSize &); void networkRequestDone(QNetworkReply *); QList jobs; @@ -434,23 +434,24 @@ void QDeclarativePixmapReader::processJobs() QDeclarativePixmapReply *runningJob = jobs.takeLast(); runningJob->loading = true; + QUrl url = runningJob->data->url; + QSize requestSize = runningJob->data->requestSize; locker.unlock(); - processJob(runningJob); + processJob(runningJob, url, requestSize); locker.relock(); } } } -void QDeclarativePixmapReader::processJob(QDeclarativePixmapReply *runningJob) +void QDeclarativePixmapReader::processJob(QDeclarativePixmapReply *runningJob, const QUrl &url, + const QSize &requestSize) { - QUrl url = runningJob->data->url; - // fetch if (url.scheme() == QLatin1String("image")) { // Use QmlImageProvider QSize readSize; QDeclarativeEnginePrivate *ep = QDeclarativeEnginePrivate::get(engine); - QImage image = ep->getImageFromProvider(url, &readSize, runningJob->data->requestSize); + QImage image = ep->getImageFromProvider(url, &readSize, requestSize); QDeclarativePixmapReply::ReadError errorCode = QDeclarativePixmapReply::NoError; QString errorStr; @@ -472,7 +473,7 @@ void QDeclarativePixmapReader::processJob(QDeclarativePixmapReply *runningJob) QFile f(lf); QSize readSize; if (f.open(QIODevice::ReadOnly)) { - if (!readImage(url, &f, &image, &errorStr, &readSize, runningJob->data->requestSize)) + if (!readImage(url, &f, &image, &errorStr, &readSize, requestSize)) errorCode = QDeclarativePixmapReply::Loading; } else { errorStr = QDeclarativePixmap::tr("Cannot open: %1").arg(url.toString()); @@ -663,6 +664,7 @@ void QDeclarativePixmapStore::shrinkCache(int remove) data->prevUnreferenced = 0; remove -= data->cost(); + m_unreferencedCost -= data->cost(); data->removeFromCache(); delete data; } diff --git a/tests/auto/declarative/qdeclarativepixmapcache/tst_qdeclarativepixmapcache.cpp b/tests/auto/declarative/qdeclarativepixmapcache/tst_qdeclarativepixmapcache.cpp index 6b36224..b20d8ec 100644 --- a/tests/auto/declarative/qdeclarativepixmapcache/tst_qdeclarativepixmapcache.cpp +++ b/tests/auto/declarative/qdeclarativepixmapcache/tst_qdeclarativepixmapcache.cpp @@ -42,6 +42,7 @@ #include #include #include +#include #include #include "testhttpserver.h" #include "../../../shared/util.h" @@ -72,6 +73,7 @@ private slots: void parallel_data(); void massive(); void cancelcrash(); + void shrinkcache(); private: QDeclarativeEngine engine; @@ -326,6 +328,31 @@ void tst_qdeclarativepixmapcache::cancelcrash() } } +class MyPixmapProvider : public QDeclarativeImageProvider +{ +public: + MyPixmapProvider() + : QDeclarativeImageProvider(Pixmap) {} + + virtual QPixmap requestPixmap(const QString &d, QSize *, const QSize &) { + QPixmap pix(800, 600); + pix.fill(Qt::red); + return pix; + } +}; + +// QTBUG-13345 +void tst_qdeclarativepixmapcache::shrinkcache() +{ + QDeclarativeEngine engine; + engine.addImageProvider(QLatin1String("mypixmaps"), new MyPixmapProvider); + + for (int ii = 0; ii < 4000; ++ii) { + QUrl url("image://mypixmaps/" + QString::number(ii)); + QDeclarativePixmap p(&engine, url); + } +} + QTEST_MAIN(tst_qdeclarativepixmapcache) #include "tst_qdeclarativepixmapcache.moc" -- cgit v0.12 From cbe62050c28bae3b1f251be72e28cfe509cea14c Mon Sep 17 00:00:00 2001 From: axis Date: Wed, 1 Sep 2010 15:44:47 +0200 Subject: Fixed Symbian builds after introduction of boilerplate code. Hopefully the linux-armcc and linux-gcce mkspecs will be renamed later, but until then, we need this fix. RevBy: Trust me --- src/corelib/global/global.pri | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/global/global.pri b/src/corelib/global/global.pri index 2505e72..260ed59 100644 --- a/src/corelib/global/global.pri +++ b/src/corelib/global/global.pri @@ -19,7 +19,7 @@ INCLUDEPATH += $$QT_BUILD_TREE/src/corelib/global # Only used on platforms with CONFIG += precompile_header PRECOMPILED_HEADER = global/qt_pch.h -linux*:!static { +linux*:!static:!linux-armcc:!linux-gcce { QMAKE_LFLAGS += -Wl,-e,qt_core_boilerplate prog=$$quote(if (/program interpreter: (.*)]/) { print $1; }) DEFINES += ELF_INTERPRETER=\\\"$$system(readelf -l /bin/ls | perl -n -e \'$$prog\')\\\" -- cgit v0.12 From 389921022ea903c1a3eab6e110afd9bff49e719b Mon Sep 17 00:00:00 2001 From: axis Date: Thu, 2 Sep 2010 09:47:37 +0200 Subject: Revert "QLineEdit cursor is shown when asked to be non-visible" This reverts commit 9ef61d3d1e53d32dc2568cbfb9f8ff5b19cb4ffc. --- src/gui/widgets/qlinecontrol.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/gui/widgets/qlinecontrol.cpp b/src/gui/widgets/qlinecontrol.cpp index 69e6791..b6dfd13 100644 --- a/src/gui/widgets/qlinecontrol.cpp +++ b/src/gui/widgets/qlinecontrol.cpp @@ -464,8 +464,6 @@ void QLineControl::processInputMethodEvent(QInputMethodEvent *event) if (a.type == QInputMethodEvent::Cursor) { m_preeditCursor = a.start; m_hideCursor = !a.length; - if (m_hideCursor) - setCursorBlinkPeriod(0); } else if (a.type == QInputMethodEvent::TextFormat) { QTextCharFormat f = qvariant_cast(a.value).toCharFormat(); if (f.isValid()) { @@ -529,7 +527,7 @@ void QLineControl::draw(QPainter *painter, const QPoint &offset, const QRect &cl int cursor = m_cursor; if (m_preeditCursor != -1) cursor += m_preeditCursor; - if (!m_hideCursor && (!m_blinkPeriod || m_blinkStatus)) + if(!m_blinkPeriod || m_blinkStatus) m_textLayout.drawCursor(painter, offset, cursor, m_cursorWidth); } } -- cgit v0.12 From 4c8571de2d50e1dbfeef38b1e1e09c48a0a27aa4 Mon Sep 17 00:00:00 2001 From: Jiang Jiang Date: Mon, 23 Aug 2010 12:53:04 +0200 Subject: Fix symbol font detection in generic CMap decoding For fonts that have an AppleRoman name table, *isSymbolFont failed to return correct value even if they have a symbol table. This patch corrected this behavior by using symbolTable variable to detect that instead of checking if score == Symbol. Also prefer symbol table over AppleRoman table to make generic CMap decoding consistent with QFontEngineFT (which will use the symbol table whenever its available). Task-number: QTBUG-3852 Reviewed-by: Lars Knoll --- src/gui/text/qfontengine.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/gui/text/qfontengine.cpp b/src/gui/text/qfontengine.cpp index 3f758b1..1e8461f 100644 --- a/src/gui/text/qfontengine.cpp +++ b/src/gui/text/qfontengine.cpp @@ -874,8 +874,8 @@ const uchar *QFontEngine::getCMap(const uchar *table, uint tableSize, bool *isSy enum { Invalid, - Symbol, AppleRoman, + Symbol, Unicode11, Unicode, MicrosoftUnicode, @@ -939,7 +939,7 @@ const uchar *QFontEngine::getCMap(const uchar *table, uint tableSize, bool *isSy return 0; resolveTable: - *isSymbolFont = (score == Symbol); + *isSymbolFont = (symbolTable > -1); unsigned int unicode_table = qFromBigEndian(maps + 8*tableToUse + 4); -- cgit v0.12 From 7f5cae532d9f1841d15f01064bf97775b9fd8b0d Mon Sep 17 00:00:00 2001 From: Jiang Jiang Date: Mon, 23 Aug 2010 12:56:50 +0200 Subject: Keep mirrored char handling consistent between some font engines Mirrored character subsitution should be used in right-to-left text direction unless the font is a symbol font. This patch will keep this behavior consistent between FreeType, QPF and S60 font engines. For Mac font engines, the shaping process is delegated to Core Text or ATSUI, so we don't do mirrored char handling by ourselves. Task-number: QTBUG-3852 Reviewed-by: Lars Knoll --- src/gui/text/qfontengine_ft.cpp | 2 -- src/gui/text/qfontengine_qpf.cpp | 2 -- src/gui/text/qfontengine_s60.cpp | 2 +- 3 files changed, 1 insertion(+), 5 deletions(-) diff --git a/src/gui/text/qfontengine_ft.cpp b/src/gui/text/qfontengine_ft.cpp index 60db8b6..a9b25f5 100644 --- a/src/gui/text/qfontengine_ft.cpp +++ b/src/gui/text/qfontengine_ft.cpp @@ -1565,8 +1565,6 @@ bool QFontEngineFT::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs FT_Face face = freetype->face; for ( int i = 0; i < len; ++i ) { unsigned int uc = getChar(str, i, len); - if (mirrored) - uc = QChar::mirroredChar(uc); glyphs->glyphs[glyph_pos] = uc < QFreetypeFace::cmapCacheSize ? freetype->cmapCache[uc] : 0; if ( !glyphs->glyphs[glyph_pos] ) { glyph_t glyph; diff --git a/src/gui/text/qfontengine_qpf.cpp b/src/gui/text/qfontengine_qpf.cpp index a0593cc..53b6910 100644 --- a/src/gui/text/qfontengine_qpf.cpp +++ b/src/gui/text/qfontengine_qpf.cpp @@ -578,8 +578,6 @@ bool QFontEngineQPF::stringToCMap(const QChar *str, int len, QGlyphLayout *glyph if (symbol) { for (int i = 0; i < len; ++i) { unsigned int uc = getChar(str, i, len); - if (mirrored) - uc = QChar::mirroredChar(uc); glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc); if(!glyphs->glyphs[glyph_pos] && uc < 0x100) glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc + 0xf000); diff --git a/src/gui/text/qfontengine_s60.cpp b/src/gui/text/qfontengine_s60.cpp index 2cc3f50..2c533db 100644 --- a/src/gui/text/qfontengine_s60.cpp +++ b/src/gui/text/qfontengine_s60.cpp @@ -256,7 +256,7 @@ bool QFontEngineS60::stringToCMap(const QChar *characters, int len, QGlyphLayout for (int i = 0; i < len; ++i) { const unsigned int uc = getChar(characters, i, len); *g++ = QFontEngine::getTrueTypeGlyphIndex(cmap, - isRtl ? QChar::mirroredChar(uc) : uc); + (isRtl && !m_symbolCMap) ? QChar::mirroredChar(uc) : uc); } glyphs->numGlyphs = g - glyphs->glyphs; -- cgit v0.12 From f700d92ad259e3c4ddc6adf04069e200403b028a Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Thu, 2 Sep 2010 11:54:11 +0200 Subject: Update the cpuid code to be better There's no need to test and retest if the cpuid instruction is present on 32-bit. There's no need to test it at all on 64-bit. We don't know why, but it also fixes some problems on 64-bit. Approving-nod-from: Bradley Hughes --- src/corelib/tools/qsimd.cpp | 106 ++++++++++++++++---------------------------- 1 file changed, 37 insertions(+), 69 deletions(-) diff --git a/src/corelib/tools/qsimd.cpp b/src/corelib/tools/qsimd.cpp index 68ab033..7349432 100644 --- a/src/corelib/tools/qsimd.cpp +++ b/src/corelib/tools/qsimd.cpp @@ -140,56 +140,41 @@ static inline uint detectProcessorFeatures() uint result = 0; /* see p. 118 of amd64 instruction set manual Vol3 */ #if defined(Q_CC_GNU) - asm ("push %%ebx\n" - "pushf\n" - "pop %%eax\n" - "mov %%eax, %%ebx\n" - "xor $0x00200000, %%eax\n" - "push %%eax\n" - "popf\n" - "pushf\n" - "pop %%eax\n" - "xor %%edx, %%edx\n" - "xor %%ebx, %%eax\n" - "jz 1f\n" - - "mov $0x00000001, %%eax\n" - "cpuid\n" - "1:\n" - "pop %%ebx\n" - "mov %%edx, %0\n" - "mov %%ecx, %1\n" - : "=r" (result), "=r" (feature_result) - : - : "%eax", "%ecx", "%edx" - ); - - asm ("push %%ebx\n" - "pushf\n" - "pop %%eax\n" - "mov %%eax, %%ebx\n" - "xor $0x00200000, %%eax\n" - "push %%eax\n" + long cpuid_supported, tmp1; + asm ("pushf\n" + "pop %0\n" + "mov %0, %1\n" + "xor $0x00200000, %0\n" + "push %0\n" "popf\n" "pushf\n" - "pop %%eax\n" - "xor %%edx, %%edx\n" - "xor %%ebx, %%eax\n" - "jz 2f\n" - - "mov $0x80000000, %%eax\n" - "cpuid\n" - "cmp $0x80000000, %%eax\n" - "jbe 2f\n" - "mov $0x80000001, %%eax\n" - "cpuid\n" - "2:\n" - "pop %%ebx\n" - "mov %%edx, %0\n" - : "=r" (extended_result) - : - : "%eax", "%ecx", "%edx" - ); + "pop %0\n" + "xor %1, %0\n" // %eax is now 0 if CPUID is not supported + : "=a" (cpuid_supported), "=r" (tmp1) + ); + if (cpuid_supported) { + asm ("xchg %%ebx, %2\n" + "cpuid\n" + "xchg %%ebx, %2\n" + : "=c" (feature_result), "=d" (result), "=&r" (tmp1) + : "a" (1)); + + asm ("xchg %%ebx, %1\n" + "cpuid\n" + "cmp $0x80000000, %%eax\n" + "jnbe 1f\n" + "xor %0, %0\n" + "jmp 2f\n" + "1:\n" + "mov $0x80000001, %%eax\n" + "cpuid\n" + "2:\n" + "xchg %%ebx, %1\n" + : "=d" (extended_result), "=&r" (tmp1) + : "a" (0x80000000) + : "%ecx" + ); + } #elif defined (Q_OS_WIN) _asm { @@ -289,27 +274,10 @@ static inline uint detectProcessorFeatures() uint feature_result = 0; #if defined(Q_CC_GNU) - asm ("push %%rbx\n" - "pushf\n" - "pop %%rax\n" - "mov %%eax, %%ebx\n" - "xor $0x00200000, %%eax\n" - "push %%rax\n" - "popf\n" - "pushf\n" - "pop %%rax\n" - "xor %%edx, %%edx\n" - "xor %%ebx, %%eax\n" - "jz 1f\n" - - "mov $0x00000001, %%eax\n" - "cpuid\n" - "1:\n" - "pop %%rbx\n" - "mov %%ecx, %0\n" - : "=r" (feature_result) - : - : "%eax", "%ecx", "%edx" + asm ("cpuid" + : "=c" (feature_result) + : "a" (1) + : "%ebx", "%edx" ); #elif defined (Q_OS_WIN64) { -- cgit v0.12 From 0896d1f24396a2721cf1671f4e658b8856a0f430 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Tue, 29 Jun 2010 21:29:46 +0200 Subject: Reorganise qelapsedtimer_unix.cpp for better inlining performance. Benchmarks indicate no more than 5% improvement in the calls to elapsed(). Reviewed-by: Bradley T. Hughes --- src/corelib/tools/qelapsedtimer_unix.cpp | 129 ++++++++++++++++++------------- 1 file changed, 74 insertions(+), 55 deletions(-) diff --git a/src/corelib/tools/qelapsedtimer_unix.cpp b/src/corelib/tools/qelapsedtimer_unix.cpp index 2c4ea58..633fa00 100644 --- a/src/corelib/tools/qelapsedtimer_unix.cpp +++ b/src/corelib/tools/qelapsedtimer_unix.cpp @@ -40,22 +40,58 @@ ****************************************************************************/ #include "qelapsedtimer.h" -#include "qpair.h" #include #include #include -#if !defined(QT_NO_CLOCK_MONOTONIC) -# if defined(QT_BOOTSTRAPPED) -# define QT_NO_CLOCK_MONOTONIC +#if defined(QT_NO_CLOCK_MONOTONIC) || defined(QT_BOOTSTRAPPED) +// turn off the monotonic clock +# ifdef _POSIX_MONOTONIC_CLOCK +# undef _POSIX_MONOTONIC_CLOCK # endif +# define _POSIX_MONOTONIC_CLOCK -1 #endif QT_BEGIN_NAMESPACE -static qint64 fractionAdjustment() +#if (_POSIX_MONOTONIC_CLOCK-0 != 0) +static const bool monotonicClockChecked = true; +static const bool monotonicClockAvailable = _POSIX_MONOTONIC_CLOCK > 0; +#else +static int monotonicClockChecked = false; +static int monotonicClockAvailable = false; +#endif + +#ifdef Q_CC_GNU +# define is_likely(x) __builtin_expect((x), 1) +#else +# define is_likely(x) (x) +#endif +#define load_acquire(x) ((volatile const int&)(x)) +#define store_release(x,v) ((volatile int&)(x) = (v)) + +static void unixCheckClockType() +{ +#if (_POSIX_MONOTONIC_CLOCK-0 == 0) + if (is_likely(load_acquire(monotonicClockChecked))) + return; + +# if defined(_SC_MONOTONIC_CLOCK) + // detect if the system support monotonic timers + long x = sysconf(_SC_MONOTONIC_CLOCK); + store_release(monotonicClockAvailable, x >= 200112L); +# endif + + store_release(monotonicClockChecked, true); +#endif +} + +static inline qint64 fractionAdjustment() { - if (QElapsedTimer::isMonotonic()) { + // disabled, but otherwise indicates bad usage of QElapsedTimer + //Q_ASSERT(monotonicClockChecked); + + if (monotonicClockAvailable) { // the monotonic timer is measured in nanoseconds // 1 ms = 1000000 ns return 1000*1000ull; @@ -68,90 +104,73 @@ static qint64 fractionAdjustment() bool QElapsedTimer::isMonotonic() { -#if (_POSIX_MONOTONIC_CLOCK-0 > 0) - return true; -#else - static int returnValue = 0; - - if (returnValue == 0) { -# if (_POSIX_MONOTONIC_CLOCK-0 < 0) || !defined(_SC_MONOTONIC_CLOCK) - returnValue = -1; -# elif (_POSIX_MONOTONIC_CLOCK == 0) - // detect if the system support monotonic timers - long x = sysconf(_SC_MONOTONIC_CLOCK); - returnValue = (x >= 200112L) ? 1 : -1; -# endif - } - - return returnValue != -1; -#endif + unixCheckClockType(); + return monotonicClockAvailable; } QElapsedTimer::ClockType QElapsedTimer::clockType() { - return isMonotonic() ? MonotonicClock : SystemTime; + unixCheckClockType(); + return monotonicClockAvailable ? MonotonicClock : SystemTime; } -static inline QPair do_gettime() +static inline void do_gettime(qint64 *sec, qint64 *frac) { -#if (_POSIX_MONOTONIC_CLOCK-0 > 0) - timespec ts; - clock_gettime(CLOCK_MONOTONIC, &ts); - return qMakePair(ts.tv_sec, ts.tv_nsec); -#else -# if !defined(QT_NO_CLOCK_MONOTONIC) && !defined(QT_BOOTSTRAPPED) - if (QElapsedTimer::isMonotonic()) { +#if (_POSIX_MONOTONIC_CLOCK-0 >= 0) + unixCheckClockType(); + if (is_likely(monotonicClockAvailable)) { timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); - return qMakePair(ts.tv_sec, ts.tv_nsec); + *sec = ts.tv_sec; + *frac = ts.tv_nsec; + return; } -# endif +#endif // use gettimeofday timeval tv; ::gettimeofday(&tv, 0); - return qMakePair(tv.tv_sec, tv.tv_usec); -#endif + *sec = tv.tv_sec; + *frac = tv.tv_usec; } // used in qcore_unix.cpp and qeventdispatcher_unix.cpp timeval qt_gettime() { - QPair r = do_gettime(); + qint64 sec, frac; + do_gettime(&sec, &frac); timeval tv; - tv.tv_sec = r.first; - tv.tv_usec = r.second; - if (QElapsedTimer::isMonotonic()) + tv.tv_sec = sec; + tv.tv_usec = frac; + if (monotonicClockAvailable) tv.tv_usec /= 1000; return tv; } +static qint64 elapsedAndRestart(qint64 sec, qint64 frac, + qint64 *nowsec, qint64 *nowfrac) +{ + do_gettime(nowsec, nowfrac); + sec = *nowsec - sec; + frac = *nowfrac - frac; + return sec * Q_INT64_C(1000) + frac / fractionAdjustment(); +} + void QElapsedTimer::start() { - QPair r = do_gettime(); - t1 = r.first; - t2 = r.second; + do_gettime(&t1, &t2); } qint64 QElapsedTimer::restart() { - QPair r = do_gettime(); - qint64 oldt1 = t1; - qint64 oldt2 = t2; - t1 = r.first; - t2 = r.second; - - r.first -= oldt1; - r.second -= oldt2; - return r.first * Q_INT64_C(1000) + r.second / fractionAdjustment(); + return elapsedAndRestart(t1, t2, &t1, &t2); } qint64 QElapsedTimer::elapsed() const { - QElapsedTimer now; - now.start(); - return msecsTo(now); + qint64 sec, frac; + return elapsedAndRestart(t1, t2, &sec, &frac); } qint64 QElapsedTimer::msecsSinceReference() const -- cgit v0.12 From a1e1103e1c3f0e47c5d075660a77d00f47e1c125 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Tue, 17 Aug 2010 21:32:23 +0200 Subject: Rewrite ucstrcmp in terms of ucstrncmp Reviewed-By: Bradley T. Hughes --- src/corelib/tools/qstring.cpp | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/src/corelib/tools/qstring.cpp b/src/corelib/tools/qstring.cpp index d940bf8..2813b29 100644 --- a/src/corelib/tools/qstring.cpp +++ b/src/corelib/tools/qstring.cpp @@ -173,19 +173,6 @@ static int ucstricmp(const ushort *a, const ushort *ae, const uchar *b) return 1; } -// Unicode case-sensitive comparison -static int ucstrcmp(const QChar *a, int alen, const QChar *b, int blen) -{ - if (a == b && alen == blen) - return 0; - int l = qMin(alen, blen); - while (l-- && *a == *b) - a++,b++; - if (l == -1) - return (alen-blen); - return a->unicode() - b->unicode(); -} - // Unicode case-sensitive compare two same-sized strings static int ucstrncmp(const QChar *a, const QChar *b, int l) { @@ -196,6 +183,16 @@ static int ucstrncmp(const QChar *a, const QChar *b, int l) return a->unicode() - b->unicode(); } +// Unicode case-sensitive comparison +static int ucstrcmp(const QChar *a, int alen, const QChar *b, int blen) +{ + if (a == b && alen == blen) + return 0; + int l = qMin(alen, blen); + int cmp = ucstrncmp(a, b, l); + return cmp ? cmp : (alen-blen); +} + // Unicode case-insensitive compare two same-sized strings static int ucstrnicmp(const ushort *a, const ushort *b, int l) { -- cgit v0.12 From ac33c5ba3206ac7bb1d38c796139d864a637f7a4 Mon Sep 17 00:00:00 2001 From: Marius Storm-Olsen Date: Tue, 31 Aug 2010 13:12:30 -0500 Subject: Add option to enable -MP compile option for MSVC The option is on when building Qt, but off by default for other projects, due to potential incompatible compile options in other projects. (/E, /EP, /Gm, /Yc, /showIncludes, #import preprocessor directive) Reviewed-by: bhughes Reviewed-by: ossi --- mkspecs/features/win32/msvc_mp.prf | 2 ++ mkspecs/win32-msvc2008/qmake.conf | 2 ++ mkspecs/win32-msvc2010/qmake.conf | 2 ++ tools/configure/configureapp.cpp | 14 +++++++++++++- 4 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 mkspecs/features/win32/msvc_mp.prf diff --git a/mkspecs/features/win32/msvc_mp.prf b/mkspecs/features/win32/msvc_mp.prf new file mode 100644 index 0000000..d6dea14 --- /dev/null +++ b/mkspecs/features/win32/msvc_mp.prf @@ -0,0 +1,2 @@ +QMAKE_CFLAGS += $$QMAKE_CFLAGS_MP +QMAKE_CXXFLAGS += $$QMAKE_CXXFLAGS_MP diff --git a/mkspecs/win32-msvc2008/qmake.conf b/mkspecs/win32-msvc2008/qmake.conf index 9805e90..9a69aaa 100644 --- a/mkspecs/win32-msvc2008/qmake.conf +++ b/mkspecs/win32-msvc2008/qmake.conf @@ -23,6 +23,7 @@ QMAKE_CFLAGS_RELEASE = -O2 -MD QMAKE_CFLAGS_DEBUG = -Zi -MDd QMAKE_CFLAGS_YACC = QMAKE_CFLAGS_LTCG = -GL +QMAKE_CFLAGS_MP = -MP QMAKE_CXX = $$QMAKE_CC QMAKE_CXXFLAGS = $$QMAKE_CFLAGS @@ -32,6 +33,7 @@ QMAKE_CXXFLAGS_RELEASE = $$QMAKE_CFLAGS_RELEASE QMAKE_CXXFLAGS_DEBUG = $$QMAKE_CFLAGS_DEBUG QMAKE_CXXFLAGS_YACC = $$QMAKE_CFLAGS_YACC QMAKE_CXXFLAGS_LTCG = $$QMAKE_CFLAGS_LTCG +QMAKE_CXXFLAGS_MP = $$QMAKE_CFLAGS_MP QMAKE_CXXFLAGS_STL_ON = -EHsc QMAKE_CXXFLAGS_STL_OFF = QMAKE_CXXFLAGS_RTTI_ON = -GR diff --git a/mkspecs/win32-msvc2010/qmake.conf b/mkspecs/win32-msvc2010/qmake.conf index 28d4d3c..8331c14 100644 --- a/mkspecs/win32-msvc2010/qmake.conf +++ b/mkspecs/win32-msvc2010/qmake.conf @@ -23,6 +23,7 @@ QMAKE_CFLAGS_RELEASE = -O2 -MD QMAKE_CFLAGS_DEBUG = -Zi -MDd QMAKE_CFLAGS_YACC = QMAKE_CFLAGS_LTCG = -GL +QMAKE_CFLAGS_MP = -MP QMAKE_CXX = $$QMAKE_CC QMAKE_CXXFLAGS = $$QMAKE_CFLAGS @@ -32,6 +33,7 @@ QMAKE_CXXFLAGS_RELEASE = $$QMAKE_CFLAGS_RELEASE QMAKE_CXXFLAGS_DEBUG = $$QMAKE_CFLAGS_DEBUG QMAKE_CXXFLAGS_YACC = $$QMAKE_CFLAGS_YACC QMAKE_CXXFLAGS_LTCG = $$QMAKE_CFLAGS_LTCG +QMAKE_CXXFLAGS_MP = $$QMAKE_CFLAGS_MP QMAKE_CXXFLAGS_STL_ON = -EHsc QMAKE_CXXFLAGS_STL_OFF = QMAKE_CXXFLAGS_RTTI_ON = -GR diff --git a/tools/configure/configureapp.cpp b/tools/configure/configureapp.cpp index 09da581..89d3ef0 100644 --- a/tools/configure/configureapp.cpp +++ b/tools/configure/configureapp.cpp @@ -381,6 +381,7 @@ Configure::Configure(int& argc, char** argv) dictionary[ "INCREDIBUILD_XGE" ] = "auto"; dictionary[ "LTCG" ] = "no"; dictionary[ "NATIVE_GESTURES" ] = "yes"; + dictionary[ "MSVC_MP" ] = "no"; } Configure::~Configure() @@ -534,6 +535,13 @@ void Configure::parseCmdLine() else if (configCmdLine.at(i) == "-no-ltcg") { dictionary[ "LTCG" ] = "no"; } + else if (configCmdLine.at(i) == "-mp") { + dictionary[ "MSVC_MP" ] = "yes"; + } + else if (configCmdLine.at(i) == "-no-mp") { + dictionary[ "MSVC_MP" ] = "no"; + } + #endif else if (configCmdLine.at(i) == "-platform") { @@ -1848,6 +1856,8 @@ bool Configure::displayHelp() desc("STYLE_S60" , "yes", "", " s60\n", ' '); desc("NATIVE_GESTURES", "no", "-no-native-gestures", "Do not use native gestures on Windows 7."); desc("NATIVE_GESTURES", "yes", "-native-gestures", "Use native gestures on Windows 7."); + desc("MSVC_MP", "no", "-no-mp", "Do not use multiple processors for compiling with MSVC"); + desc("MSVC_MP", "yes", "-mp", "Use multiple processors for compiling with MSVC (-MP)"); /* We do not support -qconfig on Windows yet @@ -2822,7 +2832,7 @@ void Configure::generateCachefile() for (QStringList::Iterator var = qmakeVars.begin(); var != qmakeVars.end(); ++var) { cacheStream << (*var) << endl; } - cacheStream << "CONFIG += " << qmakeConfig.join(" ") << " incremental create_prl link_prl depend_includepath QTDIR_build" << endl; + cacheStream << "CONFIG += " << qmakeConfig.join(" ") << " incremental msvc_mp create_prl link_prl depend_includepath QTDIR_build" << endl; QStringList buildParts; buildParts << "libs" << "tools" << "examples" << "demos" << "docs" << "translations"; @@ -2885,6 +2895,8 @@ void Configure::generateCachefile() if (dictionary[ "LTCG" ] == "yes") configStream << " ltcg"; + if (dictionary[ "MSVC_MP" ] == "yes") + configStream << " msvc_mp"; if (dictionary[ "STL" ] == "yes") configStream << " stl"; if (dictionary[ "EXCEPTIONS" ] == "yes") -- cgit v0.12 From d9d9fc57e70a63b42077de59fca45f9de082b2a2 Mon Sep 17 00:00:00 2001 From: Marius Storm-Olsen Date: Tue, 31 Aug 2010 13:50:28 -0500 Subject: Turn Makefile.win32 into batch-mode, enable /MP and PCH This should make compiling qmake quite a bit faster, since less invokations of the compiler is needed, every compile unit starts of with a already known state, and all the CPU cores are used to compile the units. Reviewed-by: bhughes Reviewed-by: ossi --- qmake/Makefile.win32 | 357 +++++++-------------------------------------------- 1 file changed, 49 insertions(+), 308 deletions(-) diff --git a/qmake/Makefile.win32 b/qmake/Makefile.win32 index b58757c..01387bf 100644 --- a/qmake/Makefile.win32 +++ b/qmake/Makefile.win32 @@ -24,9 +24,11 @@ LINK = link # !if "$(QMAKESPEC)" == "win32-msvc2005" CFLAGS = /Zc:wchar_t- +!elseif "$(QMAKESPEC)" == "win32-msvc2008" || "$(QMAKESPEC)" == "win32-msvc2010" +CFLAGS = /MP !endif -CFLAGS = -c -Fo$@ \ +CFLAGS_BARE = -c -Fo./ \ -W3 -nologo -O2 \ -I. -Igenerators -Igenerators\unix -Igenerators\win32 -Igenerators\mac -Igenerators\symbian \ -I$(BUILD_PATH)\include -I$(BUILD_PATH)\include\QtCore \ @@ -37,42 +39,23 @@ CFLAGS = -c -Fo$@ \ -I$(SOURCE_PATH)\tools\shared \ -DQT_NO_TEXTCODEC -DQT_NO_UNICODETABLES -DQT_LITE_COMPONENT -DQT_NODLL -DQT_NO_STL \ -DQT_NO_COMPRESS -DUNICODE -DHAVE_QCONFIG_CPP -DQT_BUILD_QMAKE -DQT_NO_THREAD \ - -DQT_NO_QOBJECT -DQT_NO_GEOM_VARIANT -DQT_NO_DATASTREAM -DQT_NO_PCRE -DQT_BOOTSTRAPPED \ - $(CFLAGS) -CXXFLAGS = $(CFLAGS) + -DQT_NO_QOBJECT -DQT_NO_GEOM_VARIANT -DQT_NO_DATASTREAM -DQT_NO_PCRE -DQT_BOOTSTRAPPED +CFLAGS = -Yuqmake_pch.h -FIqmake_pch.h -Fpqmake_pch.pch $(CFLAGS_BARE) $(CFLAGS) + +CXXFLAGS_BARE = $(CFLAGS_BARE) +CXXFLAGS = $(CFLAGS) + LFLAGS = LIBS = ole32.lib advapi32.lib LINKQMAKE = $(LINK) $(LFLAGS) -OUT:qmake.exe $(OBJS) $(QTOBJS) $(LIBS) ADDCLEAN = vc60.pdb vc70.pdb qmake.pdb qmake.ilk -!ELSE -# -# specific stuff for Borland make -# -!if !$d(BCB) -BCB = $(MAKEDIR)\.. -!endif -CXX = bcc32 -CFLAGS = -c -o$@ \ - -tWR -w -w-hid -w-use -O1 \ - -I. -Igenerators -Igenerators\unix -Igenerators\win32 -Igenerators\mac -Igenerators\symbian \ - -I$(BUILD_PATH)\include -I$(BUILD_PATH)\include\QtCore \ - -I$(SOURCE_PATH)\include -I$(SOURCE_PATH)\include\QtCore \ - -I$(BUILD_PATH)\src\corelib\global \ - -I$(SOURCE_PATH)\mkspecs\$(QMAKESPEC) \ - -I$(SOURCE_PATH)\tools\shared \ - -DQT_NO_TEXTCODEC -DQT_NO_UNICODETABLES -DQT_LITE_COMPONENT -DQT_NODLL -DQT_NO_STL \ - -DQT_NO_COMPRESS -DUNICODE -DHAVE_QCONFIG_CPP -DQT_BUILD_QMAKE -DQT_NO_THREAD \ - -DQT_NO_QOBJECT -DQT_NO_GEOM_VARIANT -CXXFLAGS = $(CFLAGS) -LFLAGS = -L$(BCB)\lib -c -x -Gn -ap -Tpe c0x32.obj -LIBS = import32.lib cw32i.lib -LINKQMAKE = ilink32 $(LFLAGS) $(OBJS) $(QTOBJS), qmake.exe,,$(LIBS) -ADDCLEAN = qmake.tds +!ELSE +!ERROR Unsupported compiler for this Makefile !ENDIF #qmake code -OBJS = project.obj main.obj makefile.obj unixmake.obj unixmake2.obj mingw_make.obj \ +OBJS = qmake_pch.obj project.obj main.obj makefile.obj unixmake.obj unixmake2.obj mingw_make.obj \ option.obj winmakefile.obj projectgenerator.obj property.obj meta.obj \ makefiledeps.obj metamakefile.obj xmloutput.obj pbuilder_pbx.obj \ borland_bmake.obj msvc_nmake.obj msvc_vcproj.obj msvc_vcxproj.obj \ @@ -137,77 +120,9 @@ qmake.exe: $(OBJS) $(QTOBJS) -copy qmake.exe $(BUILD_PATH)\bin\qmake.exe clean:: - -del qbitarray.obj - -del qbuffer.obj - -del qcryptographichash.obj - -del qlinkedlist.obj - -del qfsfileengine.obj - -del qfsfileengine_iterator.obj - -del qbytearray.obj - -del qvsnprintf.obj - -del qbytearraymatcher.obj - -del qdatetime.obj - -del qdir.obj - -del qdiriterator.obj - -del qfile.obj - -del qtemporaryfile.obj - -del qabstractfileengine.obj - -del qfsfileengine_win.obj - -del qfsfileengine_iterator_win.obj - -del qfileinfo.obj - -del qglobal.obj - -del qhash.obj - -del qiodevice.obj - -del qlist.obj - -del qlocale.obj - -del qmalloc.obj - -del qmap.obj - -del qregexp.obj - -del qtextcodec.obj - -del qutfcodec.obj - -del qstring.obj - -del qstringlist.obj - -del qtextstream.obj - -del qdatastream.obj - -del quuid.obj - -del qvector.obj - -del qsettings.obj - -del qlibraryinfo.obj - -del qvariant.obj - -del qurl.obj - -del qsettings_win.obj - -del qmetatype.obj - -del project.obj - -del main.obj - -del makefile.obj - -del unixmake.obj - -del unixmake2.obj - -del mingw_make.obj - -del option.obj - -del winmakefile.obj - -del projectgenerator.obj - -del property.obj - -del meta.obj - -del makefiledeps.obj - -del metamakefile.obj - -del xmloutput.obj - -del borland_bmake.obj - -del msvc_nmake.obj - -del msvc_vcproj.obj - -del msvc_vcxproj.obj - -del msvc_objectmodel.obj - -del msbuild_objectmodel.obj - -del symmake.obj - -del symmake_abld.obj - -del symmake_sbsv2.obj - -del symbiancommon.obj - -del initprojectdeploy_symbian.obj - -del registry.obj - -del epocroot.obj - -del pbuilder_pbx.obj - -del qxmlstream.obj - -del qxmlutils.obj - -del qnumeric.obj + -del $(QTOBJS) + -del $(OBJS) + -del qmake_pch.pch -del vc60.pdb -del vc70.pdb -del qmake.pdb @@ -229,227 +144,53 @@ distclean:: clean .cxx.obj: $(CXX) $(CXXFLAGS) $< -qsettings_win.obj: $(SOURCE_PATH)\src\corelib\io\qsettings_win.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qsettings_win.cpp - -qsettings.obj: $(SOURCE_PATH)\src\corelib\io\qsettings.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qsettings.cpp - -qlibraryinfo.obj: $(SOURCE_PATH)\src\corelib\global\qlibraryinfo.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\global\qlibraryinfo.cpp - -qnumeric.obj: $(SOURCE_PATH)\src\corelib\global\qnumeric.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\global\qnumeric.cpp - -qvariant.obj: $(SOURCE_PATH)\src\corelib\kernel\qvariant.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\kernel\qvariant.cpp - -qurl.obj: $(SOURCE_PATH)\src\corelib\io\qurl.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qurl.cpp - -qtextstream.obj: $(SOURCE_PATH)\src\corelib\io\qtextstream.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qtextstream.cpp - -qdatastream.obj: $(SOURCE_PATH)\src\corelib\io\qdatastream.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qdatastream.cpp - -qiodevice.obj: $(SOURCE_PATH)\src\corelib\io\qiodevice.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qiodevice.cpp - -qmalloc.obj: $(SOURCE_PATH)\src\corelib\global\qmalloc.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\global\qmalloc.cpp - -qglobal.obj: $(SOURCE_PATH)\src\corelib\global\qglobal.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\global\qglobal.cpp - -qhash.obj: $(SOURCE_PATH)\src\corelib\tools\qhash.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qhash.cpp - -qbytearray.obj: $(SOURCE_PATH)\src\corelib\tools\qbytearray.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qbytearray.cpp - -qcryptographichash.obj: $(SOURCE_PATH)\src\corelib\tools\qcryptographichash.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qcryptographichash.cpp - -qvsnprintf.obj: $(SOURCE_PATH)\src\corelib\tools\qvsnprintf.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qvsnprintf.cpp - -qbytearraymatcher.obj: $(SOURCE_PATH)\src\corelib\tools\qbytearraymatcher.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qbytearraymatcher.cpp - -qchar.obj: $(SOURCE_PATH)\src\corelib\tools\qchar.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qchar.cpp - -qutfcodec.obj: $(SOURCE_PATH)\src\corelib\codecs\qutfcodec.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\codecs\qutfcodec.cpp - -qstring.obj: $(SOURCE_PATH)\src\corelib\tools\qstring.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qstring.cpp - -qstringmatcher.obj: $(SOURCE_PATH)\src\corelib\tools\qstringmatcher.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qstringmatcher.cpp - -qlocale.obj: $(SOURCE_PATH)\src\corelib\tools\qlocale.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qlocale.cpp - -quuid.obj: $(SOURCE_PATH)\src\corelib\plugin\quuid.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\plugin\quuid.cpp - -qbuffer.obj: $(SOURCE_PATH)\src\corelib\io\qbuffer.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qbuffer.cpp - -qlist.obj: $(SOURCE_PATH)\src\corelib\tools\qlist.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qlist.cpp - -qlinkedlist.obj: $(SOURCE_PATH)\src\corelib\tools\qlinkedlist.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qlinkedlist.cpp - -qfile.obj: $(SOURCE_PATH)\src\corelib\io\qfile.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qfile.cpp - -qtemporaryfile.obj: $(SOURCE_PATH)\src\corelib\io\qtemporaryfile.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qtemporaryfile.cpp - -qfsfileengine_win.obj: $(SOURCE_PATH)\src\corelib\io\qfsfileengine_win.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qfsfileengine_win.cpp - -qfsfileengine_iterator_win.obj: $(SOURCE_PATH)\src\corelib\io\qfsfileengine_iterator_win.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qfsfileengine_iterator_win.cpp - -qfsfileengine.obj: $(SOURCE_PATH)\src\corelib\io\qfsfileengine.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qfsfileengine.cpp - -qfsfileengine_iterator.obj: $(SOURCE_PATH)\src\corelib\io\qfsfileengine_iterator.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qfsfileengine_iterator.cpp - -qabstractfileengine.obj: $(SOURCE_PATH)\src\corelib\io\qabstractfileengine.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qabstractfileengine.cpp - -qtextcodec.obj: $(SOURCE_PATH)\src\corelib\codecs\qtextcodec.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\codecs\qtextcodec.cpp - -qregexp.obj: $(SOURCE_PATH)\src\corelib\tools\qregexp.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qregexp.cpp - -qvector.obj: $(SOURCE_PATH)\src\corelib\tools\qvector.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qvector.cpp +qmake_pch.obj: + $(CXX) $(CXXFLAGS_BARE) -c -Yc -Fpqmake_pch.pch -TP qmake_pch.h -qbitarray.obj: $(SOURCE_PATH)\src\corelib\tools\qbitarray.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qbitarray.cpp - -qdir.obj: $(SOURCE_PATH)\src\corelib\io\qdir.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qdir.cpp - -qdiriterator.obj: $(SOURCE_PATH)\src\corelib\io\qdiriterator.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qdiriterator.cpp - -qmetatype.obj: $(SOURCE_PATH)\src\corelib\kernel\qmetatype.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\kernel\qmetatype.cpp - -qfileinfo.obj: $(SOURCE_PATH)\src\corelib\io\qfileinfo.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\io\qfileinfo.cpp - -qdatetime.obj: $(SOURCE_PATH)\src\corelib\tools\qdatetime.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qdatetime.cpp - -qstringlist.obj: $(SOURCE_PATH)\src\corelib\tools\qstringlist.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qstringlist.cpp - -qmap.obj: $(SOURCE_PATH)\src\corelib\tools\qmap.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qmap.cpp - -qunicodetables.obj: $(SOURCE_PATH)\src\corelib\tools\qunicodetables.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\tools\qunicodetables.cpp - -makefile.obj: $(SOURCE_PATH)/qmake/generators\makefile.cpp - $(CXX) $(CXXFLAGS) generators\makefile.cpp - -unixmake.obj: $(SOURCE_PATH)/qmake/generators\unix\unixmake.cpp - $(CXX) $(CXXFLAGS) generators\unix\unixmake.cpp - -unixmake2.obj: $(SOURCE_PATH)/qmake/generators\unix\unixmake2.cpp - $(CXX) $(CXXFLAGS) generators\unix\unixmake2.cpp - -winmakefile.obj: $(SOURCE_PATH)/qmake/generators/win32/winmakefile.cpp - $(CXX) $(CXXFLAGS) generators/win32/winmakefile.cpp - -borland_bmake.obj: $(SOURCE_PATH)/qmake/generators/win32/borland_bmake.cpp - $(CXX) $(CXXFLAGS) generators/win32/borland_bmake.cpp - -mingw_make.obj: $(SOURCE_PATH)/qmake/generators/win32/mingw_make.cpp - $(CXX) $(CXXFLAGS) generators/win32/mingw_make.cpp - -msvc_nmake.obj: $(SOURCE_PATH)/qmake/generators/win32/msvc_nmake.cpp - $(CXX) $(CXXFLAGS) generators/win32/msvc_nmake.cpp - -msvc_vcproj.obj: $(SOURCE_PATH)/qmake/generators/win32/msvc_vcproj.cpp - $(CXX) $(CXXFLAGS) generators/win32/msvc_vcproj.cpp - -msvc_vcxproj.obj: $(SOURCE_PATH)/qmake/generators/win32/msvc_vcxproj.cpp - $(CXX) $(CXXFLAGS) generators/win32/msvc_vcxproj.cpp - -msvc_objectmodel.obj: $(SOURCE_PATH)/qmake/generators/win32/msvc_objectmodel.cpp - $(CXX) $(CXXFLAGS) generators/win32/msvc_objectmodel.cpp - -msbuild_objectmodel.obj: $(SOURCE_PATH)/qmake/generators/win32/msbuild_objectmodel.cpp - $(CXX) $(CXXFLAGS) generators/win32/msbuild_objectmodel.cpp - -symmake.obj: $(SOURCE_PATH)/qmake/generators/symbian/symmake.cpp - $(CXX) $(CXXFLAGS) generators/symbian/symmake.cpp - -symmake_abld.obj: $(SOURCE_PATH)/qmake/generators/symbian/symmake_abld.cpp - $(CXX) $(CXXFLAGS) generators/symbian/symmake_abld.cpp - -symmake_sbsv2.obj: $(SOURCE_PATH)/qmake/generators/symbian/symmake_sbsv2.cpp - $(CXX) $(CXXFLAGS) generators/symbian/symmake_sbsv2.cpp - -symbiancommon.obj: $(SOURCE_PATH)/qmake/generators/symbian/symbiancommon.cpp - $(CXX) $(CXXFLAGS) generators/symbian/symbiancommon.cpp - -initprojectdeploy_symbian.obj: $(SOURCE_PATH)/qmake/generators/symbian/initprojectdeploy_symbian.cpp - $(CXX) $(CXXFLAGS) generators/symbian/initprojectdeploy_symbian.cpp +{$(SOURCE_PATH)\qmake\generators\mac}.cpp{}.obj:: + $(CXX) $(CXXFLAGS) $< -registry.obj: $(SOURCE_PATH)/tools/shared/windows/registry.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)/tools/shared/windows/registry.cpp +{$(SOURCE_PATH)\qmake\generators\symbian}.cpp{}.obj:: + $(CXX) $(CXXFLAGS) $< -epocroot.obj: $(SOURCE_PATH)/tools/shared/symbian/epocroot.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)/tools/shared/symbian/epocroot.cpp +{$(SOURCE_PATH)\qmake\generators\unix}.cpp{}.obj:: + $(CXX) $(CXXFLAGS) $< -md5.obj: $(SOURCE_PATH)\src\3rdparty\md5\md5.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\3rdparty\md5\md5.cpp +{$(SOURCE_PATH)\qmake\generators\win32}.cpp{}.obj:: + $(CXX) $(CXXFLAGS) $< -project.obj: $(SOURCE_PATH)/qmake/project.cpp $(SOURCE_PATH)/qmake/project.h $(SOURCE_PATH)/qmake/option.h - $(CXX) $(CXXFLAGS) project.cpp +{$(SOURCE_PATH)\qmake\generators}.cpp{}.obj:: + $(CXX) $(CXXFLAGS) $< -meta.obj: $(SOURCE_PATH)/qmake/meta.cpp $(SOURCE_PATH)/qmake/project.h $(SOURCE_PATH)/qmake/option.h - $(CXX) $(CXXFLAGS) meta.cpp +{$(SOURCE_PATH)\qmake}.cpp{}.obj:: + $(CXX) $(CXXFLAGS) $< -main.obj: $(SOURCE_PATH)/qmake/main.cpp $(SOURCE_PATH)/qmake/project.h - $(CXX) $(CXXFLAGS) main.cpp +{$(SOURCE_PATH)\src\3rdparty\md5}.cpp{}.obj:: + $(CXX) $(CXXFLAGS) $< -option.obj: $(SOURCE_PATH)/qmake/option.cpp $(SOURCE_PATH)/qmake/option.h - $(CXX) $(CXXFLAGS) option.cpp +{$(SOURCE_PATH)\src\corelib\codecs}.cpp{}.obj:: + $(CXX) $(CXXFLAGS) $< -property.obj: $(SOURCE_PATH)/qmake/property.cpp $(SOURCE_PATH)/qmake/project.h $(SOURCE_PATH)/qmake/option.h - $(CXX) $(CXXFLAGS) property.cpp +{$(SOURCE_PATH)\src\corelib\global}.cpp{}.obj:: + $(CXX) $(CXXFLAGS) $< -projectgenerator.obj: $(SOURCE_PATH)/qmake/generators/projectgenerator.cpp - $(CXX) $(CXXFLAGS) generators/projectgenerator.cpp +{$(SOURCE_PATH)\src\corelib\io}.cpp{}.obj:: + $(CXX) $(CXXFLAGS) $< -pbuilder_pbx.obj: $(SOURCE_PATH)/qmake/generators/mac/pbuilder_pbx.cpp - $(CXX) $(CXXFLAGS) generators/mac/pbuilder_pbx.cpp +{$(SOURCE_PATH)\src\corelib\kernel}.cpp{}.obj:: + $(CXX) $(CXXFLAGS) $< -makefiledeps.obj: $(SOURCE_PATH)/qmake/generators/makefiledeps.cpp - $(CXX) $(CXXFLAGS) generators/makefiledeps.cpp +{$(SOURCE_PATH)\src\corelib\plugin}.cpp{}.obj:: + $(CXX) $(CXXFLAGS) $< -metamakefile.obj: $(SOURCE_PATH)/qmake/generators/metamakefile.cpp - $(CXX) $(CXXFLAGS) generators/metamakefile.cpp +{$(SOURCE_PATH)\src\corelib\tools}.cpp{}.obj:: + $(CXX) $(CXXFLAGS) $< -xmloutput.obj: $(SOURCE_PATH)/qmake/generators/xmloutput.cpp - $(CXX) $(CXXFLAGS) generators/xmloutput.cpp +{$(SOURCE_PATH)\src\corelib\xml}.cpp{}.obj:: + $(CXX) $(CXXFLAGS) $< -qxmlstream.obj: $(SOURCE_PATH)\src\corelib\xml\qxmlstream.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\xml\qxmlstream.cpp +{$(SOURCE_PATH)\tools\shared\symbian}.cpp{}.obj:: + $(CXX) $(CXXFLAGS) $< -qxmlutils.obj: $(SOURCE_PATH)\src\corelib\xml\qxmlutils.cpp - $(CXX) $(CXXFLAGS) $(SOURCE_PATH)\src\corelib\xml\qxmlutils.cpp +{$(SOURCE_PATH)\tools\shared\windows}.cpp{}.obj:: + $(CXX) $(CXXFLAGS) $< -- cgit v0.12 From 6387bb349e2590da620bd69d779df966c703f358 Mon Sep 17 00:00:00 2001 From: Marius Storm-Olsen Date: Wed, 1 Sep 2010 12:30:51 -0500 Subject: New binary of configure.exe with -mp/-no-mp option Reviewed-by: trustme --- configure.exe | Bin 1320960 -> 1320960 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/configure.exe b/configure.exe index 982e038..aba5872 100755 Binary files a/configure.exe and b/configure.exe differ -- cgit v0.12 From adcd745d6ef2dbd68a28e932e2a8961b70bece09 Mon Sep 17 00:00:00 2001 From: Morten Engvoldsen Date: Thu, 2 Sep 2010 13:55:31 +0200 Subject: Doc: Updated Supported Platforms page. Finished --- doc/src/platforms/supported-platforms.qdoc | 42 ++++++++++++++---------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/doc/src/platforms/supported-platforms.qdoc b/doc/src/platforms/supported-platforms.qdoc index bb80ae5..6e9fb3d 100644 --- a/doc/src/platforms/supported-platforms.qdoc +++ b/doc/src/platforms/supported-platforms.qdoc @@ -64,18 +64,22 @@ \row \o Linux (32 and 64-bit) \o gcc 4.2 \row \o Microsoft Windows XP - \o gcc 4.4 (MinGW) (32-bit), MSVC 2003, 2005 (32 and 64-bit) + \o gcc 4.4 (MinGW) (32-bit), MSVC 2005 (32 and 64-bit) \row \o Microsoft Windows Vista \o MSVC 2005, 2008 \row \o Microsoft Windows Vista 64bit \o MSVC 2008 - \row \o Apple Mac OS X 10.5 "Leopard" x86_64 (Carbon, Cocoa 32 and 64bit) + \row \o Microsoft Windows 7 + \o MSVC 2008 + \row \o Apple Mac OS X 10.6 "Snow Leopard" + \o As provided by Apple + \row \o Apple Mac OS X 10.5 "Leopard" x86_64 (Cocoa 32 and 64bit) \o As provided by Apple \row \o Embedded Linux QWS (ARM) \o gcc (\l{http://www.codesourcery.com/}{Codesourcery version)} \row \o Windows CE 5.0 (ARMv4i, x86, MIPS) \o MSVC 2005 WinCE 5.0 Standard (x86, pocket, smart, mipsii) - \row \o Symbian (Symbian/S60 3.1, 3.2 and 5.0) + \row \o Symbian (Symbian/S60 5.0) \o RVCT 2.2 [build 686 or later], WINSCW 3.2.5 [build 482 or later], GCCE (for applications) \endtable @@ -90,19 +94,15 @@ \table \header \o Platform \o Compilers - \row \o Windows XP, Vista - \o gcc 3.4.2 (MinGW) \row \o Windows 7 - \o MSVC 2008 - \row \o Apple Mac OS X 10.6 "Snow Leopard" + \o MSVC 2010 + \row \o Apple Mac OS X 10.4 "Tiger" (Carbon) \o As provided by Apple - \row \o Apple Mac OS X 10.4 "Tiger" + \row \o Apple Mac OS X 10.5 "Leopard" (Carbon) \o As provided by Apple - \row \o HPUXi 11.11 - \o aCC 3.57, gcc 3.4 \row \o HPUXi 11.23 \o aCC 6.10 - \row \o Solaris 10 (UltraSparc, x86) + \row \o Solaris 10 UltraSparc \o Sun Studio 12 \row \o AIX 6 \o Power5 xlC 7 @@ -114,8 +114,14 @@ \o gcc (\l{http://www.codesourcery.com/}{Codesourcery version)} \row \o Embedded Linux X11 (ARM) \o gcc (\l{http://www.scratchbox.org/}{Scratchbox)} + \row \o Windows CE 5.0 (ARMv4i, x86, MIPS) + \o MSVC 2005 WinCE 5.0 Standard (x86, pocket, smart, mipsii) \row \o Windows CE 6.0 (ARMv4i, x86, MIPS) \o MSVC 2008 WinCE 6.0 Professional + \row \o Maemo 5(Linux, ARM, X11) + \o gcc (\l{http://www.scratchbox.org/}{Scratchbox)} + \row \o Symbian (Symbian/S60 3.1, 3.2) + \o RVCT 2.2 [build 686 or later], WINSCW 3.2.5 [build 482 or later], GCCE (for applications) \endtable \section1 Tier 3 Platforms (Not supported by Nokia) @@ -142,20 +148,12 @@ implied warranties of merchantability, fitness for a particular purpose, title and non-infringement with regard to the Licensed Software. - \section1 Planned Changes for Qt 4.7 + \section1 Planned Changes for Qt 4.8 The following changes to the list of supported platforms are at time of publishing - planned for Qt 4.7: + planned for Qt 4.8: \list - \o Upgrade Windows 7 to Tier 1 - \o Upgrade Mac OS X 10.6 to Tier 1 - \o Add support for Visual Studio 2010 (Tier 2) - \o Move support for Carbon implementation of Qt on Mac OS X from Tier 1 to Tier 2 - \o Drop support for MinGW 3.4 - \o Drop support for Visual Studio 2003 - \o Drop support for HP-UX on PA-RISC - \o Drop support for Windows Mobile 5 - \o Drop support for OpenGL ES Common Lite 1.0 + \o Plans not yet released \endlist */ -- cgit v0.12 From 9d88ff485e93e9701719263ce0a46cb86b0398ca Mon Sep 17 00:00:00 2001 From: Gareth Stockwell Date: Thu, 2 Sep 2010 13:03:50 +0100 Subject: Prevent null pointer dereference Task-number: QTBUG-13204 Reviewed-by: axis --- src/gui/kernel/qapplication_s60.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/kernel/qapplication_s60.cpp b/src/gui/kernel/qapplication_s60.cpp index 4ed4ba3..21f930e 100644 --- a/src/gui/kernel/qapplication_s60.cpp +++ b/src/gui/kernel/qapplication_s60.cpp @@ -129,7 +129,7 @@ void QS60Data::setStatusPaneAndButtonGroupVisibility(bool statusPaneVisible, boo statusPaneVisibilityChanged = (s->IsVisible() != statusPaneVisible); s->MakeVisible(statusPaneVisible); } - if (buttonGroupVisibilityChanged && !statusPaneVisibilityChanged) + if (buttonGroupVisibilityChanged && !statusPaneVisibilityChanged && QApplication::activeWindow()) // Ensure that control rectangle is updated static_cast(QApplication::activeWindow()->winId())->handleClientAreaChange(); } -- cgit v0.12 From 55b067d14d8c12bd29b03c17e0281a11a49f95ca Mon Sep 17 00:00:00 2001 From: Gareth Stockwell Date: Thu, 2 Sep 2010 13:07:59 +0100 Subject: Update QDesktopWidget geometry when S60 furniture visibility changes Task-number: QTBUG-13204 Reviewed-by: axis --- src/gui/kernel/qapplication_s60.cpp | 6 ++++++ src/gui/kernel/qwidget_s60.cpp | 6 ++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/gui/kernel/qapplication_s60.cpp b/src/gui/kernel/qapplication_s60.cpp index 21f930e..e937918 100644 --- a/src/gui/kernel/qapplication_s60.cpp +++ b/src/gui/kernel/qapplication_s60.cpp @@ -129,6 +129,12 @@ void QS60Data::setStatusPaneAndButtonGroupVisibility(bool statusPaneVisible, boo statusPaneVisibilityChanged = (s->IsVisible() != statusPaneVisible); s->MakeVisible(statusPaneVisible); } + if (buttonGroupVisibilityChanged || statusPaneVisibilityChanged) { + const QSize size = qt_TRect2QRect(static_cast(S60->appUi())->ClientRect()).size(); + const QSize oldSize; // note that QDesktopWidget::resizeEvent ignores the QResizeEvent contents + QResizeEvent event(size, oldSize); + QApplication::instance()->sendEvent(QApplication::desktop(), &event); + } if (buttonGroupVisibilityChanged && !statusPaneVisibilityChanged && QApplication::activeWindow()) // Ensure that control rectangle is updated static_cast(QApplication::activeWindow()->winId())->handleClientAreaChange(); diff --git a/src/gui/kernel/qwidget_s60.cpp b/src/gui/kernel/qwidget_s60.cpp index fc13c93..c98c05a 100644 --- a/src/gui/kernel/qwidget_s60.cpp +++ b/src/gui/kernel/qwidget_s60.cpp @@ -503,8 +503,10 @@ void QWidgetPrivate::show_sys() // Can't use AppUi directly because it privately inherits from MEikStatusPaneObserver. QSymbianControl *desktopControl = static_cast(QApplication::desktop()->winId()); S60->statusPane()->SetObserver(desktopControl); - if (isFullscreen) - S60->statusPane()->MakeVisible(false); + if (isFullscreen) { + const bool cbaVisible = S60->buttonGroupContainer() && S60->buttonGroupContainer()->IsVisible(); + S60->setStatusPaneAndButtonGroupVisibility(false, cbaVisible); + } } } } -- cgit v0.12 From f8c789a70ee3061dd81307ead82c47bb0f8041d5 Mon Sep 17 00:00:00 2001 From: Jani Hautakangas Date: Thu, 2 Sep 2010 15:30:37 +0300 Subject: Document known limitations in UI performance on S60 5.0 based devices. Task-number: QTBUG-11333 Reviewed-by: axis --- doc/src/images/symbian-draw-pixmap-sequence.png | Bin 0 -> 5724 bytes doc/src/images/symbian-qt-draw-pixmap-sequence.png | Bin 0 -> 9141 bytes .../symbian-qt-rendering-stack-non-screenplay.png | Bin 0 -> 52802 bytes .../symbian-rendering-stack-non-screenplay.png | Bin 0 -> 44655 bytes doc/src/platforms/platform-notes.qdoc | 50 +++++++++++++++++++++ 5 files changed, 50 insertions(+) create mode 100644 doc/src/images/symbian-draw-pixmap-sequence.png create mode 100644 doc/src/images/symbian-qt-draw-pixmap-sequence.png create mode 100644 doc/src/images/symbian-qt-rendering-stack-non-screenplay.png create mode 100644 doc/src/images/symbian-rendering-stack-non-screenplay.png diff --git a/doc/src/images/symbian-draw-pixmap-sequence.png b/doc/src/images/symbian-draw-pixmap-sequence.png new file mode 100644 index 0000000..05e3739 Binary files /dev/null and b/doc/src/images/symbian-draw-pixmap-sequence.png differ diff --git a/doc/src/images/symbian-qt-draw-pixmap-sequence.png b/doc/src/images/symbian-qt-draw-pixmap-sequence.png new file mode 100644 index 0000000..f7546f4 Binary files /dev/null and b/doc/src/images/symbian-qt-draw-pixmap-sequence.png differ diff --git a/doc/src/images/symbian-qt-rendering-stack-non-screenplay.png b/doc/src/images/symbian-qt-rendering-stack-non-screenplay.png new file mode 100644 index 0000000..9e1997d Binary files /dev/null and b/doc/src/images/symbian-qt-rendering-stack-non-screenplay.png differ diff --git a/doc/src/images/symbian-rendering-stack-non-screenplay.png b/doc/src/images/symbian-rendering-stack-non-screenplay.png new file mode 100644 index 0000000..80cb078 Binary files /dev/null and b/doc/src/images/symbian-rendering-stack-non-screenplay.png differ diff --git a/doc/src/platforms/platform-notes.qdoc b/doc/src/platforms/platform-notes.qdoc index 94b9856..6f533ae 100644 --- a/doc/src/platforms/platform-notes.qdoc +++ b/doc/src/platforms/platform-notes.qdoc @@ -526,6 +526,56 @@ platform in use. If available, it is loaded in preference over the MMF plugin. If the Helix plugin fails to load, the MMF plugin, if present on the device, will be loaded instead. + + \section1 UI Performance in devices prior to Symbian^3 + + Qt uses the QPainter class to perform low-level painting on widgets and + other paint devices. QPainter provides functions to draw complex shapes, + aligned text and pixmaps. It can also do vector path clipping, coordinate + transformations and Porter-Duff composition. If the underlying graphics + architecture does not support all of these operations then Qt uses the + raster graphics system for rendering. + + Most of the Symbian devices prior to Symbian^3 use a non-ScreenPlay + graphics architecture which does not have native support for all functions + provided by QPainter. In non-ScreenPlay devices Qt uses the raster + graphics system by default which has a performance penalty when compared + to native Symbian rendering. + + In order to be able to perform all functions provided by QPainter, the + raster graphics system needs to have pixel level framebuffer access. To + make this possible in non-ScreenPlay devices Qt has to create an + additional offscreen buffer that is the target for all Qt rendering + operations. Qt renders the widget tree to the offscreen buffer and the + offscreen buffer is blitted to the framebuffer via Symbian Window Server. + + The following table shows the rendering stacks of native Symbian and Qt in + non-ScreenPlay devices. + + \table + \header \o Symbian + \o Qt + \row \o \image symbian-rendering-stack-non-screenplay.png + \o \image symbian-qt-rendering-stack-non-screenplay.png + \endtable + + The following diagrams show a simplified sequence of drawing a pixmap in + a non-ScreenPlay device. + + \table + \header \o Symbian + \row \o \image symbian-draw-pixmap-sequence.png + \endtable + + \table + \header \o Qt + \row \o \image symbian-qt-draw-pixmap-sequence.png + \endtable + + When compared to a native Symbian application, Qt does an additional blit + to the offscreen buffer before drawing to the framebuffer. That is the + performance penalty which needs to be paid to get all functionality + provided by QPainter in non-ScreenPlay architecture. */ /*! -- cgit v0.12 From 0d54ade501443d8a3b0e756520f6c43e602f1283 Mon Sep 17 00:00:00 2001 From: David Boddie Date: Thu, 2 Sep 2010 15:41:38 +0200 Subject: Doc: Changed the default URL to avoid a Flash plugin crash on x86-64. Reviewed-by: Kevin Wright --- demos/browser/settings.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demos/browser/settings.cpp b/demos/browser/settings.cpp index 5ceca67..fba781b 100644 --- a/demos/browser/settings.cpp +++ b/demos/browser/settings.cpp @@ -89,7 +89,7 @@ void SettingsDialog::loadFromSettings() { QSettings settings; settings.beginGroup(QLatin1String("MainWindow")); - QString defaultHome = QLatin1String("http://qt.nokia.com"); + QString defaultHome = QLatin1String("http://doc.qt.nokia.com"); homeLineEdit->setText(settings.value(QLatin1String("home"), defaultHome).toString()); settings.endGroup(); -- cgit v0.12 From 03b7a3cffba609df56b4ccadacae6b6f985e96e9 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Thu, 2 Sep 2010 14:33:26 +0200 Subject: Reduce memory consumption of QtScript/JSC on Symbian Backport of Jay's patch from https://bugs.webkit.org/show_bug.cgi?id=34349 with minor modifications. Even though the original patch was rejected upstream and has been superseded by the patches for https://bugs.webkit.org/show_bug.cgi?id=43185, those patches are more involved (affecting all platforms), hence difficult/risky to backport. Task-number: QTBUG-13361 Reviewed-by: Simon Hausmann --- .../javascriptcore/JavaScriptCore/ChangeLog | 36 +++++++ .../JavaScriptCore/JavaScriptCore.pri | 1 + .../JavaScriptCore/interpreter/RegisterFile.cpp | 2 + .../JavaScriptCore/interpreter/RegisterFile.h | 33 +++++- .../wtf/symbian/RegisterFileAllocatorSymbian.cpp | 111 +++++++++++++++++++++ .../wtf/symbian/RegisterFileAllocatorSymbian.h | 69 +++++++++++++ .../JavaScriptCore/wtf/symbian/SymbianDefines.h | 42 ++++++++ src/script/script.pro | 5 +- 8 files changed, 295 insertions(+), 4 deletions(-) create mode 100644 src/3rdparty/javascriptcore/JavaScriptCore/wtf/symbian/RegisterFileAllocatorSymbian.cpp create mode 100644 src/3rdparty/javascriptcore/JavaScriptCore/wtf/symbian/RegisterFileAllocatorSymbian.h create mode 100644 src/3rdparty/javascriptcore/JavaScriptCore/wtf/symbian/SymbianDefines.h diff --git a/src/3rdparty/javascriptcore/JavaScriptCore/ChangeLog b/src/3rdparty/javascriptcore/JavaScriptCore/ChangeLog index 93431df..fbaf5d2 100644 --- a/src/3rdparty/javascriptcore/JavaScriptCore/ChangeLog +++ b/src/3rdparty/javascriptcore/JavaScriptCore/ChangeLog @@ -1,3 +1,39 @@ +2010-06-18 Tucker Jay + + Reviewed by NOBODY (OOPS!). + + [Symbian] Lazy commit of memory required in JSC register file + https://bugs.webkit.org/show_bug.cgi?id=34349 + + * JavaScriptCore.pro: Added 1 new Symbian source file + * interpreter/RegisterFile.cpp: + (JSC::RegisterFile::~RegisterFile): + * interpreter/RegisterFile.h: + (JSC::RegisterFile::): + (JSC::RegisterFile::start): + (JSC::RegisterFile::end): + (JSC::RegisterFile::size): + (JSC::RegisterFile::setNumGlobals): + (JSC::RegisterFile::numGlobals): + (JSC::RegisterFile::maxGlobals): + (JSC::RegisterFile::lastGlobal): + (JSC::RegisterFile::markGlobals): + (JSC::RegisterFile::markCallFrames): + (JSC::isPageAligned): + (JSC::RegisterFile::RegisterFile): + (JSC::RegisterFile::shrink): + (JSC::RegisterFile::grow): + * wtf/symbian/RegisterFileAllocatorSymbian.cpp: Added. + (WTF::RegisterFileAllocator::RegisterFileAllocator): + Helper class to allocate memory required by RegisterFile + more efficiently. + (WTF::RegisterFileAllocator::~RegisterFileAllocator): + (WTF::RegisterFileAllocator::buffer): + (WTF::RegisterFileAllocator::grow): + (WTF::RegisterFileAllocator::shrink): + * wtf/symbian/RegisterFileAllocatorSymbian.h: Added. + * wtf/symbian/SymbianDefines.h: Added. + 2010-06-19 Thiago Macieira Reviewed by Kenneth Rohde Christiansen. diff --git a/src/3rdparty/javascriptcore/JavaScriptCore/JavaScriptCore.pri b/src/3rdparty/javascriptcore/JavaScriptCore/JavaScriptCore.pri index 75737ae..d75bd31 100644 --- a/src/3rdparty/javascriptcore/JavaScriptCore/JavaScriptCore.pri +++ b/src/3rdparty/javascriptcore/JavaScriptCore/JavaScriptCore.pri @@ -211,6 +211,7 @@ SOURCES += \ wtf/qt/ThreadingQt.cpp \ wtf/RandomNumber.cpp \ wtf/RefCountedLeakCounter.cpp \ + wtf/symbian/RegisterFileAllocatorSymbian.cpp \ wtf/ThreadingNone.cpp \ wtf/Threading.cpp \ wtf/TypeTraits.cpp \ diff --git a/src/3rdparty/javascriptcore/JavaScriptCore/interpreter/RegisterFile.cpp b/src/3rdparty/javascriptcore/JavaScriptCore/interpreter/RegisterFile.cpp index 939573b..293fc38 100644 --- a/src/3rdparty/javascriptcore/JavaScriptCore/interpreter/RegisterFile.cpp +++ b/src/3rdparty/javascriptcore/JavaScriptCore/interpreter/RegisterFile.cpp @@ -40,6 +40,8 @@ RegisterFile::~RegisterFile() VirtualFree(m_buffer, DWORD(m_commitEnd) - DWORD(m_buffer), MEM_DECOMMIT); #endif VirtualFree(m_buffer, 0, MEM_RELEASE); +#elif OS(SYMBIAN) + delete m_registerFileAllocator; #else fastFree(m_buffer); #endif diff --git a/src/3rdparty/javascriptcore/JavaScriptCore/interpreter/RegisterFile.h b/src/3rdparty/javascriptcore/JavaScriptCore/interpreter/RegisterFile.h index 34e2504..49304d9 100644 --- a/src/3rdparty/javascriptcore/JavaScriptCore/interpreter/RegisterFile.h +++ b/src/3rdparty/javascriptcore/JavaScriptCore/interpreter/RegisterFile.h @@ -41,6 +41,10 @@ #include #endif +#if OS(SYMBIAN) +#include +#endif + namespace JSC { /* @@ -152,12 +156,21 @@ namespace JSC { #if HAVE(VIRTUALALLOC) Register* m_commitEnd; #endif +#if OS(SYMBIAN) + // Commits and frees a continguous chunk of memory as required + WTF::RegisterFileAllocator* m_registerFileAllocator; +#endif JSGlobalObject* m_globalObject; // The global object whose vars are currently stored in the register file. }; // FIXME: Add a generic getpagesize() to WTF, then move this function to WTF as well. - inline bool isPageAligned(size_t size) { return size != 0 && size % (8 * 1024) == 0; } + // This is still a hack that should be fixed later. We know that a Symbian page size is 4K. + #if OS(SYMBIAN) + inline bool isPageAligned(size_t size) { return size && !(size % (4 * 1024)); } + #else + inline bool isPageAligned(size_t size) { return size && !(size % (8 * 1024)); } + #endif inline RegisterFile::RegisterFile(size_t capacity, size_t maxGlobals) : m_numGlobals(0) @@ -204,7 +217,13 @@ namespace JSC { CRASH(); } m_commitEnd = reinterpret_cast(reinterpret_cast(m_buffer) + committedSize); - #else + #elif OS(SYMBIAN) + m_registerFileAllocator = new WTF::RegisterFileAllocator(bufferLength); + m_buffer = (Register*)(m_registerFileAllocator->buffer()); + // start by committing enough space to hold maxGlobals + void* newEnd = (void*)((int)m_buffer + (maxGlobals * sizeof(Register))); + m_registerFileAllocator->grow(newEnd); + #else /* * If neither MMAP nor VIRTUALALLOC are available - use fastMalloc instead. * @@ -226,8 +245,13 @@ namespace JSC { if (newEnd >= m_end) return; m_end = newEnd; - if (m_end == m_start && (m_maxUsed - m_start) > maxExcessCapacity) + if (m_end == m_start && (m_maxUsed - m_start) > maxExcessCapacity) { +#if OS(SYMBIAN) + m_registerFileAllocator->shrink(newEnd); +#endif + releaseExcessCapacity(); + } } inline bool RegisterFile::grow(Register* newEnd) @@ -252,6 +276,9 @@ namespace JSC { m_commitEnd = reinterpret_cast(reinterpret_cast(m_commitEnd) + size); } #endif +#if OS(SYMBIAN) + m_registerFileAllocator->grow((void*)newEnd); +#endif if (newEnd > m_maxUsed) m_maxUsed = newEnd; diff --git a/src/3rdparty/javascriptcore/JavaScriptCore/wtf/symbian/RegisterFileAllocatorSymbian.cpp b/src/3rdparty/javascriptcore/JavaScriptCore/wtf/symbian/RegisterFileAllocatorSymbian.cpp new file mode 100644 index 0000000..baa7841 --- /dev/null +++ b/src/3rdparty/javascriptcore/JavaScriptCore/wtf/symbian/RegisterFileAllocatorSymbian.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies) + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#if OS(SYMBIAN) + +#include "RegisterFileAllocatorSymbian.h" + +namespace WTF { + +/** Efficiently allocates memory pools of size poolSize. + * Primarily designed for JSC RegisterFile's needs. + * Not thread-safe. + */ +RegisterFileAllocator::RegisterFileAllocator(TUint32 reservationSize, TUint32 poolSize) : + m_reserved(reservationSize), m_poolSize(poolSize) +{ + // Get system's page size value. + SYMBIAN_PAGESIZE(m_pageSize); + + // We only accept multiples of system page size for both initial reservation + // and the alignment/pool size + m_reserved = SYMBIAN_ROUNDUPTOMULTIPLE(m_reserved, m_pageSize); + __ASSERT_ALWAYS(SYMBIAN_ROUNDUPTOMULTIPLE(m_poolSize, m_pageSize), + User::Panic(_L("RegisterFileAllocator1"), KErrArgument)); + + // Open a Symbian RChunk, and reserve requested virtual address range + // Any thread in this process can operate this RChunk due to EOwnerProcess access rights. + TInt ret = m_chunk.CreateDisconnectedLocal(0 , 0, (TInt)m_reserved , EOwnerProcess); + if (ret != KErrNone) + User::Panic(_L("RegisterFileAllocator2"), ret); + + m_buffer = (void*)m_chunk.Base(); + m_resEnd = (void*)(m_chunk.Base() + m_chunk.MaxSize()); + m_comEnd = m_buffer; +} + +RegisterFileAllocator::~RegisterFileAllocator() +{ + // release everything! + m_chunk.Decommit(0, m_chunk.MaxSize()); + m_chunk.Close(); +} + +void* RegisterFileAllocator::buffer() const +{ + return m_buffer; +} + +void RegisterFileAllocator::grow(void* newEnd) +{ + // trying to commit more memory than reserved! + if (newEnd > m_resEnd) + return; + + if (newEnd > m_comEnd) { + TInt nBytes = (TInt)(newEnd) - (TInt)(m_comEnd); + nBytes = SYMBIAN_ROUNDUPTOMULTIPLE(nBytes, m_poolSize); + TInt offset = (TInt)m_comEnd - (TInt)m_buffer; + + TInt ret = m_chunk.Commit(offset, nBytes); + if (ret == KErrNone) + m_comEnd = (void*)(m_chunk.Base() + m_chunk.Size()); + } +} + +void RegisterFileAllocator::shrink(void* newEnd) +{ + if (newEnd < m_comEnd) { + TInt nBytes = (TInt)newEnd - (TInt)m_comEnd; + if (nBytes >= m_poolSize) { + TInt offset = SYMBIAN_ROUNDUPTOMULTIPLE((TUint)newEnd, m_poolSize) - (TInt)m_buffer; + nBytes = (TInt)m_comEnd - offset - (TInt)m_buffer; + if (nBytes > 0) { + TInt ret = m_chunk.Decommit(offset, nBytes); + if (ret == KErrNone) + m_comEnd = (void*)(m_chunk.Base() + m_chunk.Size()); + } + } + } +} + +} // end of namespace + +#endif // SYMBIAN diff --git a/src/3rdparty/javascriptcore/JavaScriptCore/wtf/symbian/RegisterFileAllocatorSymbian.h b/src/3rdparty/javascriptcore/JavaScriptCore/wtf/symbian/RegisterFileAllocatorSymbian.h new file mode 100644 index 0000000..4cfc8c5 --- /dev/null +++ b/src/3rdparty/javascriptcore/JavaScriptCore/wtf/symbian/RegisterFileAllocatorSymbian.h @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies) + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RegisterFileAllocatorSymbian_h +#define RegisterFileAllocatorSymbian_h + +#include "SymbianDefines.h" + +namespace WTF { + +/** + * Allocates contiguous regions of size poolSize. + * poolSize must be a multiple of system page size (typically 4K on Symbian/ARM) + * + * @param reservationSize Virtual address range to be reserved upon creation of chunk (bytes). + * @param poolSize Size of a single allocation. + */ +class RegisterFileAllocator { + +public: + RegisterFileAllocator( + TUint32 reservationSize, TUint32 poolSize = SYMBIAN_REGFILEALLOC_DEFAULTPOOLSIZE); + ~RegisterFileAllocator(); + void* buffer() const; + void grow(void* newEnd); + void shrink(void* newEnd); + +private: + RChunk m_chunk; // Symbian chunk that lets us reserve/commit/decommit + + // all following values are in numbers of bytes + TInt m_pageSize; // cached value of system page size, typically 4K on Symbian + TUint32 m_reserved; // total number of reserved bytes in virtual memory + TUint32 m_poolSize; // size of one memory pool, set by default to 64K in wtf/symbian/SymbianDefines.h + + void* m_buffer; // pointer to base of the chunk + void* m_comEnd; // pointer to end of currently committed memory + void* m_resEnd; // pointer to end of reserved memory + +}; + +} // end of namespace + +#endif // RegisterFileAllocatorSymbian_h diff --git a/src/3rdparty/javascriptcore/JavaScriptCore/wtf/symbian/SymbianDefines.h b/src/3rdparty/javascriptcore/JavaScriptCore/wtf/symbian/SymbianDefines.h new file mode 100644 index 0000000..43e22b3 --- /dev/null +++ b/src/3rdparty/javascriptcore/JavaScriptCore/wtf/symbian/SymbianDefines.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies) + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef SymbianDefines_h +#define SymbianDefines_h + +#include +#include +#include + +#define SYMBIAN_PAGESIZE(x) (HAL::Get(HALData::EMemoryPageSize, x)); +#define SYMBIAN_FREERAM(x) (HAL::Get(HALData::EMemoryRAMFree, x)); +#define SYMBIAN_ROUNDUPTOMULTIPLE(x, multipleof) ( (x + multipleof - 1) & ~(multipleof - 1) ) + +#define SYMBIAN_REGFILEALLOC_DEFAULTPOOLSIZE 65536 // 64K + +#endif // SymbianDefines_h diff --git a/src/script/script.pro b/src/script/script.pro index 55217e0..4ee86d7 100644 --- a/src/script/script.pro +++ b/src/script/script.pro @@ -79,7 +79,10 @@ INCLUDEPATH += $$PWD include(script.pri) -symbian:TARGET.UID3=0x2001B2E1 +symbian { + TARGET.UID3=0x2001B2E1 + LIBS += -lhal +} # WebKit doesn't compile in C++0x mode *-g++*:QMAKE_CXXFLAGS -= -std=c++0x -std=gnu++0x -- cgit v0.12 From efe67ac8c1c59fd4cf8c793b549169f4e2926ac8 Mon Sep 17 00:00:00 2001 From: axis Date: Thu, 2 Sep 2010 15:40:38 +0200 Subject: Fixed a bug where passwords would not be committed when confirming. The bug happened when you were typing a password and pressing "Done" softkey very quickly. Because of the temporarily visible character, the widget would not contain the full string at the time of softkey triggering, only the *** part. Fixed by having the input context listen for softkey (command) events and commit the temporary character before the softkey action is triggered. AutoTest: Included Task: QTBUG-12949 RevBy: Miikka Heikkinen --- src/gui/inputmethod/qcoefepinputcontext_p.h | 1 + src/gui/inputmethod/qcoefepinputcontext_s60.cpp | 13 +++ tests/auto/qinputcontext/tst_qinputcontext.cpp | 124 ++++++++++++++++++++++++ 3 files changed, 138 insertions(+) diff --git a/src/gui/inputmethod/qcoefepinputcontext_p.h b/src/gui/inputmethod/qcoefepinputcontext_p.h index 2fd6d16..ac40bba 100644 --- a/src/gui/inputmethod/qcoefepinputcontext_p.h +++ b/src/gui/inputmethod/qcoefepinputcontext_p.h @@ -84,6 +84,7 @@ public: void update(); bool filterEvent(const QEvent *event); + bool symbianFilterEvent(QWidget *keyWidget, const QSymbianEvent *event); void mouseHandler( int x, QMouseEvent *event); bool isComposing() const { return !m_preeditString.isEmpty(); } diff --git a/src/gui/inputmethod/qcoefepinputcontext_s60.cpp b/src/gui/inputmethod/qcoefepinputcontext_s60.cpp index add3d17..abcec32 100644 --- a/src/gui/inputmethod/qcoefepinputcontext_s60.cpp +++ b/src/gui/inputmethod/qcoefepinputcontext_s60.cpp @@ -47,6 +47,7 @@ #include #include #include +#include #include #include @@ -287,6 +288,18 @@ bool QCoeFepInputContext::filterEvent(const QEvent *event) return false; } +bool QCoeFepInputContext::symbianFilterEvent(QWidget *keyWidget, const QSymbianEvent *event) +{ + Q_UNUSED(keyWidget); + if (event->type() == QSymbianEvent::CommandEvent) + // A command basically means the same as a button being pushed. With Qt buttons + // that would normally result in a reset of the input method due to the focus change. + // This should also happen for commands. + reset(); + + return false; +} + void QCoeFepInputContext::timerEvent(QTimerEvent *timerEvent) { if (timerEvent->timerId() == m_tempPreeditStringTimeout.timerId()) diff --git a/tests/auto/qinputcontext/tst_qinputcontext.cpp b/tests/auto/qinputcontext/tst_qinputcontext.cpp index 93813f9..52e655b 100644 --- a/tests/auto/qinputcontext/tst_qinputcontext.cpp +++ b/tests/auto/qinputcontext/tst_qinputcontext.cpp @@ -49,6 +49,7 @@ #include #include #include +#include #ifdef Q_OS_SYMBIAN #include @@ -80,6 +81,8 @@ private slots: void focusProxy(); void symbianTestCoeFepInputContext_data(); void symbianTestCoeFepInputContext(); + void symbianTestCoeFepAutoCommit_data(); + void symbianTestCoeFepAutoCommit(); private: bool m_phoneIsQwerty; @@ -936,5 +939,126 @@ void tst_QInputContext::symbianTestCoeFepInputContext() #endif } +void tst_QInputContext::symbianTestCoeFepAutoCommit_data() +{ +#ifdef Q_OS_SYMBIAN + QTest::addColumn ("inputMethodHints"); + QTest::addColumn ("echoMode"); + QTest::addColumn > ("keyEvents"); + QTest::addColumn ("finalString"); + + QList events; + + events << FepReplayEvent('4', '4', 0, 0); + events << FepReplayEvent('4', '4', 0, 0); + events << FepReplayEvent('0', '0', 0, 0); + events << FepReplayEvent('9', '9', 0, 0); + events << FepReplayEvent('6', '6', 0, 0); + events << FepReplayEvent('8', '8', 0, 0); + QTest::newRow("Numbers") + << Qt::InputMethodHints(Qt::ImhDigitsOnly) + << QLineEdit::Normal + << events + << QString("440968"); + QTest::newRow("Numbers and password") + << Qt::InputMethodHints(Qt::ImhDigitsOnly) + << QLineEdit::Password + << events + << QString("440968"); + QTest::newRow("Multitap") + << Qt::InputMethodHints(Qt::ImhPreferLowercase | Qt::ImhNoPredictiveText) + << QLineEdit::Normal + << events + << QString("h wmt"); + QTest::newRow("T9") + << Qt::InputMethodHints(Qt::ImhPreferLowercase) + << QLineEdit::Normal + << events + << QString("hi you"); + QTest::newRow("Multitap with password") + << Qt::InputMethodHints(Qt::ImhPreferLowercase | Qt::ImhNoPredictiveText) + << QLineEdit::Password + << events + << QString("h wmt"); + QTest::newRow("T9 with password") + << Qt::InputMethodHints(Qt::ImhPreferLowercase) + << QLineEdit::Password + << events + << QString("h wmt"); +#endif +} + +void tst_QInputContext::symbianTestCoeFepAutoCommit() +{ +#ifndef Q_OS_SYMBIAN + QSKIP("This is a Symbian-only test", SkipAll); +#else + QCoeFepInputContext *ic = qobject_cast(qApp->inputContext()); + if (!ic) { + QSKIP("coefep is not the active input context; skipping test", SkipAll); + } + + QFETCH(Qt::InputMethodHints, inputMethodHints); + QFETCH(QLineEdit::EchoMode, echoMode); + QFETCH(QList, keyEvents); + QFETCH(QString, finalString); + + if (m_phoneIsQwerty) { + QSKIP("Skipping advanced input method tests on QWERTY phones", SkipSingle); + } + + QWidget w; + QLayout *layout = new QVBoxLayout; + w.setLayout(layout); + QLineEdit *lineedit = new QLineEdit; + layout->addWidget(lineedit); + lineedit->setFocus(); +#ifdef QT_KEYPAD_NAVIGATION + lineedit->setEditFocus(true); +#endif + QPushButton *pushButton = new QPushButton("Done"); + layout->addWidget(pushButton); + QAction softkey("Done", &w); + softkey.setSoftKeyRole(QAction::PositiveSoftKey); + w.addAction(&softkey); + w.show(); + + lineedit->setInputMethodHints(inputMethodHints); + lineedit->setEchoMode(echoMode); + + QTest::qWait(200); + foreach(FepReplayEvent event, keyEvents) { + event.replay(lineedit); + } + QApplication::processEvents(); + + QTest::mouseClick(pushButton, Qt::LeftButton); + + QCOMPARE(lineedit->text(), finalString); + QVERIFY(ic->m_preeditString.isEmpty()); + +#ifdef Q_WS_S60 + lineedit->inputContext()->reset(); + lineedit->clear(); + lineedit->setFocus(); +#ifdef QT_KEYPAD_NAVIGATION + lineedit->setEditFocus(true); +#endif + + QTest::qWait(200); + foreach(FepReplayEvent event, keyEvents) { + event.replay(lineedit); + } + QApplication::processEvents(); + + FepReplayEvent(EStdKeyDevice0, EKeyDevice0, 0, 0).replay(lineedit); // Left softkey + + QCOMPARE(lineedit->text(), finalString); + QVERIFY(ic->m_preeditString.isEmpty()); + +#endif // Q_WS_S60 +#endif // Q_OS_SYMBIAN +} + QTEST_MAIN(tst_QInputContext) #include "tst_qinputcontext.moc" -- cgit v0.12 From 5afd02d13fca42d556e03579a5ed4eb53d2eb172 Mon Sep 17 00:00:00 2001 From: axis Date: Thu, 2 Sep 2010 16:09:17 +0200 Subject: Fixed a few warnings. --- src/gui/inputmethod/qcoefepinputcontext_s60.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/gui/inputmethod/qcoefepinputcontext_s60.cpp b/src/gui/inputmethod/qcoefepinputcontext_s60.cpp index abcec32..b08b9a9 100644 --- a/src/gui/inputmethod/qcoefepinputcontext_s60.cpp +++ b/src/gui/inputmethod/qcoefepinputcontext_s60.cpp @@ -664,7 +664,7 @@ void QCoeFepInputContext::UpdateFepInlineTextL(const TDesC& aNewInlineText, QInputMethodEvent event(newPreeditString, attributes); if (newPreeditString.isEmpty() && m_preeditString.isEmpty()) { // In Symbian world this means "erase last character". - event.setCommitString("", -1, 1); + event.setCommitString(QLatin1String(""), -1, 1); } m_preeditString = newPreeditString; sendEvent(event); @@ -836,8 +836,6 @@ void QCoeFepInputContext::DoCommitFepInlineEditL() void QCoeFepInputContext::commitCurrentString(bool cancelFepTransaction) { - int longPress = 0; - QList attributes; QInputMethodEvent event(QLatin1String(""), attributes); event.setCommitString(m_preeditString, 0, 0); -- cgit v0.12 From 71a3b1a0d3ee6429832bdbf0da026cdc3f74080f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tor=20Arne=20Vestb=C3=B8?= Date: Thu, 2 Sep 2010 15:18:31 +0200 Subject: Ensure that OpenGL contexts are attached to an NSView before first paint MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Attaching an OpenGL context to an NSView too soon will result in an error "invalid drawable" printed on the console. We used to guard against this by checking the visible property of the NSWindow, but this turned out to be too late, as we had already recived an initial paint event by then as part of showing the window. The visual result was a single frame of gray painted before the user's paint event code took effect. We solve this by hooking into setInitialFirstResponder on the NSWindow, which is called as part of making the window visible for the first time. At this point it's safe to attach the GL context to the NSView, so we iterate all the GLWidget children of the top level window and make sure the context is attached by sending a MacGLWindowChange event. The check in qt_mac_update_child_gl_widgets() for a top level window had to be removed for this approach to work, but should be okey as we're only iterating the children. Reviewed-by: Richard Moe Gustavsen Reviewed-by: Trond Kjernåsen --- src/gui/kernel/qapplication_mac.mm | 3 --- src/gui/kernel/qcocoasharedwindowmethods_mac_p.h | 13 +++++++++++++ src/opengl/qgl_mac.mm | 14 +++++++++++--- 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/gui/kernel/qapplication_mac.mm b/src/gui/kernel/qapplication_mac.mm index 321492d..dd819e5 100644 --- a/src/gui/kernel/qapplication_mac.mm +++ b/src/gui/kernel/qapplication_mac.mm @@ -737,9 +737,6 @@ static void qt_post_window_change_event(QWidget *widget) */ static void qt_mac_update_child_gl_widgets(QWidget *widget) { - if (widget->isWindow()) - return; - // Update all OpenGL child widgets for the given widget. QList &glWidgets = qt_widget_private(widget)->glWidgets; QList::iterator end = glWidgets.end(); diff --git a/src/gui/kernel/qcocoasharedwindowmethods_mac_p.h b/src/gui/kernel/qcocoasharedwindowmethods_mac_p.h index 6795149..16f5bd6 100644 --- a/src/gui/kernel/qcocoasharedwindowmethods_mac_p.h +++ b/src/gui/kernel/qcocoasharedwindowmethods_mac_p.h @@ -58,6 +58,8 @@ QT_BEGIN_NAMESPACE extern Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum); // qcocoaview.mm extern QPointer qt_button_down; //qapplication_mac.cpp extern const QStringList& qEnabledDraggedTypes(); // qmime_mac.cpp +extern void qt_event_request_window_change(QWidget *); // qapplication_mac.mm +extern void qt_mac_send_posted_gl_updates(QWidget *widget); // qapplication_mac.mm Q_GLOBAL_STATIC(QPointer, currentDragTarget); @@ -227,6 +229,17 @@ QT_END_NAMESPACE [self release]; } +- (void)setInitialFirstResponder:(NSView *)view +{ + // This method is called the first time the window is placed on screen and + // is the earliest point in time we can connect OpenGL contexts to NSViews. + QWidget *qwidget = [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] qt_qwidgetForWindow:self]; + qt_event_request_window_change(qwidget); + qt_mac_send_posted_gl_updates(qwidget); + + [super setInitialFirstResponder:view]; +} + - (BOOL)makeFirstResponder:(NSResponder *)responder { // For some reason Cocoa wants to flip the first responder diff --git a/src/opengl/qgl_mac.mm b/src/opengl/qgl_mac.mm index 66fe7d3..f023a97 100644 --- a/src/opengl/qgl_mac.mm +++ b/src/opengl/qgl_mac.mm @@ -697,9 +697,17 @@ void QGLContext::updatePaintDevice() QWidget *w = (QWidget *)d->paintDevice; NSView *view = qt_mac_nativeview_for(w); - // ideally we would use QWidget::isVisible(), but we get "invalid drawable" errors - if (![(NSWindow *)qt_mac_window_for(w) isVisible]) - return; + // Trying to attach the GL context to the NSView will fail with + // "invalid drawable" if done too soon, but we have to make sure + // the connection is made before the first paint event. Using + // the NSView do to this check fails as the NSView is visible + // before it's safe to connect, and using the NSWindow fails as + // the NSWindow will become visible after the first paint event. + // This leaves us with the QWidget, who's visible state seems + // to match the point in time when it's safe to connect. + if (!w || !w->isVisible()) + return; // Not safe to attach GL context to view yet + if ([static_cast(d->cx) view] != view && ![view isHidden]) [static_cast(d->cx) setView:view]; } else if (d->paintDevice->devType() == QInternal::Pixmap) { -- cgit v0.12 From 4b7346a4bd30705ab5910d448ec56daa6568aa90 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Thu, 2 Sep 2010 17:09:13 +0200 Subject: Fix remote crash in delivering D-Bus calls with too few arguments Patch by Christoph Feck. Task-number: QTBUG-13348 Reviewed by me --- src/dbus/qdbusintegrator.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/dbus/qdbusintegrator.cpp b/src/dbus/qdbusintegrator.cpp index 7951177..3833874 100644 --- a/src/dbus/qdbusintegrator.cpp +++ b/src/dbus/qdbusintegrator.cpp @@ -714,6 +714,9 @@ QDBusCallDeliveryEvent* QDBusConnectionPrivate::prepareReply(QDBusConnectionPriv if (metaTypes[n] == QDBusMetaTypeId::message) --n; + if (msg.arguments().count() < n) + return 0; // too few arguments + // check that types match for (int i = 0; i < n; ++i) if (metaTypes.at(i + 1) != msg.arguments().at(i).userType() && -- cgit v0.12 From 19beb3de012c4531dc69699bbb33f2cf1e86a84c Mon Sep 17 00:00:00 2001 From: Jiang Jiang Date: Thu, 2 Sep 2010 15:57:59 +0200 Subject: Fix broken S60 build Reviewed-by: Liang Qi --- src/gui/text/qfontengine_s60.cpp | 7 ++++++- src/gui/text/qfontengine_s60_p.h | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/gui/text/qfontengine_s60.cpp b/src/gui/text/qfontengine_s60.cpp index 2c533db..5980f20 100644 --- a/src/gui/text/qfontengine_s60.cpp +++ b/src/gui/text/qfontengine_s60.cpp @@ -166,6 +166,11 @@ const uchar *QSymbianTypeFaceExtras::cmap() const return reinterpret_cast(m_cmapTable.constData()); } +bool QSymbianTypeFaceExtras::isSymbolCMap() const +{ + return m_symbolCMap; +} + CFont *QSymbianTypeFaceExtras::fontOwner() const { return m_cFont; @@ -256,7 +261,7 @@ bool QFontEngineS60::stringToCMap(const QChar *characters, int len, QGlyphLayout for (int i = 0; i < len; ++i) { const unsigned int uc = getChar(characters, i, len); *g++ = QFontEngine::getTrueTypeGlyphIndex(cmap, - (isRtl && !m_symbolCMap) ? QChar::mirroredChar(uc) : uc); + (isRtl && !m_extras->isSymbolCMap()) ? QChar::mirroredChar(uc) : uc); } glyphs->numGlyphs = g - glyphs->glyphs; diff --git a/src/gui/text/qfontengine_s60_p.h b/src/gui/text/qfontengine_s60_p.h index d65f13b..d05c23c 100644 --- a/src/gui/text/qfontengine_s60_p.h +++ b/src/gui/text/qfontengine_s60_p.h @@ -81,6 +81,7 @@ public: bool getSfntTableData(uint tag, uchar *buffer, uint *length) const; const uchar *cmap() const; CFont *fontOwner() const; + bool isSymbolCMap() const; private: CFont* m_cFont; -- cgit v0.12 From c229d4c1cb4c5aa0be22dddd5e8d8436a29cf103 Mon Sep 17 00:00:00 2001 From: Alessandro Portale Date: Thu, 2 Sep 2010 17:37:07 +0200 Subject: Removing a left over #if 1..#endif construct --- src/gui/text/qfont_s60.cpp | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/gui/text/qfont_s60.cpp b/src/gui/text/qfont_s60.cpp index ccd17a2..f303419 100644 --- a/src/gui/text/qfont_s60.cpp +++ b/src/gui/text/qfont_s60.cpp @@ -46,7 +46,6 @@ QT_BEGIN_NAMESPACE -#if 1 #ifdef QT_NO_FREETYPE Q_GLOBAL_STATIC(QMutex, lastResortFamilyMutex); #endif // QT_NO_FREETYPE @@ -70,7 +69,7 @@ QString QFont::lastResortFamily() const lock.relock(); } return family; -#else +#else // QT_NO_FREETYPE // For the FreeType case we just hard code the face name, since otherwise on // East Asian systems we may get a name for a stroke based (non-ttf) font. @@ -82,12 +81,6 @@ QString QFont::lastResortFamily() const return QLatin1String(isJapaneseOrChineseSystem?"Heisei Kaku Gothic S60":"Series 60 Sans"); #endif // QT_NO_FREETYPE } -#else // 0 -QString QFont::lastResortFamily() const -{ - return QLatin1String("Series 60 Sans"); -} -#endif // 0 QString QFont::defaultFamily() const { -- cgit v0.12 From b600ce8b388ad20b64c44198b582e000b4289c00 Mon Sep 17 00:00:00 2001 From: Victor Ostashevsky Date: Thu, 2 Sep 2010 18:46:21 +0200 Subject: Ukrainian translation updated New strings which appeared after MR783 and MR2456 are translated. Also some stylistic fixes applied. xmlpatterns translation started. Merge-request: 801 Reviewed-by: Oswald Buddenhagen --- translations/assistant_uk.ts | 461 +++------ translations/designer_uk.ts | 131 ++- translations/linguist_uk.ts | 2355 ++++++++++++++++++++++++++---------------- translations/qt_help_uk.ts | 4 +- translations/qt_uk.ts | 124 ++- translations/qvfb_uk.ts | 145 ++- 6 files changed, 1893 insertions(+), 1327 deletions(-) diff --git a/translations/assistant_uk.ts b/translations/assistant_uk.ts index c7aad83..d08003e 100644 --- a/translations/assistant_uk.ts +++ b/translations/assistant_uk.ts @@ -41,7 +41,7 @@ Reason: %2 - Не можу зареєструвати файл документації + Не вдалось зареєструвати файл документації %1 Причина: @@ -57,7 +57,7 @@ Reason: Reason: %2 - Не можу скасувати реєстрацію файлу документації + Не вдалось скасувати реєстрацію файлу документації %1 Причина: @@ -77,7 +77,7 @@ Reason: Cannot load sqlite database driver! - Не можу завантажити драйвер бази даних SQLite! + Неможливо завантажити драйвер бази даних SQLite! @@ -108,6 +108,17 @@ Reason: + BookmarkItem + + New Folder + Нова тека + + + Untitled + Без назви + + + BookmarkManager Untitled @@ -313,6 +324,60 @@ Reason: CmdLineParser + Usage: assistant [Options] + +-collectionFile file Uses the specified collection + file instead of the default one +-showUrl url Shows the document with the + url. +-enableRemoteControl Enables Assistant to be + remotely controlled. +-show widget Shows the specified dockwidget + which can be "contents", "index", + "bookmarks" or "search". +-activate widget Activates the specified dockwidget + which can be "contents", "index", + "bookmarks" or "search". +-hide widget Hides the specified dockwidget + which can be "contents", "index" + "bookmarks" or "search". +-register helpFile Registers the specified help file + (.qch) in the given collection + file. +-unregister helpFile Unregisters the specified help file + (.qch) from the give collection + file. +-setCurrentFilter filter Set the filter as the active filter. +-remove-search-index Removes the full text search index. +-rebuild-search-index Re-builds the full text search index (potentially slow). +-quiet Does not display any error or + status message. +-help Displays this help. + + Використання: assistant [Опції] + +-collectionFile файл Використати вказаний файл колекції + замість типового +-showUrl URL Показати документ з URL. +-enableRemoteControl Увімкнути віддалене керування Assistant. +-show віджет Показати вказаний віджет (може бути: + "contents", "index", "bookmarks" чи "search"). +-activate віджет Активувати вказаний віджет (може бути: + "contents", "index", "bookmarks" чи "search"). +-hide віджет Сховати вказаний віджет (може бути: + "contents", "index", "bookmarks" чи "search"). +-register файлДовідки Зареєструвати вказаний файл довідки + (.qch) в даному файлі колекції. +-unregister файлДовідки Скасувати реєстрацію вказаного файлу довідки + (.qch) в даному файлі колекції. +-setCurrentFilter фільтр Встановити фільтр в якості активного. +-remove-search-index Видалити повнотекстовий пошуковий індекс. +-rebuild-search-index Перебудувати повнотекстовий пошуковий індекс (можливо довго). +-quiet Не показувати жодних помилок чи статусних повідомлень. +-help Показати цю довідку. + + + Unknown option: %1 Невідома опція: %1 @@ -487,6 +552,11 @@ Reason: The attributes for custom filter '%1' are defined multiple times. Атрибути для користувацького фільтра '%1' визначено декілька раз. + + unfiltered + list of available documentation + без фільтра + FindWidget @@ -513,6 +583,10 @@ Reason: Converting File Конвертування файлу + + Creating the new Qt help files from the old ADP file. + Створення нових файлів довідки Qt зі старого файлу ADP. + FontPanel @@ -577,6 +651,13 @@ Reason: + HelpGenerator + + Warning: %1 + Попередження: %1 + + + HelpViewer <title>about:blank</title> @@ -584,7 +665,7 @@ Reason: <title>Error 404...</title><div align="center"><br><br><h1>The page could not be found</h1><br><h3>'%1'</h3></div> - <title>Помилка 404...</title><div align="center"><br><br><h1>Неможливо знайти сторінку</h1><br><h3>'%1'</h3></div> + <title>Помилка 404...</title><div align="center"><br><br><h1>Не вдалось знайти сторінку</h1><br><h3>'%1'</h3></div> Copy &Link Location @@ -600,6 +681,13 @@ Reason: + HelpWindow + + <center><b>Wizard Assistant</b></center> + <center><b>Майстер Assistant</b></center> + + + IdentifierPage Form @@ -736,7 +824,7 @@ Reason: Unable to save the file %1: %2. - Не можу зберегти файл %1: %2. + Неможливо зберегти файл %1: %2. Downloading %1... @@ -988,6 +1076,10 @@ Reason: Не вдалось знайти елемент, пов'язаний зі змістом. + <center><h3>%1</h3><p>Version %2</p></center><p>Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).</p> + <center><h3>%1</h3><p>Версія %2</p></center><p>Copyright (C) 2010 Корпорація Nokia та/або її дочірні компанії.</p> + + About %1 Про %1 @@ -997,7 +1089,7 @@ Reason: Could not register file '%1': %2 - Не можу зареєструвати файл '%1': %2 + Не вдалось зареєструвати файл '%1': %2 @@ -1221,45 +1313,20 @@ Do you want to remove it? - QCLuceneResultWidget - - Search Results - Результати пошуку - - - Note: - Примітка: - - - The search results may not be complete since the documentation is still being indexed! - Результати пошуку можуть бути не повні, оскільки документація досі індексується! - - - Your search did not match any documents. - Ваш пошук не повернув результатів. - - - (The reason for this might be that the documentation is still being indexed.) - (Причиною цього може бути те, що документація досі індексується.) - - - QCollectionGenerator Unknown token at line %1. Невідомий токен в рядку %1. - Unknown token at line %1. Expected "QtHelpCollectionProject"! - Невідомий токен в рядку %1. Очікувався "QtHelpCollectionProject"! + Missing end tags. + Відсутні кінцеві теги. - Missing output file name! - Відсутнє ім'я вихідного файлу! - - - Missing collection config file! - Відсутній файл налаштувань колекції! + Qt Collection Generator version 1.0 (Qt %1) + + Qt Collection Generator версії 1.0 (Qt %1) + @@ -1288,209 +1355,92 @@ qcollectiongenerator <файл-налаштувань-колекції> [ - - - QHelp - Untitled - Без назви - - - - QHelpCollectionHandler - - The collection file '%1' is not set up yet! - Файл колекції '%1' ще не встановлено! - - - Cannot load sqlite database driver! - Не можу завантажити драйвер бази даних SQLite! - - - Cannot open collection file: %1 - Неможливо відкрити файл колекції: %1 - - - Cannot create tables in file %1! - Неможливо створити таблиці в файлі %1! - - - The collection file '%1' already exists! - Файл колекції '%1' вже існує! - - - Cannot create directory: %1 - Неможливо створити теку: %1 - - - Cannot copy collection file: %1 - Неможливо скопіювати файл колекції: %1 + Unknown token at line %1. Expected "QtHelpCollectionProject". + Невідомий токен в рядку %1. Очікувався "QtHelpCollectionProject". - Unknown filter '%1'! - Невідомий фільтр '%1'! + Missing input or output file for help file generation. + Відсутній вхідний чи вихідний файл для генерації файлу довідки. - Cannot register filter %1! - Неможливо зареєструвати фільтр %1! + Missing output file name. + Відсутнє ім'я вихідного файлу. - Cannot open documentation file %1! - Неможливо відкрити файл документації %1! + Missing collection config file. + Відсутній файл налаштувань колекції. - Invalid documentation file '%1'! - Неправильний файл документації '%1'! + Could not open %1. + + Не вдалось відкрити %1. + - The namespace %1 was not registered! - Простір імен %1 не зареєстровано! + Reading collection config file... + + Читання файлу налаштувань колекції... + - Namespace %1 already exists! - Простір імен %1 вже існує! + Collection config file error: %1 + + Помилка файлу налаштувань колекції: %1 + - Cannot register namespace '%1'! - Неможливо зареєструвати простір імен '%1'! + Generating help for %1... + + Генерування довідки для %1... + - Cannot open database '%1' to optimize! - Неможливо відкрити базу даних '%1' для оптимізації! + Creating collection file... + + Створення файлу колекції... + - - - QHelpDBReader - Cannot open database '%1' '%2': %3 - The placeholders are: %1 - The name of the database which cannot be opened %2 - The unique id for the connection %3 - The actual error string - Неможливо відкрити базу даних: '%1' '%2': %3 + The file %1 cannot be overwritten. + + Неможливо перезаписати файл %1. + - - - QHelpEngineCore - Cannot open documentation file %1: %2! - Неможливо файл документації %1: %2! + Cannot open %1. + + Неможливо відкрити %1. + - The specified namespace does not exist! - Вказаний простір імен не існує! + Cannot open referenced image file %1. + + Неможливо відкрити файл зображення %1, на який є посилання. + QHelpGenerator - Invalid help data! - Неправильні дані довідки! - - - No output file name specified! - Не вказане ім'я вихідного файлу! - - - The file %1 cannot be overwritten! - Неможливо перезаписати файл %1! - - - Building up file structure... - Побудова структури файлу.... - - - Cannot open data base file %1! - Неможливо відкрити файл бази даних %1! + Missing output file name. + Відсутнє ім'я вихідного файлу. - Cannot register namespace %1! - Неможливо зареєструвати простір імен %1! - - - Insert custom filters... - Вставка фільтрів користувача... - - - Insert help data for filter section (%1 of %2)... - Вставка даних довідки для розділу фільтра (%1 з %2)... - - - Documentation successfully generated. - Документацію успішно згенеровано. - - - Some tables already exist! - Деякі таблиці вже існують! - - - Cannot create tables! - Неможливо створити таблиці! - - - Cannot register virtual folder! - Неможливо зареєструвати віртуальну теку! - - - Insert files... - Вставка файлів... - - - The referenced file %1 must be inside or within a subdirectory of (%2). Skipping it. - Файл %1 має бути всередині підтеки (%2). Пропускаємо його. - - - The file %1 does not exist! Skipping it. - Файл %1 не існує! Пропускаємо його. - - - Cannot open file %1! Skipping it. - Неможливо відкрити файл %1! Пропускаємо його. - - - The filter %1 is already registered! - Фільтр %1 вже зареєстровано! - - - Cannot register filter %1! - Неможливо зареєструвати фільтр %1! - - - Insert indices... - Вставка індексів... - - - Insert contents... - Вставка змісту... - - - Cannot insert contents! - Неможливо вставити зміст! - - - Cannot register contents! - Неможливо зареєструвати зміст! - - - File '%1' does not exist. - Файл '%1' не існує. - - - File '%1' cannot be opened. - Неможливо відкрити файл '%1'. - - - File '%1' contains an invalid link to file '%2' - Файл '%1' містить неправильне посилання до файлу '%2' - - - Invalid links in HTML files. - Неправильні посилання в файлах HTML. + Qt Help Generator version 1.0 (Qt %1) + + Qt Help Generator версії 1.0 (Qt %1) + - Missing output file name! - Відсутнє ім'я вихідного файлу! + Missing Qt help project file. + Відсутній файл проекту колекції довідки Qt. - Missing Qt help project file! - Відсутній файл проекту колекції довідки Qt! + Could not open %1. + + Не вдалось відкрити %1. + @@ -1524,102 +1474,11 @@ qhelpgenerator <файл-проекту-довідки> [опції] - - - QHelpProject - - Unknown token. - Невідомий токен. - - - Unknown token. Expected "QtHelpProject"! - Невідомий токен. Очікувався "QtHelpProject"! - - - Error in line %1: %2 - Помилка в рядку %1: %2 - - - Virtual folder has invalid syntax. - Віртуальна тека має неправильний синтаксис. - - - Namespace has invalid syntax. - Простір імен має неправильний синтаксис. - - - Missing namespace in QtHelpProject. - Відсутній простір імен в QtHelpProject. - - - Missing virtual folder in QtHelpProject - Відсутня віртуальна тека в QtHelpProject - - - Missing attribute in keyword at line %1. - Відсутній атрибут в ключовому слові на рядку %1. - - - The input file %1 could not be opened! - Неможливо відкрити вхідний файл %1! - - - - QHelpSearchQueryWidget - - Search for: - Шукати: - - Previous search - Попередній пошук - - - Next search - Наступний пошук - - - Search - Пошук - - - Advanced search - Розширений пошук - - - words <B>similar</B> to: - слова <B>схожі</B> на: - - - <B>without</B> the words: - <B>без</B> слів: - - - with <B>exact phrase</B>: - з <B>точною фразою</B>: - - - with <B>all</B> of the words: - з <B>усіма</B> словами: - - - with <B>at least one</B> of the words: - з <B>щонайменше одним</B> зі слів: - - - - QHelpSearchResultWidget - - %1 - %2 of %n Hits - - %1 - %2 з %n збігу - %1 - %2 з %n збігів - %1 - %2 з %n збігів - - - - 0 - 0 of 0 Hits - 0 - 0 of 0 збігів + Could not create output directory: %1 + + Не вдалось створити вихідну теку: %1 + diff --git a/translations/designer_uk.ts b/translations/designer_uk.ts index ae27e67..12e60e6 100644 --- a/translations/designer_uk.ts +++ b/translations/designer_uk.ts @@ -25,6 +25,49 @@ + AbstractItemEditor + + Selectable + Можна вибирати + + + Editable + Можна редагувати + + + DragEnabled + Можна тягти + + + DropEnabled + Можна кидати + + + UserCheckable + Користувач може позначати + + + Enabled + Увімкнено + + + Tristate + Три стани + + + Unchecked + Не позначено + + + PartiallyChecked + Частково позначено + + + Checked + Позначено + + + AddLinkDialog Insert Link @@ -62,7 +105,7 @@ The font file '%1' could not be loaded. - Неможливо завантажити файл шрифт '%1'. + Не вдалось завантажити файл шрифт '%1'. '%1' is not a valid font id. @@ -74,7 +117,7 @@ The font '%1' (%2) could not be unloaded. - Неможливо вивантажити шрифт '%1' (%2). + Не вдалось вивантажити шрифт '%1' (%2). @@ -639,7 +682,7 @@ The converted file could not be read. - Неможливо прочитати конвертований файл. + Не вдалось прочитати конвертований файл. This file was created using Designer from Qt-%1 and will be converted to a new form by Qt Designer. @@ -652,7 +695,7 @@ This file was created using Designer from Qt-%1 and could not be read: %2 - Неможливо прочитати файл, бо його було створено з використанням Designer з Qt-%1: + Не вдалось прочитати файл, бо його було створено з використанням Designer з Qt-%1: %2 @@ -672,14 +715,14 @@ '%1' could not be converted to an enumeration value of type '%2'. - Неможливо сконвертувати '%1'до типу значень переліку '%2'. + Не вдалось сконвертувати '%1'до типу значень переліку '%2'. DesignerMetaFlags '%1' could not be converted to a flag value of type '%2'. - '%1' не можу бути сконвертовано до прапорця типу '%2'. + Не вдалось перетворити '%1' прапорця типу '%2'. @@ -721,7 +764,7 @@ DeviceSkin The image file '%1' could not be loaded. - Неможливо завантажити файл зображення '%1'. + Не вдалось завантажити файл зображення '%1'. The skin directory '%1' does not contain a configuration file. @@ -729,11 +772,11 @@ The skin configuration file '%1' could not be opened. - Неможливо відкрити файл налаштувань '%1'. + Не вдалось відкрити файл налаштувань '%1'. The skin configuration file '%1' could not be read: %2 - Неможливо прочитати файл налаштувань '%1': %2 + Не вдалось прочитати файл налаштувань '%1': %2 Syntax error: %1 @@ -1044,11 +1087,11 @@ Parsing grid layout minimum size values A temporary form file could not be created in %1. - Неможливо створити тимчасовий файл форми в %1. + Не вдалось створити тимчасовий файл форми в %1. The temporary form file %1 could not be written. - Неможливо записати тимчасовий файл форми %1. + Не вдалось записати тимчасовий файл форми %1. @@ -1179,7 +1222,7 @@ This indicates an inconsistency in the ui-file. While applying tab stops: The widget '%1' could not be found. - Під час застосування позицій табуляції: Неможливо знайти віджет '%1'. + Під час застосування позицій табуляції: Не вдалось знайти віджет '%1'. Invalid QButtonGroup reference '%1' referenced by '%2'. @@ -1464,13 +1507,13 @@ Do you want to update the file location or generate a new form? Could not open file - Неможливо відкрити файл + Не вдалось відкрити файл The file %1 could not be opened. Reason: %2 Would you like to retry or select a different file? - Неможливо відкрити файл %1. + Не вдалось відкрити файл %1. Причина: %2 Чи не хотіли б ви спробувати ще раз чи вибрати інший файл? @@ -1480,7 +1523,7 @@ Would you like to retry or select a different file? Could not write file - Неможливо записати файл + Не вдалось записати файл It was not possible to write the entire file %1 to disk. @@ -1500,15 +1543,15 @@ Would you like to retry? The backup file %1 could not be written. - Неможливо записати файл резервної копії %1. + Не вдалось записати файл резервної копії %1. The backup directory %1 could not be created. - Неможливо створити теку резервних копій %1. + Не вдалось створити теку резервних копій %1. The temporary backup directory %1 could not be created. - Неможливо створити тимчасову теку резервних копій %1. + Не вдалось створити тимчасову теку резервних копій %1. Preview failed @@ -1528,7 +1571,7 @@ Would you like to retry? The file %1 could not be written. - Неможливо записати файл %1. + Не вдалось записати файл %1. Please close all forms to enable the loading of additional fonts. @@ -1735,7 +1778,7 @@ Container pages should only be added by specifying them in XML returned by the d QDesignerSharedSettings The template path %1 could not be created. - Неможливо створити шлях до шаблону %1. + Не вдалось створити шлях до шаблону %1. An error has been encountered while parsing device profile XML: %1 @@ -1845,7 +1888,7 @@ Container pages should only be added by specifying them in XML returned by the d The file <b>%1</b> could not be opened. - Неможливо відкрити файл <b>%1</b>. + Не вдалось відкрити файл <b>%1</b>. The file <b>%1</b> is not a valid Designer UI file. @@ -1877,11 +1920,11 @@ Empty class name passed to widget factory method The set-type property %1 could not be read. - Неможливо прочитати властивість %1 типу "множина". + Не вдалось прочитати властивість %1 типу "множина". The enumeration-type property %1 could not be read. - Неможливо прочитати властивість %1 типу "перелік". + Не вдалось прочитати властивість %1 типу "перелік". Reading properties of the type %1 is not supported yet. @@ -1889,7 +1932,7 @@ Empty class name passed to widget factory method The property %1 could not be written. The type %2 is not supported yet. - Неможливо записати властивість %1. Тип %2 ще не підтримується. + Не вдалось записати властивість %1. Тип %2 ще не підтримується. The enumeration-value '%1' is invalid. The default value '%2' will be used instead. @@ -2513,6 +2556,10 @@ Empty class name passed to widget factory method QtLocalePropertyManager + <Invalid> + <Неправильний> + + %1, %2 %1, %2 @@ -2740,14 +2787,14 @@ This could for example be a language extension like "_de". Could not overwrite %1. - Неможливо перезаписати %1. + Не вдалось перезаписати %1. Could not copy %1 to %2 - Неможливо копіювати + Не вдалось скопіювати %1 до %2 @@ -2764,7 +2811,7 @@ to Could not write %1: %2 - Неможливо записати %1: %2 + Не вдалось записати %1: %2 Edit Resources @@ -3480,11 +3527,11 @@ Do you want overwrite the template? A temporary form file could not be created in %1. - Неможливо створити тимчасовий файл форми в %1. + Не вдалось створити тимчасовий файл форми в %1. The temporary form file %1 could not be written. - Неможливо записати тимчасовий файл форми %1. + Не вдалось записати тимчасовий файл форми %1. %1 - [Code] @@ -3500,11 +3547,11 @@ Do you want overwrite the template? The file %1 could not be opened: %2 - Неможливо відкрити файл %1: %2 + Не вдалось відкрити файл %1: %2 The file %1 could not be written: %2 - Неможливо записати файл %1: %2 + Не вдалось записати файл %1: %2 %1 - Error @@ -3951,7 +3998,7 @@ Do you want overwrite the template? Cannot paste widgets. Designer could not find a container without a layout to paste into. - Неможливо вставити віджети. Qt Designer не зміг знайти контейнер без розташування для вставки. + Неможливо вставити віджети. Qt Designer'у не вдалось знайти контейнер без розташування для вставки. Break the layout of the container you want to paste into, select this container and then paste again. @@ -4150,7 +4197,7 @@ Do you want overwrite the template? Could not create form preview Title of warning message box - Неможливо створити попередній перегляд форми + Не вдалось створити попередній перегляд форми Form Settings - %1 @@ -4225,7 +4272,7 @@ Do you want overwrite the template? The file '%1' could not be read: %2 - Неможливо прочитати файл '%1': %2 + Не вдалось прочитати файл '%1': %2 Choose a Pixmap @@ -4740,8 +4787,16 @@ Please select another name. Шукати нові встановлені додатки користувацьких віджетів. + Loaded Plugins + Завантажені додатки + + + Failed Plugins + Проблемні додатки + + Qt Designer couldn't find any plugins - Qt Designer не зміг знайти жодного додатку + Qt Designer'у не вдалось знайти жодного додатку Qt Designer found the following plugins @@ -5014,7 +5069,7 @@ Class: %2 The specified qrc file <p><b>%1</b></p><p>could not be found. Do you want to update the file location?</p> - Неможливо знайти вказаний файл qrc <p><b>%1</b></p><p>. Бажаєте оновити розташування файлу?</p> + Не вдалось знайти вказаний файл qrc <p><b>%1</b></p><p>. Бажаєте оновити розташування файлу?</p> New location for %1 @@ -5152,7 +5207,7 @@ Class: %2 A widget element could not be found. - Неможливо знайти елемент віджета. + Не вдалось знайти елемент віджета. @@ -5741,7 +5796,7 @@ Class: %2 The current page of the container '%1' (%2) could not be determined while creating a layout.This indicates an inconsistency in the ui-file, probably a layout being constructed on a container widget. - Неможливо визначити поточну сторінку контейнера '%1' (%2) під час створення розташування. Це вказує на некоректність файлу UI, можливо, розташування було створене на контейнерному віджеті. + Не вдалось визначити поточну сторінку контейнера '%1' (%2) під час створення розташування. Це вказує на некоректність файлу UI, можливо, розташування було створене на контейнерному віджеті. Attempt to add a layout to a widget '%1' (%2) which already has an unmanaged layout of type %3. diff --git a/translations/linguist_uk.ts b/translations/linguist_uk.ts index 6e58be5..ca326d6 100644 --- a/translations/linguist_uk.ts +++ b/translations/linguist_uk.ts @@ -113,7 +113,7 @@ Will assume a single universal form. Cannot create '%2': %1 - Не можу створити '%2': %1 + Неможливо створити '%2': %1 Universal Form @@ -259,6 +259,186 @@ Will assume a single universal form. + LConvert + + +Usage: + lconvert [options] <infile> [<infile>...] + +lconvert is part of Qt's Linguist tool chain. It can be used as a +stand-alone tool to convert and filter translation data files. +The following file formats are supported: + +%1 +If multiple input files are specified, they are merged with +translations from later files taking precedence. + +Options: + -h + --help Display this information and exit. + + -i <infile> + --input-file <infile> + Specify input file. Use if <infile> might start with a dash. + This option can be used several times to merge inputs. + May be '-' (standard input) for use in a pipe. + + -o <outfile> + --output-file <outfile> + Specify output file. Default is '-' (standard output). + + -if <informat> + --input-format <format> + Specify input format for subsequent <infile>s. + The format is auto-detected from the file name and defaults to 'ts'. + + -of <outformat> + --output-format <outformat> + Specify output format. See -if. + + --input-codec <codec> + Specify encoding for QM and PO input files. Default is 'Latin1' + for QM and 'UTF-8' for PO files. UTF-8 is always tried as well for + QM, corresponding to the possible use of the trUtf8() function. + + --output-codec <codec> + Specify encoding for PO output files. Default is 'UTF-8'. + + --drop-tags <regexp> + Drop named extra tags when writing TS or XLIFF files. + May be specified repeatedly. + + --drop-translations + Drop existing translations and reset the status to 'unfinished'. + Note: this implies --no-obsolete. + + --source-language <language>[_<region>] + Specify/override the language of the source strings. Defaults to + POSIX if not specified and the file does not name it yet. + + --target-language <language>[_<region>] + Specify/override the language of the translation. + The target language is guessed from the file name if this option + is not specified and the file contents name no language yet. + + --no-obsolete + Drop obsolete messages. + + --no-finished + Drop finished messages. + + --sort-contexts + Sort contexts in output TS file alphabetically. + + --locations {absolute|relative|none} + Override how source code references are saved in TS files. + Default is absolute. + + --no-ui-lines + Drop line numbers from references to UI files. + + --verbose + be a bit more verbose + +Long options can be specified with only one leading dash, too. + +Return value: + 0 on success + 1 on command line parse failures + 2 on read failures + 3 on write failures + + +Використання: + lconvert [опції] <вхідний_файл> [<вхідний_файл>...] + +lconvert - це частина набору програм Qt Linguist. Вона може використовуватись, +як окремий інструмент, для конвертування та фільтрування файлів перекладу. +Підтримуються наступні формати файлів: + +%1 +Якщо вказано декілька вхідних файлів, то вони об'єднується з перекладами з +попередньо вказаних файлів з урахуванням порядку задання. + +Опції: + -h + --help Показати цю інформацію та вийти. + + -i <вхідний_файл> + --input-file <вхідний_файл> + Вказати вхідний файл. Використовуйте, якщо <вхідний_файл> + починається з дефіса. Ця опція може бути використана декілька + раз, щоб об'єднати вхідні дані. + Може бути '-' (стандартний вхід) для використання в конвеєрі. + + -o <вихідний_файл> + --output-file <вихідний_файл> + Вказати вихідний файл. Типово - '-' (стандартний вихід). + + -if <формат> + --input-format <формат> + Вказати вхідний формат для наступних <вхідних_файлів>. + Формат автоматично визначається з імені файлу. Типово - 'ts'. + + -of <формат> + --output-format <формат> + Вказати вихідний формат. Дивіться -if. + + --input-codec <кодек> + Вказати кодування для вхідних файлів QM та PO. Типово - 'Latin1' + для QM та 'UTF-8' файлів PO. Для QM також здійснюється спроба + використати UTF-8, відповідно до можливого застосування функції trUtf8(). + + --output-codec <кодек> + Вказати кодування для вихідних файлів PO. Типово - 'UTF-8'. + + --drop-tags <регулярний_вираз> + Видалити вказані додаткові теги під час запису файлів TS чи XLIFF. + Може вказуватись декілька раз. + + --drop-translations + Видаляти існуючі переклади та скидати статус в 'незавершений'. + Примітка: це включає --no-obsolete. + + --source-language <мова>[_<регіон>] + Вказати/замінити мову оригінальних рядків. Типово - POSIX, + якщо не вказано та не встановлено в файлі. + + --target-language <мова>[_<регіон>] + Вказати/замінити мову перекладу. + Якщо ця опція не вказана і у вмісті файлу мова не задана, то + мова перекладу вгадується з імені файлу. + + --no-obsolete + Відкинути застарілі повідомлення. + + --no-finished + Відкинути завершені повідомлення. + + --sort-contexts + Сортувати контексти в вихідному файлі TS за абеткою. + + --locations {absolute|relative|none} + Замінити як посилання на код зберігаються в файлі TS. + Типово - абсолютно. + + --no-ui-lines + Видалити номери рядків з посилань на файли UI. + + --verbose + бути трохи більш детальним + +Довгі опції також можуть вказуватись лише з одним дефісом. + +Коди повернення: + 0 при успіху + 1 при помилці розбору командного рядка + 2 при помилках читання + 3 при помилках запису + + + + LRelease Dropped %n message(s) which had no ID. @@ -292,1346 +472,1887 @@ Will assume a single universal form. Зігноровано %n неперекладених оригінальних текстів - - - LUpdate - lupdate warning: Codec for tr() '%1' disagrees with existing file's codec '%2'. Expect trouble. + Usage: + lrelease [options] project-file + lrelease [options] ts-files [-qm qm-file] + +lrelease is part of Qt's Linguist tool chain. It can be used as a +stand-alone tool to convert XML-based translations files in the TS +format into the 'compiled' QM format used by QTranslator objects. + +Options: + -help Display this information and exit + -idbased + Use IDs instead of source strings for message keying + -compress + Compress the QM files + -nounfinished + Do not include unfinished translations + -removeidentical + If the translated text is the same as + the source text, do not include the message + -markuntranslated <prefix> + If a message has no real translation, use the source text + prefixed with the given string instead + -silent + Do not explain what is being done + -version + Display the version of lrelease and exit - попередження lupdate: Кодек для tr() '%1' не узгоджується з існуючим кодеком файлу '%2'. Очікуйте неприємностей. + Використання: + lrelease [опції] файл-проект + lrelease [опції] файли-ts [-qm файл-qm] + +lrelease - це частина набору програм Qt Linguist. Вона може використовуватися +як окремий засіб для перетворення файлів перекладу на базі XML в форматі TS +до 'скомпільованого' формату QM, що використовується об'єктами QTranslator. + +Опції: + -help Показати цю інформацію та вийти + -idbased + Використовувати ID замість рядків оригіналу як ключі повідомлень + -compress + Стискати файли QM + -nounfinished + Не включати незавершені переклади + -removeidentical + Якщо перекладений текст однаковий з оригіналом, то + не включати повідомлення + -markuntranslated <prefix> + If a message has no real translation, use the source text + prefixed with the given string instead + -silent + Не пояснювати, що відбувається + -version + Показати версію lrelease та вийти - lupdate warning: Specified target language '%1' disagrees with existing file's language '%2'. Ignoring. - - попередження lupdate: Вказана мова перекладу '%1' не узгоджується з існуючою мовою файлу '%2'. Ігнорую. - + lrelease error: %1 + помилка lrelease: %1 - lupdate warning: Specified source language '%1' disagrees with existing file's language '%2'. Ignoring. + Updating '%1'... - попередження lupdate: Вказана мова оригіналу '%1' не узгоджується з існуючою мовою файлу '%2'. Ігнорую. + Оновлюю '%1'... - lupdate warning: Codec for source '%1' is invalid. Falling back to codec for tr(). + Removing translations equal to source text in '%1'... - попередження lupdate: Кодек для джерела '%1' неправильний. Повертаємось до використання кодеку для tr(). + Видалення перекладів однакових з оригінальним текстом в '%1'... - The option -target-language requires a parameter. + lrelease error: cannot create '%1': %2 - Опція -target-language вимагає параметра. + помилка lrelease: неможливо створити '%1': %2 - The option -source-language requires a parameter. - - Опція -source-language вимагає параметра. + lrelease error: cannot save '%1': %2 + помилка lrelease: неможливо зберегти '%1': %2 - The option -disable-heuristic requires a parameter. + lrelease version %1 - Опція -disable-heuristic вимагає параметра. + lrelease версії %1 - Invalid heuristic name passed to -disable-heuristic. + lrelease error: cannot read project file '%1'. - Неправильна назва евристики для -disable-heuristic. + помилка lrelease: неможливо прочитати файл проекту '%1'. - The option -locations requires a parameter. + lrelease error: cannot process project file '%1'. - Опція -locations вимагає параметра. + помилка lrelease: неможливо обробити файл проекту '%1'. - Invalid parameter passed to -locations. + lrelease warning: Met no 'TRANSLATIONS' entry in project file '%1' - Неправильний параметр для -locations. + попередження lrelease: в файлу проекту '%1' не знайдено елементу 'TRANSLATIONS' + + + LUpdate - The -codecfortr option should be followed by a codec name. + Usage: + lupdate [options] [project-file]... + lupdate [options] [source-file|path|@lst-file]... -ts ts-files|@lst-file + +lupdate is part of Qt's Linguist tool chain. It extracts translatable +messages from Qt UI files, C++, Java and JavaScript/QtScript source code. +Extracted messages are stored in textual translation source files (typically +Qt TS XML). New and modified messages can be merged into existing TS files. + +Options: + -help Display this information and exit. + -no-obsolete + Drop all obsolete strings. + -extensions <ext>[,<ext>]... + Process files with the given extensions only. + The extension list must be separated with commas, not with whitespace. + Default: '%1'. + -pluralonly + Only include plural form messages. + -silent + Do not explain what is being done. + -no-sort + Do not sort contexts in TS files. + -no-recursive + Do not recursively scan the following directories. + -recursive + Recursively scan the following directories (default). + -I <includepath> or -I<includepath> + Additional location to look for include files. + May be specified multiple times. + -locations {absolute|relative|none} + Specify/override how source code references are saved in TS files. + Default is absolute. + -no-ui-lines + Do not record line numbers in references to UI files. + -disable-heuristic {sametext|similartext|number} + Disable the named merge heuristic. Can be specified multiple times. + -pro <filename> + Name of a .pro file. Useful for files with .pro file syntax but + different file suffix. Projects are recursed into and merged. + -source-language <language>[_<region>] + Specify the language of the source strings for new files. + Defaults to POSIX if not specified. + -target-language <language>[_<region>] + Specify the language of the translations for new files. + Guessed from the file name if not specified. + -ts <ts-file>... + Specify the output file(s). This will override the TRANSLATIONS + and nullify the CODECFORTR from possibly specified project files. + -codecfortr <codec> + Specify the codec assumed for tr() calls. Effective only with -ts. + -version + Display the version of lupdate and exit. + @lst-file + Read additional file names (one per line) from lst-file. - За опцією -codecfortr має слідувати назва кодека. + Використання: + lupdate [опції] [файл-проект]... + lupdate [опції] [вхідний-файл|шлях|@файл-список]... -ts ts-файли|@файл-список + +lupdate - це частина набору програм Qt Linguist. Вона It витягає придатні для перекладу +повідомлення з файлів Qt UI, коду C++, Java та JavaScript/QtScript. Витягнуті повідомлення +зберігаються в текстовому файлі перекладу (типово Qt TS XML). Нові та модифіковані +повідомлення можуть бути об'єднанні з існуючими файлами TS. + +Опції: + -help Показати цю інформацію та вийти. + -no-obsolete + Видалити всі застарілі рядки. + -extensions <розширення>[,<розширення>]... + Обробляти файли лише з вказаними розширеннями. + Список розширень має розділюватись комами, а не пропусками. + Типово: '%1'. + -pluralonly + Включати лише повідомлення з формою множини. + -silent + Не пояснювати, що відбувається. + -no-sort + Не сортувати контексти в файлах TS. + -no-recursive + Не сканувати рекурсивно наступні теки. + -recursive + Рекурсивно сканувати наступні теки (типово). + -I <шлях-включення> або -I<шлях-включення> + Додаткові місця для пошуку файлів включення. + Може бути вказано декілька разів. + -locations {absolute|relative|none} + Вказати/замістити як посилання на код зберігаються в файлі TS. + Типово - абсолютно. + -no-ui-lines + Не записувати номери рядків в посиланнях на файли UI. + -disable-heuristic {sametext|similartext|number} + Вимкнути вказану евристику об'єдання. Може бути вказано декілька разів. + -pro <ім'я-файлу> + Ім'я .pro файлу. Корисно для файлів із синтаксисом фалів .pro, але з + іншим розширенням. Projects are recursed into and merged. + -source-language <мова>[_<регіон>] + Вказати мову оригінальних рядків для нових файлів. + Типово, якщо не вказано - POSIX. + -target-language <мова>[_<регіон>] + Вказати мову перекладу для нових файлів. + Вгадується з імені файла, якщо не вказано. + -ts <файл-ts>... + Вказати вихідний файл(и). Це замістить TRANSLATIONS + та скине CODECFORTR з, можливо, вказаних файлів проекту. + -codecfortr <кодек> + Вказати кодек, що Specify the codec вживається для викликів tr(). Ефективно лише з -ts. + -version + Показати версію lupdate та вийти. + @файл-список + Читати додаткові імена файлів (одне на рядок) з файла-списку. - The -extensions option should be followed by an extension list. + lupdate warning: Codec for tr() '%1' disagrees with existing file's codec '%2'. Expect trouble. - За опцією -extensions має слідувати список розширень. + попередження lupdate: Кодек для tr() '%1' не узгоджується з існуючим кодеком файлу '%2'. Очікуйте неприємностей. - The -pro option should be followed by a filename of .pro file. + lupdate warning: Specified target language '%1' disagrees with existing file's language '%2'. Ignoring. - За опцією -pro має слідувати ім'я .pro файлу. + попередження lupdate: Вказана мова перекладу '%1' не узгоджується з існуючою мовою файлу '%2'. Ігнорую. - The -I option should be followed by a path. + lupdate warning: Specified source language '%1' disagrees with existing file's language '%2'. Ignoring. - За опцією -l має слідувати шлях. + попередження lupdate: Вказана мова оригіналу '%1' не узгоджується з існуючою мовою файлу '%2'. Ігнорую. - Unrecognized option '%1'. + Updating '%1'... - Нерозпізнана опція '%1'. + Оновлюю '%1'... - lupdate error: List file '%1' is not readable. + Stripping non plural forms in '%1'... - помилка lupdate: Неможливо прочитати файл списку '%1'. + Видалення не множинних форм в '%1'... - lupdate warning: For some reason, '%1' is not writable. + lupdate warning: Codec for source '%1' is invalid. Falling back to codec for tr(). - попередження lupdate: З певних причин в '%1' не можливо записати. + попередження lupdate: Кодек для джерела '%1' неправильний. Повертаємось до використання кодеку для tr(). - lupdate error: File '%1' has no recognized extension. + lupdate warning: TS files from command line will override TRANSLATIONS in %1. - помилка lupdate: Файл '%1' має невідоме розширення. + попередження lupdate: файл-TS з командного рядка замінять TRANSLATIONS в %1. - lupdate error: File '%1' does not exist. + lupdate warning: TS files from command line prevent recursing into %1. - помилка lupdate: Файл '%1' не існує. + попередження lupdate: файли TS з командного рядка перешкоджають рекурсивному проходу %1. - lupdate warning: -target-language usually only makes sense with exactly one TS file. + lupdate warning: no TS files specified. Only diagnostics will be produced for '%1'. - попередження lupdate: Використання -target-language, зазвичай, має сенс лише з одним файлом TS. + попередження lupdate: не вказано файлів TS. Здійснюватиметься лише діагностика для '%1'. - lupdate warning: -codecfortr has no effect without -ts. + The option -target-language requires a parameter. - попередження lupdate: -codecfortr не дає ефекту без -ts. + Опція -target-language вимагає параметра. - lupdate warning: no TS files specified. Only diagnostics will be produced. + The option -source-language requires a parameter. - попередження lupdate: не вказано файлів TS. Здійснюватиметься лише діагностика. + Опція -source-language вимагає параметра. - lupdate error: Both project and source files / include paths specified. + The option -disable-heuristic requires a parameter. - помилка lupdate: Одночасно вказані файл проекту та вхідні файли / шляхи для включення. + Опція -disable-heuristic вимагає параметра. - - - MainWindow - MainWindow - Головне вікно + Invalid heuristic name passed to -disable-heuristic. + + Неправильна назва евристики для -disable-heuristic. + - &Phrases - Фра&зи + The option -locations requires a parameter. + + Опція -locations вимагає параметра. + - &Close Phrase Book - &Закрити глосарій + Invalid parameter passed to -locations. + + Неправильний параметр для -locations. + - &Edit Phrase Book - &Редагувати глосарій + The -codecfortr option should be followed by a codec name. + + За опцією -codecfortr має слідувати назва кодека. + - &Print Phrase Book - &Друк глосарію + The -extensions option should be followed by an extension list. + + За опцією -extensions має слідувати список розширень. + - V&alidation - Перев&ірка + The -pro option should be followed by a filename of .pro file. + + За опцією -pro має слідувати ім'я .pro файлу. + - &View - &Вид + The -I option should be followed by a path. + + За опцією -l має слідувати шлях. + - Vie&ws - &Види + Unrecognized option '%1'. + + Нерозпізнана опція '%1'. + - &Toolbars - Панелі &інструментів + lupdate error: List file '%1' is not readable. + + помилка lupdate: Неможливо прочитати файл списку '%1'. + - &Help - &Довідка + lupdate warning: For some reason, '%1' is not writable. + + попередження lupdate: З певних причин в '%1' не можливо записати. + - &Translation - Пере&клад + lupdate error: File '%1' has no recognized extension. + + помилка lupdate: Файл '%1' має невідоме розширення. + - &File - &Файл + lupdate error: File '%1' does not exist. + + помилка lupdate: Файл '%1' не існує. + - Recently Opened &Files - &Нещодавно відкриті файли + Scanning directory '%1'... + + Сканування теки '%1'... + - &Edit - &Правка + lupdate warning: -target-language usually only makes sense with exactly one TS file. + + попередження lupdate: Використання -target-language, зазвичай, має сенс лише з одним файлом TS. + - &Open... - &Відкрити... + lupdate warning: -codecfortr has no effect without -ts. + + попередження lupdate: -codecfortr не дає ефекту без -ts. + - Open a Qt translation source file (TS file) for editing - Відкрити файл перекладу Qt (файл TS) для редагування + lupdate warning: no TS files specified. Only diagnostics will be produced. + + попередження lupdate: не вказано файлів TS. Здійснюватиметься лише діагностика. + - Ctrl+O - + lupdate error: Both project and source files / include paths specified. + + помилка lupdate: Одночасно вказані файл проекту та вхідні файли / шляхи для включення. + - E&xit - Ви&йти + Parenthesis/bracket/brace mismatch between #if and #else branches; using #if branch + + Круглі/квадратні/фігурні дужки не збігаються між гілками #if та #else, використовую гілку #if + - Close this window and exit. - Закрити вікно та вийти. + Parenthesis/brace mismatch between #if and #else branches; using #if branch + + Круглі/фігурні дужки не збігаються між гілками #if та #else, використовую гілку #if + - Ctrl+Q - + Unterminated C++ comment + + Незавершений коментар C++ + - Save - Зберегти + Unterminated C++ string + + Незавершений рядок C++ + - Save changes made to this Qt translation source file - Зберегти зміни зроблені до цього файлу перекладу Qt + Excess closing brace in C++ code (or abuse of the C++ preprocessor) + + Забагато закриваючих фігурних дужок в коді C++ (або неправильне застосування препроцесора C++) + - Save &As... - Зберегти &як... + Excess closing parenthesis in C++ code (or abuse of the C++ preprocessor) + + Забагато закриваючих круглих дужок в коді C++ (або неправильне застосування препроцесора C++) + - Save As... - Зберегти як... + Excess closing bracket in C++ code (or abuse of the C++ preprocessor) + + Забагато закриваючих квадратних дужок в коді C++ (або неправильне застосування препроцесора C++) + - Save changes made to this Qt translation source file into a new file. - Зберегти зміни зроблені до цього файлу перекладу Qt до нового файлу. + Cannot open %1: %2 + Неможливо відкрити %1: %2 - Release - Скомпілювати + //% cannot be used with tr() / QT_TR_NOOP(). Ignoring + + //% не може бути використаний разом з tr() / QT_TR_NOOP(). Ігнорую + - Create a Qt message file suitable for released applications from the current message file. - Створити файл повідомлень Qt придатний для використання програмами з поточного файлу повідомлень. + circular inclusion of %1 + + циклічне вкладення %1 + - &Print... - &Друк... + Cannot open %1: %2 + + Неможливо відкрити %1: %2 + - Print a list of all the translation units in the current translation source file. - Друкувати список усіх елементів перекладу з поточного файлу перекладу. + Qualifying with unknown namespace/class %1::%2 + + Задаю з невідомим простором імен/класом %1::%2 + - Ctrl+P - + tr() cannot be called without context + + tr() не можна викликати без контексту + - &Undo - &Повернути + Class '%1' lacks Q_OBJECT macro + + У класу '%1' не вистачає макросу Q_OBJECT + - Undo the last editing operation performed on the current translation. - Скасувати останню операцію редагування здійснену над поточним перекладом. + It is not recommended to call tr() from within a constructor '%1::%2' + + Не рекомендовано викликати tr() з конструктора '%1::%2' + - Ctrl+Z - + //% cannot be used with translate() / QT_TRANSLATE_NOOP(). Ignoring + + //% не може бути використаний разом з translate() / QT_TRANSLATE_NOOP(). Ігнорую + - &Redo - П&овторити + //= cannot be used with qtTrId() / QT_TRID_NOOP(). Ignoring + + //= не може бути використаний разом з qtTrId() / QT_TRID_NOOP(). Ігнорую + - Redo an undone editing operation performed on the translation. - Повторити скасовану операцію редагування здійснену над поточним перекладом. + Unexpected character in meta string + + Неочікуваний символ в мета-рядку + - Ctrl+Y - + Unterminated meta string + + Незавершений мета-рядок + - Cu&t - Ви&різати + Cannot invoke tr() like this + + Неможливо викликати tr() подібним чином + - Copy the selected translation text to the clipboard and deletes it. - Копіювати виділений текст перекладу в буфер обміну та видалити його. + Discarding unconsumed meta data + + Відкидаю невжиті мета-дані + - Ctrl+X - + Unbalanced opening brace in C++ code (or abuse of the C++ preprocessor) + + Незбалансовані відкриваючі фігурні дужки в коді C++ (або неправильне застосування препроцесора C++) + - &Copy - &Копіювати + Unbalanced opening parenthesis in C++ code (or abuse of the C++ preprocessor) + + Незбалансовані відкриваючі круглі дужки в коді C++ (або неправильне застосування препроцесора C++) + - Copy the selected translation text to the clipboard. - Копіювати виділений текст перекладу до буферу обміну. + Unbalanced opening bracket in C++ code (or abuse of the C++ preprocessor) + + Незбалансовані відкриваючі квадратні дужки в коді C++ (або неправильне застосування препроцесора C++) + - Ctrl+C - + Unterminated Java comment. + + Незавершений коментар Java. + - &Paste - &Вставити + Invalid Unicode value. + + Неправильне значення Unicode. + - Paste the clipboard text into the translation. - Вставити текст з буферу обміну до перекладу. + Unterminated string. + + Незавершений рядок. + - Ctrl+V - + String used in translation can contain only literals concatenated with other literals, not expressions or numbers. + + Рядки, що використовуються в перекладі, можуть містити лише літерали об'єднані з іншими літералами, а не вирази або числа. + - Select &All - Виділити в&се - - - Select the whole translation text. - Виділити все текст перекладу. + 'class' must be followed by a class name. + + Після 'class' повинна слідувати назва класу. + - Ctrl+A - + Excess closing brace. + + Забагато закриваючих фігурних дужок. - &Find... - &Знайти... + 'package' must be followed by package name. + + Після 'package' повинна слідувати назва пакунку. + - Search for some text in the translation source file. - Шукати деякий текст в файлі перекладу. + Unbalanced opening brace. + + Незбалансовані відкриваючі фігурні дужки. + - Ctrl+F - + Unbalanced opening parenthesis. + + Незбалансовані відкриваючі круглі дужки. + - - Find &Next - Знайти &наступне + + Found %n source text(s) (%1 new and %2 already existing) + + + Знайдено %n оригінальний текст (%1 новий та %2 вже існує) + + Знайдено %n оригінальних тексти (%1 нових та %2 вже існує) + + Знайдено %n оригінальних текстів (%1 нових та %2 вже існує) + + - - Continue the search where it was left. - Продовжити пошук з місця, де він був зупинений. + + Removed %n obsolete entries + + + Видалено %n застарілий елемент + + Видалено %n застарілих елементи + + Видалено %n застарілих елементів + + - - F3 - + + Kept %n obsolete entries + + + Залишено %n застарілий елемент + + Залишено %n застарілих елементи + + Залишено %n застарілих елементів + + - - &Prev Unfinished - &Попередній незавершений + + Number heuristic provided %n translation(s) + + + Числова евристика надала %n переклад + + Числова евристика надала %n переклади + + Числова евристика надала %n перекладів + + - - Previous unfinished item - Попередній незавершений елемент + + Same-text heuristic provided %n translation(s) + + + Евристика "однаковий текст" надала %n переклад + + Евристика "однаковий текст" надала %n переклади + + Евристика "однаковий текст" надала %n перекладів + + - - Move to the previous unfinished item. - Перейти до попереднього незавершеного елементу. + + Similar-text heuristic provided %n translation(s) + + + Евристика "схожий текст" надала %n переклад + + Евристика "схожий текст" надала %n переклади + + Евристика "схожий текст" надала %n перекладів + + - Ctrl+K - + Illegal character + Неприпустимий символ - &Next Unfinished - &Наступний незавершений + Unclosed string at end of line + Незакритий рядок в кінці файлу - Next unfinished item - Наступний незавершений елемент + Illegal escape squence + Неприпустима керуюча послідовність - Move to the next unfinished item. - Перейти до наступного незавершеного елементу. + Illegal unicode escape sequence + Неприпустима керуюча послідовність Unicode - Ctrl+J - + Unclosed comment at end of file + Незакритий коментар в кінці файлу - P&rev - П&опередній + Illegal syntax for exponential number + Неприпустимий синтаксис для експоненційного числа - Move to previous item - Перейти до попереднього елементу + Identifier cannot start with numeric literal + Ідентифікатор не може починатись з числового літералу - Move to the previous item. - Перейти до попереднього елементу. + Unterminated regular expression literal + Незавершений літерал регулярного виразу - Ctrl+Shift+K - + //% cannot be used with %1(). Ignoring + + //% не може бути використаний разом з %1(). Ігнорую + - Ne&xt - Н&аступний + %1() requires at least two arguments. + + %1() вимагає щонайменше двох аргументів. + - Next item - Наступний елемент + %1(): both arguments must be literal strings. + + %1(): обидва аргументи повинні бути рядковими літералами. + - Move to the next item. - Перейти до наступного елементу. + %1() requires at least one argument. + + %1() вимагає щонайменше одного аргументу. + - Ctrl+Shift+J - + %1(): text to translate must be a literal string. + + %1(): текст для перекладу повинен бути рядковим літералом. + - &Done and Next - &Готово і наступний + //= cannot be used with %1(). Ignoring + + //= не може бути використаний разом з %1(). Ігнорую + - Mark item as done and move to the next unfinished item - Помітити елемент як завершений та перейти до наступного незавершеного елементу + %1(): identifier must be a literal string. + + %1(): ідентифікатор повинен бути рядковим літералом. + - Mark this item as done and move to the next unfinished item. - Помітити цей елемент як завершений та перейти до наступного незавершеного елементу. + Expected + Beginning of the string that contains comma-separated list of expected tokens + Очікувалось - Copy from source text - Копіювати з оригінального тексту + XML error: Parse error at line %1, column %2 (%3). + Помилка XML: Помилка розбору в рядку %1, позиція %2 (%3). - Copies the source text into the translation field - Копіює оригінальний текст в поле перекладу + Parse error in UI file + Помилка розбору файлу UI + + + MainWindow - Copies the source text into the translation field. - Копіює оригінальний текст в поле перекладу. + MainWindow + Головне вікно - Ctrl+B - + &Phrases + Фра&зи - &Accelerators - &Акселератори + &Close Phrase Book + &Закрити глосарій - Toggle the validity check of accelerators - Перемикання перевірки правильності акселераторів + &Edit Phrase Book + &Редагувати глосарій - Toggle the validity check of accelerators, i.e. whether the number of ampersands in the source and translation text is the same. If the check fails, a message is shown in the warnings window. - Перемикання перевірки акселераторів, тобто чи збігається кількість амперсандів в оригінальному та перекладеному тексті. Якщо буде виявлено розбіжність, то у вікні попереджень буде показано повідомлення. + &Print Phrase Book + &Друк глосарію - &Ending Punctuation - &Кінцева пунктуація + V&alidation + Перев&ірка - Toggle the validity check of ending punctuation - Перемикання перевірки правильності кінцевої пунктуації + &View + &Вид - Toggle the validity check of ending punctuation. If the check fails, a message is shown in the warnings window. - Перемикання перевірки кінцевої пунктуації. Якщо буде виявлено розбіжність, то у вікні попереджень буде показано повідомлення. + Vie&ws + &Види - &Phrase matches - Збіги &фраз + &Toolbars + Панелі &інструментів - Toggle checking that phrase suggestions are used - Перемикання перевірки, що пропозиції фраз були застосовані + &Help + &Довідка - Toggle checking that phrase suggestions are used. If the check fails, a message is shown in the warnings window. - Перемикання перевірки про використання запропонованих фраз. Якщо буде виявлено розбіжність, то у вікні попереджень буде показано повідомлення. + &Translation + Пере&клад - Place &Marker Matches - Збіги &маркерів положення + &File + &Файл - Toggle the validity check of place markers - Перемикання перевірки правильності маркерів розташування + Recently Opened &Files + &Нещодавно відкриті файли - Toggle the validity check of place markers, i.e. whether %1, %2, ... are used consistently in the source text and translation text. If the check fails, a message is shown in the warnings window. - Перемикання перевірки правильності маркерів розташування, тобто чи усі %1, %2, ... збігаються в оригінальному та перекладеному тексті. Якщо буде виявлено розбіжність, то у вікні попереджень буде показано повідомлення. + &Edit + &Правка - &New Phrase Book... - &Новий глосарій... + &Open... + &Відкрити... - Create a new phrase book. - Створити новий глосарій. + Open a Qt translation source file (TS file) for editing + Відкрити файл перекладу Qt (файл TS) для редагування - Ctrl+N + Ctrl+O - &Open Phrase Book... - &Відкрити глосарій... + E&xit + Ви&йти - Open a phrase book to assist translation. - Відкрити глосарій для допомоги в перекладі. + Close this window and exit. + Закрити вікно та вийти. - Ctrl+H + Ctrl+Q - &Reset Sorting - С&кинути сортування + Save + Зберегти - Sort the items back in the same order as in the message file. - Сортувати елементи в тому ж порядку, що й в файлі повідомлень. + Save changes made to this Qt translation source file + Зберегти зміни зроблені до цього файлу перекладу Qt - &Display guesses - &Показувати підказки + Save &As... + Зберегти &як... - Set whether or not to display translation guesses. - Встановлює показувати чи ні підказки перекладу. + Save As... + Зберегти як... - &Statistics - &Статистика + Save changes made to this Qt translation source file into a new file. + Зберегти зміни зроблені до цього файлу перекладу Qt до нового файлу. - Display translation statistics. - Показати статистку перекладу. - - - &Manual - &Посібник + Release + Скомпілювати - F1 - + Create a Qt message file suitable for released applications from the current message file. + Створити файл повідомлень Qt придатний для використання програмами з поточного файлу повідомлень. - About Qt Linguist - Про Qt Linguist + &Print... + &Друк... - About Qt - Про Qt + Print a list of all the translation units in the current translation source file. + Друкувати список усіх елементів перекладу з поточного файлу перекладу. - Display information about the Qt toolkit by Nokia. - Показати інформацію про інструментарій Qt від Nokia. + Ctrl+P + - &What's This? - &Що це? + &Undo + &Повернути - What's This? - Що це? + Undo the last editing operation performed on the current translation. + Скасувати останню операцію редагування здійснену над поточним перекладом. - Enter What's This? mode. - Перехід в режим "Що це?". + Ctrl+Z + - Shift+F1 - Shift+F1 + &Redo + П&овторити - &Search And Translate... - Знайти &та перекласти... + Redo an undone editing operation performed on the translation. + Повторити скасовану операцію редагування здійснену над поточним перекладом. - Replace the translation on all entries that matches the search source text. - Замінити переклад усіх елементів, що збігаються з оригінальним текстом, що шукається. + Ctrl+Y + - &Batch Translation... - Пакетний перекла&д... + Cu&t + Ви&різати - Batch translate all entries using the information in the phrase books. - Пакетно перекласти усі елементи використовуючи інформацію з глосаріїв. + Copy the selected translation text to the clipboard and deletes it. + Копіювати виділений текст перекладу в буфер обміну та видалити його. - Release As... - Скомпілювати як... + Ctrl+X + - Create a Qt message file suitable for released applications from the current message file. The filename will automatically be determined from the name of the TS file. - Створення файла повідомлень Qt придатного для використання програмами з поточного файлу повідомлень. Ім'я файла буде автоматично визначено з імені файлу TS. + &Copy + &Копіювати - File - Файл + Copy the selected translation text to the clipboard. + Копіювати виділений текст перекладу до буферу обміну. - Edit - Правка + Ctrl+C + - Translation - Переклад + &Paste + &Вставити - Validation - Перевірка + Paste the clipboard text into the translation. + Вставити текст з буферу обміну до перекладу. - Help - Довідка + Ctrl+V + - Open/Refresh Form &Preview - &Відкрити/оновити попередній перегляд форм + Select &All + Виділити в&се - Form Preview Tool - Засіб попереднього перегляду форм + Select the whole translation text. + Виділити все текст перекладу. - F5 + Ctrl+A - Translation File &Settings... - Налаштування &файлу перекладу... + &Find... + &Знайти... - &Add to Phrase Book - Дод&ати до глосарію + Search for some text in the translation source file. + Шукати деякий текст в файлі перекладу. - Ctrl+T + Ctrl+F - Open Read-O&nly... - Відкрити лише для &читання... + Find &Next + Знайти &наступне - &Save All - &Зберегти усе + Continue the search where it was left. + Продовжити пошук з місця, де він був зупинений. - Ctrl+S + F3 - &Release All - &Скомпілювати все + &Prev Unfinished + &Попередній незавершений - Close - Закрити + Previous unfinished item + Попередній незавершений елемент - &Close All - З&акрити усе + Move to the previous unfinished item. + Перейти до попереднього незавершеного елементу. - Ctrl+W + Ctrl+K - Length Variants - Варіанти перекладу + &Next Unfinished + &Наступний незавершений - - This is the application's main window. - Це головне вікно програми. - + Next unfinished item + Наступний незавершений елемент - Source text - Оригінальний текст + Move to the next unfinished item. + Перейти до наступного незавершеного елементу. - Index - Індекс + Ctrl+J + - Context - Контекст + P&rev + П&опередній - Items - Елементи + Move to previous item + Перейти до попереднього елементу - This panel lists the source contexts. - В цій панелі перераховані оригінальні контексти. + Move to the previous item. + Перейти до попереднього елементу. - Strings - Рядки + Ctrl+Shift+K + - Phrases and guesses - Фрази та підказки + Ne&xt + Н&аступний - Sources and Forms - Коди та форми + Next item + Наступний елемент - Warnings - Попередження + Move to the next item. + Перейти до наступного елементу. - MOD - status bar: file(s) modified - ЗМІ + Ctrl+Shift+J + - Loading... - Завантажується... + &Done and Next + &Готово і наступний - Loading File - Qt Linguist - Завантаження файлу - Qt Linguist + Mark item as done and move to the next unfinished item + Помітити елемент як завершений та перейти до наступного незавершеного елементу - The file '%1' does not seem to be related to the currently open file(s) '%2'. - -Close the open file(s) first? - Не схоже, що файл '%1' пов'язаний з жодним з відкритим зараз файлом '%2'. - -Закрити спочатку відкриті файли? + Mark this item as done and move to the next unfinished item. + Помітити цей елемент як завершений та перейти до наступного незавершеного елементу. - The file '%1' does not seem to be related to the file '%2' which is being loaded as well. - -Skip loading the first named file? - Не схоже, що файл '%1' пов'язаний з файлом '%2', що також завантажується. - -Пропустити завантаження першого вказаного файлу? + Copy from source text + Копіювати з оригінального тексту - - %n translation unit(s) loaded. - - %n одиниця перекладу завантажена. - %n одиниці перекладу завантажені. - %n одиниць перекладу завантажено. - + + Copies the source text into the translation field + Копіює оригінальний текст в поле перекладу - Related files (%1);; - Пов'язані файли (%1);; + Copies the source text into the translation field. + Копіює оригінальний текст в поле перекладу. - Open Translation Files - Відкрити файли перекладу + Ctrl+B + - File saved. - Файл збережено. + &Accelerators + &Акселератори - Qt message files for released applications (*.qm) -All files (*) - Файли повідомлень Qt для готовий програм (*.qm) -Всі файли (*) + Toggle the validity check of accelerators + Перемикання перевірки правильності акселераторів - File created. - Файл створено. + Toggle the validity check of accelerators, i.e. whether the number of ampersands in the source and translation text is the same. If the check fails, a message is shown in the warnings window. + Перемикання перевірки акселераторів, тобто чи збігається кількість амперсандів в оригінальному та перекладеному тексті. Якщо буде виявлено розбіжність, то у вікні попереджень буде показано повідомлення. - Printing... - Друкується... + &Ending Punctuation + &Кінцева пунктуація - Context: %1 - Контекст: %1 + Toggle the validity check of ending punctuation + Перемикання перевірки правильності кінцевої пунктуації - finished - завершено + Toggle the validity check of ending punctuation. If the check fails, a message is shown in the warnings window. + Перемикання перевірки кінцевої пунктуації. Якщо буде виявлено розбіжність, то у вікні попереджень буде показано повідомлення. - unresolved - нерозв'язаний + &Phrase matches + Збіги &фраз - obsolete - застарілий + Toggle checking that phrase suggestions are used + Перемикання перевірки, що пропозиції фраз були застосовані - Printing... (page %1) - Друк... (сторінка %1) + Toggle checking that phrase suggestions are used. If the check fails, a message is shown in the warnings window. + Перемикання перевірки про використання запропонованих фраз. Якщо буде виявлено розбіжність, то у вікні попереджень буде показано повідомлення. - Printing completed - Друк завершено + Place &Marker Matches + Збіги &маркерів положення - Printing aborted - Друк перервано + Toggle the validity check of place markers + Перемикання перевірки правильності маркерів розташування - Search wrapped. - Пошук з початку. + Toggle the validity check of place markers, i.e. whether %1, %2, ... are used consistently in the source text and translation text. If the check fails, a message is shown in the warnings window. + Перемикання перевірки правильності маркерів розташування, тобто чи усі %1, %2, ... збігаються в оригінальному та перекладеному тексті. Якщо буде виявлено розбіжність, то у вікні попереджень буде показано повідомлення. - Qt Linguist - Qt Linguist + &New Phrase Book... + &Новий глосарій... - Cannot find the string '%1'. - Неможливо знайти рядок '%1. + Create a new phrase book. + Створити новий глосарій. - Search And Translate in '%1' - Qt Linguist - Пошук та переклад і '%1' - Qt Linguist + Ctrl+N + - Translate - Qt Linguist - Переклад - Qt Linguist - - - Translated %n entry(s) - - Перекладено %n елемент - Перекладено %n елементи - Перекладено %n елементів - + &Open Phrase Book... + &Відкрити глосарій... - No more occurrences of '%1'. Start over? - Більше збігів '%1' немає. Почати спочатку? + Open a phrase book to assist translation. + Відкрити глосарій для допомоги в перекладі. - Create New Phrase Book - Створити новий глосарій + Ctrl+H + - Qt phrase books (*.qph) -All files (*) - Глосарії Q (*.qph) -Всі файли (*) + &Reset Sorting + С&кинути сортування - Phrase book created. - Глосарій створено. + Sort the items back in the same order as in the message file. + Сортувати елементи в тому ж порядку, що й в файлі повідомлень. - Open Phrase Book - Відкрити глосарій + &Display guesses + &Показувати підказки - Qt phrase books (*.qph);;All files (*) - Глосарії Q (*.qph);;Всі файли (*) + Set whether or not to display translation guesses. + Встановлює показувати чи ні підказки перекладу. - - %n phrase(s) loaded. - - %n фразу завантажено. - %n фрази завантажено. - %n фраз завантажено. - + + &Statistics + &Статистика - Add to phrase book - Додати до глосарію + Display translation statistics. + Показати статистку перекладу. - No appropriate phrasebook found. - Не знайдено відповідного глосарію. + &Manual + &Посібник - Adding entry to phrasebook %1 - Додавання елементу до глосарію %1 + F1 + - Select phrase book to add to - Оберіть глосарій, в який бажаєте додати + About Qt Linguist + Про Qt Linguist - Unable to launch Qt Assistant (%1) - Неможливо запустити Qt Assistant (%1) + About Qt + Про Qt - Version %1 - Версія %1 + Display information about the Qt toolkit by Nokia. + Показати інформацію про інструментарій Qt від Nokia. - <center><img src=":/images/splash.png"/></img><p>%1</p></center><p>Qt Linguist is a tool for adding translations to Qt applications.</p><p>Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). - <center><img src=":/images/splash.png"/></img><p>%1</p></center><p>Qt Linguist - це засіб для додавання перекладів до програм на Qt.</p><p>Copyright (C) 2010 Корпорація Nokia та/або її дочірні компанії. + &What's This? + &Що це? - Do you want to save the modified files? - Бажаєте зберегти модифіковані файли? + What's This? + Що це? - Do you want to save '%1'? - Бажаєте зберегти '%1'? + Enter What's This? mode. + Перехід в режим "Що це?". - Qt Linguist[*] - Qt Linguist[*] + Shift+F1 + Shift+F1 - %1[*] - Qt Linguist - %1[*] - Qt Linguist + &Search And Translate... + Знайти &та перекласти... - No untranslated translation units left. - Неперекладених одиниць не залишилось. + Replace the translation on all entries that matches the search source text. + Замінити переклад усіх елементів, що збігаються з оригінальним текстом, що шукається. - &Window - Вікн&о + &Batch Translation... + Пакетний перекла&д... - Minimize - Мінімізувати + Batch translate all entries using the information in the phrase books. + Пакетно перекласти усі елементи використовуючи інформацію з глосаріїв. - Ctrl+M - + Release As... + Скомпілювати як... - Display the manual for %1. - Показати посібник для %1. + Create a Qt message file suitable for released applications from the current message file. The filename will automatically be determined from the name of the TS file. + Створення файла повідомлень Qt придатного для використання програмами з поточного файлу повідомлень. Ім'я файла буде автоматично визначено з імені файлу TS. - Display information about %1. - Показати інформацію про %1. + File + Файл - &Save '%1' - &Зберегти '%1' + Edit + Правка - Save '%1' &As... - Зберегти '%1' &як... + Translation + Переклад - Release '%1' - Скомпілювати '%1' + Validation + Перевірка - Release '%1' As... - Скомпілювати '%1' як... + Help + Довідка - &Close '%1' - З&акрити '%1' + Open/Refresh Form &Preview + &Відкрити/оновити попередній перегляд форм - &Save - &Зберегти + Form Preview Tool + Засіб попереднього перегляду форм - &Close - З&акрити + F5 + - Save All - Зберегти усе + Translation File &Settings... + Налаштування &файлу перекладу... - Close All - Закрити усе + &Add to Phrase Book + Дод&ати до глосарію - &Release - &Скомпілювати + Ctrl+T + - Translation File &Settings for '%1'... - Налаштування &файлу перекладу для '%1'... + Open Read-O&nly... + Відкрити лише для &читання... - &Batch Translation of '%1'... - Пакетний перекла&д '%1'... + &Save All + &Зберегти усе - Search And &Translate in '%1'... - Знайти &та переклад '%1'... + Ctrl+S + - Search And &Translate... - Знайти &та перекласти... + &Release All + &Скомпілювати все - Cannot read from phrase book '%1'. - Неможливо прочитати з глосарію '%1'. + Close + Закрити - Close this phrase book. - Закрити цей глосарій. + &Close All + З&акрити усе - Enables you to add, modify, or delete entries in this phrase book. - Дозволяє вам додавати, модифікувати та видаляти елементи глосарію. + Ctrl+W + - Print the entries in this phrase book. - Друку елементів цього глосарію. + Length Variants + Варіанти перекладу - Cannot create phrase book '%1'. - Неможливо створити глосарій '%1'. + + This is the application's main window. + Це головне вікно програми. + - Do you want to save phrase book '%1'? - Бажаєте зберегти глосарій '%1'? + Source text + Оригінальний текст - All - Усе + Index + Індекс - - - MessageEditor - - This is the right panel of the main window. - Це права панель основного вікна. - + Context + Контекст - Russian - Російська + Items + Елементи - German - Німецька + This panel lists the source contexts. + В цій панелі перераховані оригінальні контексти. - Japanese - Японська + Strings + Рядки - French - Французька + Phrases and guesses + Фрази та підказки - Polish - Польська + Sources and Forms + Коди та форми - Chinese - Китайська + Warnings + Попередження - This whole panel allows you to view and edit the translation of some source text. - Ця панель дозволяє вам переглядати та редагувати переклад деякого оригінального тексту. + MOD + status bar: file(s) modified + ЗМІ - Source text - Оригінальний текст + Loading... + Завантажується... - This area shows the source text. - В цій області відображається оригінальний текст. + Loading File - Qt Linguist + Завантаження файлу - Qt Linguist - Source text (Plural) - Оригінальний текст (множина) + The file '%1' does not seem to be related to the currently open file(s) '%2'. + +Close the open file(s) first? + Не схоже, що файл '%1' пов'язаний з жодним з відкритим зараз файлом '%2'. + +Закрити спочатку відкриті файли? - This area shows the plural form of the source text. - В цій області відображається множина оригінального тексту. + The file '%1' does not seem to be related to the file '%2' which is being loaded as well. + +Skip loading the first named file? + Не схоже, що файл '%1' пов'язаний з файлом '%2', що також завантажується. + +Пропустити завантаження першого вказаного файлу? + + + %n translation unit(s) loaded. + + %n одиниця перекладу завантажена. + %n одиниці перекладу завантажені. + %n одиниць перекладу завантажено. + - Developer comments - Коментарі розробника + Related files (%1);; + Пов'язані файли (%1);; - This area shows a comment that may guide you, and the context in which the text occurs. - В цій області відображається коментар, який може допомогти вам та контекст, в якому зустрічається текст. + Open Translation Files + Відкрити файли перекладу - Here you can enter comments for your own use. They have no effect on the translated applications. - Тут ви можете вводити коментарі для власного вжитку. Вони не впливають на перекладені програми. + File saved. + Файл збережено. - %1 translation (%2) - %1 переклад (%2) + Qt message files for released applications (*.qm) +All files (*) + Файли повідомлень Qt для готовий програм (*.qm) +Всі файли (*) - This is where you can enter or modify the translation of the above source text. - Тут ви можете чи змінювати переклад оригінального тексту, наведеного вище. + File created. + Файл створено. - %1 translation - %1 переклад + Printing... + Друкується... - %1 translator comments - %1 коментар перекладача + Context: %1 + Контекст: %1 - '%1' -Line: %2 - '%1' -Рядок: %2 + finished + завершено - - - MessageModel - Completion status for %1 - Статус завершеності для %1 + unresolved + нерозв'язаний - <file header> - <заголовок файлу> + obsolete + застарілий - <context comment> - <контекстний коментар> + Printing... (page %1) + Друк... (сторінка %1) - <unnamed context> - <контекст без назви> + Printing completed + Друк завершено - - - PhraseBookBox - Edit Phrase Book - Редагування глосарію + Printing aborted + Друк перервано - This window allows you to add, modify, or delete entries in a phrase book. - Це вікно дозволяє вам додавати, модифікувати та видаляти елементи глосарію. + Search wrapped. + Пошук з початку. - &Translation: - &Переклад: + Qt Linguist + Qt Linguist - This is the phrase in the target language corresponding to the source phrase. - Це фраза на мові перекладу, що відповідає оригінальній фразі. + Cannot find the string '%1'. + Неможливо знайти рядок '%1. - S&ource phrase: - &Оригінальна фраза: + Search And Translate in '%1' - Qt Linguist + Пошук та переклад і '%1' - Qt Linguist - This is a definition for the source phrase. - Це визначення оригінальної фрази. + Translate - Qt Linguist + Переклад - Qt Linguist + + + Translated %n entry(s) + + Перекладено %n елемент + Перекладено %n елементи + Перекладено %n елементів + - This is the phrase in the source language. - Це фраза мовою оригіналу. + No more occurrences of '%1'. Start over? + Більше збігів '%1' немає. Почати спочатку? - &Definition: - &Визначення: + Create New Phrase Book + Створити новий глосарій - Click here to add the phrase to the phrase book. - Клацніть тут, щоб додати фразу до глосарію. + Qt phrase books (*.qph) +All files (*) + Глосарії Q (*.qph) +Всі файли (*) - &New Entry - &Новий запис + Phrase book created. + Глосарій створено. - Click here to remove the entry from the phrase book. - Клацніть тут, щоб видалити фразу з глосарію. + Open Phrase Book + Відкрити глосарій - &Remove Entry - Ви&далити запис + Qt phrase books (*.qph);;All files (*) + Глосарії Q (*.qph);;Всі файли (*) + + + %n phrase(s) loaded. + + %n фразу завантажено. + %n фрази завантажено. + %n фраз завантажено. + - Settin&gs... - Нала&штування... + Add to phrase book + Додати до глосарію - Click here to save the changes made. - Клацніть тут, щоб зберегти зроблені зміни. + No appropriate phrasebook found. + Не знайдено відповідного глосарію. - &Save - &Зберегти + Adding entry to phrasebook %1 + Додавання елементу до глосарію %1 - Click here to close this window. - Клацніть тут щоб закрити вікно. + Select phrase book to add to + Оберіть глосарій, в який бажаєте додати - Close - Закрити + Unable to launch Qt Assistant (%1) + Неможливо запустити Qt Assistant (%1) - - Go to Phrase > Edit Phrase Book... The dialog that pops up is a PhraseBookBox. - Йдіть в Фрази > Редагувати глосарій... З'явиться діалог PhraseBookBox. - + Version %1 + Версія %1 - (New Entry) - (Новий запис) + <center><img src=":/images/splash.png"/></img><p>%1</p></center><p>Qt Linguist is a tool for adding translations to Qt applications.</p><p>Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). + <center><img src=":/images/splash.png"/></img><p>%1</p></center><p>Qt Linguist - це засіб для додавання перекладів до програм на Qt.</p><p>Copyright (C) 2010 Корпорація Nokia та/або її дочірні компанії. + + + Do you want to save the modified files? + Бажаєте зберегти модифіковані файли? + + + Do you want to save '%1'? + Бажаєте зберегти '%1'? + + + Qt Linguist[*] + Qt Linguist[*] %1[*] - Qt Linguist %1[*] - Qt Linguist - Qt Linguist - Qt Linguist + No untranslated translation units left. + Неперекладених одиниць не залишилось. - Cannot save phrase book '%1'. - Неможливо зберегти глосарій '%1'. + &Window + Вікн&о - - - PhraseModel - Source phrase - Оригінальна фраза + Minimize + Мінімізувати - Translation - Переклад + Ctrl+M + - Definition - Визначення + Display the manual for %1. + Показати посібник для %1. - - - PhraseView - Insert - Вставити + Display information about %1. + Показати інформацію про %1. - Edit - Редагувати + &Save '%1' + &Зберегти '%1' - Guess (%1) - Підказка (%1) + Save '%1' &As... + Зберегти '%1' &як... - Guess - Підказка + Release '%1' + Скомпілювати '%1' - - - QCoreApplication - Usage: - lrelease [options] project-file - lrelease [options] ts-files [-qm qm-file] - -lrelease is part of Qt's Linguist tool chain. It can be used as a -stand-alone tool to convert XML-based translations files in the TS -format into the 'compiled' QM format used by QTranslator objects. - -Options: - -help Display this information and exit - -idbased - Use IDs instead of source strings for message keying - -compress - Compress the QM files - -nounfinished - Do not include unfinished translations - -removeidentical - If the translated text is the same as - the source text, do not include the message - -markuntranslated <prefix> - If a message has no real translation, use the source text - prefixed with the given string instead - -silent - Do not explain what is being done - -version - Display the version of lrelease and exit - - Використання: - lrelease [опції] файл-проект - lrelease [опції] файли-ts [-qm файл-qm] - -lrelease - це частина набору програм Qt Linguist. Вона може використовуватися -як окремий засіб для перетворення файлів перекладу на базі XML в форматі TS -до 'скомпільованого' формату QM, що використовується об'єктами QTranslator. - -Опції: - -help Показати цю інформацію та вийти - -idbased - Використовувати ID замість рядків оригіналу як ключі повідомлень - -compress - Стискати файли QM - -nounfinished - Не включати незавершені переклади - -removeidentical - Якщо перекладений текст однаковий з оригіналом, то - не включати повідомлення - -markuntranslated <prefix> - If a message has no real translation, use the source text - prefixed with the given string instead - -silent - Не пояснювати, що відбувається - -version - Показати версію lrelease та вийти - + Release '%1' As... + Скомпілювати '%1' як... + + + &Close '%1' + З&акрити '%1' + + + &Save + &Зберегти + + + &Close + З&акрити + + + Save All + Зберегти усе + + + Close All + Закрити усе + + + &Release + &Скомпілювати + + + Translation File &Settings for '%1'... + Налаштування &файлу перекладу для '%1'... + + + &Batch Translation of '%1'... + Пакетний перекла&д '%1'... + + + Search And &Translate in '%1'... + Знайти &та переклад '%1'... + + + Search And &Translate... + Знайти &та перекласти... + + + Cannot read from phrase book '%1'. + Неможливо прочитати з глосарію '%1'. + + + Close this phrase book. + Закрити цей глосарій. + + + Enables you to add, modify, or delete entries in this phrase book. + Дозволяє вам додавати, модифікувати та видаляти елементи глосарію. + + + Print the entries in this phrase book. + Друку елементів цього глосарію. + + + Cannot create phrase book '%1'. + Неможливо створити глосарій '%1'. + + + Do you want to save phrase book '%1'? + Бажаєте зберегти глосарій '%1'? + + + All + Усе + + + + MessageEditor + + + This is the right panel of the main window. + Це права панель основного вікна. + + + + Russian + Російська + + + German + Німецька + + + Japanese + Японська + + + French + Французька + + + Polish + Польська + + + Chinese + Китайська + + + This whole panel allows you to view and edit the translation of some source text. + Ця панель дозволяє вам переглядати та редагувати переклад деякого оригінального тексту. + + + Source text + Оригінальний текст + + + This area shows the source text. + В цій області відображається оригінальний текст. + + + Source text (Plural) + Оригінальний текст (множина) + + + This area shows the plural form of the source text. + В цій області відображається множина оригінального тексту. + + + Developer comments + Коментарі розробника + + + This area shows a comment that may guide you, and the context in which the text occurs. + В цій області відображається коментар, який може допомогти вам та контекст, в якому зустрічається текст. + + + Here you can enter comments for your own use. They have no effect on the translated applications. + Тут ви можете вводити коментарі для власного вжитку. Вони не впливають на перекладені програми. + + + %1 translation (%2) + %1 переклад (%2) + + + This is where you can enter or modify the translation of the above source text. + Тут ви можете чи змінювати переклад оригінального тексту, наведеного вище. + + + %1 translation + %1 переклад + + + %1 translator comments + %1 коментар перекладача + + + '%1' +Line: %2 + '%1' +Рядок: %2 + + + + MessageModel + + Completion status for %1 + Статус завершеності для %1 + + + <file header> + <заголовок файлу> + + + <context comment> + <контекстний коментар> + + + <unnamed context> + <контекст без назви> + + + + PhraseBook + + Parse error at line %1, column %2 (%3). + Помилка розбору в рядку %1, позиція %2 (%3). + + + + PhraseBookBox + + Edit Phrase Book + Редагування глосарію + + + This window allows you to add, modify, or delete entries in a phrase book. + Це вікно дозволяє вам додавати, модифікувати та видаляти елементи глосарію. + + + &Translation: + &Переклад: + + + This is the phrase in the target language corresponding to the source phrase. + Це фраза на мові перекладу, що відповідає оригінальній фразі. + + + S&ource phrase: + &Оригінальна фраза: + + + This is a definition for the source phrase. + Це визначення оригінальної фрази. + + + This is the phrase in the source language. + Це фраза мовою оригіналу. + + + &Definition: + &Визначення: + + + Click here to add the phrase to the phrase book. + Клацніть тут, щоб додати фразу до глосарію. + + + &New Entry + &Новий запис + + + Click here to remove the entry from the phrase book. + Клацніть тут, щоб видалити фразу з глосарію. + + + &Remove Entry + Ви&далити запис + + + Settin&gs... + Нала&штування... + + + Click here to save the changes made. + Клацніть тут, щоб зберегти зроблені зміни. + + + &Save + &Зберегти + + + Click here to close this window. + Клацніть тут щоб закрити вікно. + + + Close + Закрити + + + + Go to Phrase > Edit Phrase Book... The dialog that pops up is a PhraseBookBox. + Йдіть в Фрази > Редагувати глосарій... З'явиться діалог PhraseBookBox. + + + + (New Entry) + (Новий запис) - Updating '%1'... - - Оновлюю '%1'... - + %1[*] - Qt Linguist + %1[*] - Qt Linguist - Removing translations equal to source text in '%1'... - - Видалення перекладів однакових з оригінальним текстом в '%1'... - + Qt Linguist + Qt Linguist - lrelease version %1 - - lrelease версії %1 - + Cannot save phrase book '%1'. + Неможливо зберегти глосарій '%1'. + + + + PhraseModel + + Source phrase + Оригінальна фраза + + + Translation + Переклад + + + Definition + Визначення + + + + PhraseView + + Insert + Вставити + + + Edit + Редагувати + + + Guess (%1) + Підказка (%1) + + + Guess + Підказка @@ -1681,215 +2402,11 @@ lrelease - це частина набору програм Qt Linguist. Вона Файли локалізації XLIFF - Usage: - lupdate [options] [project-file]... - lupdate [options] [source-file|path|@lst-file]... -ts ts-files|@lst-file - -lupdate is part of Qt's Linguist tool chain. It extracts translatable -messages from Qt UI files, C++, Java and JavaScript/QtScript source code. -Extracted messages are stored in textual translation source files (typically -Qt TS XML). New and modified messages can be merged into existing TS files. - -Options: - -help Display this information and exit. - -no-obsolete - Drop all obsolete strings. - -extensions <ext>[,<ext>]... - Process files with the given extensions only. - The extension list must be separated with commas, not with whitespace. - Default: '%1'. - -pluralonly - Only include plural form messages. - -silent - Do not explain what is being done. - -no-sort - Do not sort contexts in TS files. - -no-recursive - Do not recursively scan the following directories. - -recursive - Recursively scan the following directories (default). - -I <includepath> or -I<includepath> - Additional location to look for include files. - May be specified multiple times. - -locations {absolute|relative|none} - Specify/override how source code references are saved in TS files. - Default is absolute. - -no-ui-lines - Do not record line numbers in references to UI files. - -disable-heuristic {sametext|similartext|number} - Disable the named merge heuristic. Can be specified multiple times. - -pro <filename> - Name of a .pro file. Useful for files with .pro file syntax but - different file suffix. Projects are recursed into and merged. - -source-language <language>[_<region>] - Specify the language of the source strings for new files. - Defaults to POSIX if not specified. - -target-language <language>[_<region>] - Specify the language of the translations for new files. - Guessed from the file name if not specified. - -ts <ts-file>... - Specify the output file(s). This will override the TRANSLATIONS - and nullify the CODECFORTR from possibly specified project files. - -codecfortr <codec> - Specify the codec assumed for tr() calls. Effective only with -ts. - -version - Display the version of lupdate and exit. - @lst-file - Read additional file names (one per line) from lst-file. - - Використання: - lupdate [опції] [файл-проект]... - lupdate [опції] [вхідний-файл|шлях|@файл-список]... -ts ts-файли|@файл-список - -lupdate - це частина набору програм Qt Linguist. Вона It витягає придатні для перекладу -повідомлення з файлів Qt UI, коду C++, Java та JavaScript/QtScript. Витягнуті повідомлення -зберігаються в текстовому файлі перекладу (типово Qt TS XML). Нові та модифіковані -повідомлення можуть бути об'єднанні з існуючими файлами TS. - -Опції: - -help Показати цю інформацію та вийти. - -no-obsolete - Видалити всі застарілі рядки. - -extensions <розширення>[,<розширення>]... - Обробляти файли лише з вказаними розширеннями. - Список розширень має розділюватись комами, а не пропусками. - Типово: '%1'. - -pluralonly - Включати лише повідомлення з формою множини. - -silent - Не пояснювати, що відбувається. - -no-sort - Не сортувати контексти в файлах TS. - -no-recursive - Не сканувати рекурсивно наступні теки. - -recursive - Рекурсивно сканувати наступні теки (типово). - -I <шлях-включення> або -I<шлях-включення> - Додаткові місця для пошуку файлів включення. - Може бути вказано декілька разів. - -locations {absolute|relative|none} - Вказати/замістити як посилання на код зберігаються в файлі TS. - Типово - абсолютно. - -no-ui-lines - Не записувати номери рядків в посиланнях на файли UI. - -disable-heuristic {sametext|similartext|number} - Вимкнути вказану евристику об'єдання. Може бути вказано декілька разів. - -pro <ім'я-файлу> - Ім'я .pro файлу. Корисно для файлів із синтаксисом фалів .pro, але з - іншим розширенням. Projects are recursed into and merged. - -source-language <мова>[_<регіон>] - Вказати мову оригінальних рядків для нових файлів. - Типово, якщо не вказано - POSIX. - -target-language <мова>[_<регіон>] - Вказати мову перекладу для нових файлів. - Вгадується з імені файла, якщо не вказано. - -ts <файл-ts>... - Вказати вихідний файл(и). Це замістить TRANSLATIONS - та скине CODECFORTR з, можливо, вказаних файлів проекту. - -codecfortr <кодек> - Вказати кодек, що Specify the codec вживається для викликів tr(). Ефективно лише з -ts. - -version - Показати версію lupdate та вийти. - @файл-список - Читати додаткові імена файлів (одне на рядок) з файла-списку. - - - - Updating '%1'... - - Оновлюю '%1'... - - - - Stripping non plural forms in '%1'... - - Видалення не множинних форм в '%1'... - - - lupdate version %1 lupdate версії %1 - - Scanning directory '%1'... - - Сканування теки '%1'... - - - - Found %n source text(s) (%1 new and %2 already existing) - - - Знайдено %n оригінальний текст (%1 новий та %2 вже існує) - - Знайдено %n оригінальних тексти (%1 нових та %2 вже існує) - - Знайдено %n оригінальних текстів (%1 нових та %2 вже існує) - - - - - Removed %n obsolete entries - - - Видалено %n застарілий елемент - - Видалено %n застарілих елементи - - Видалено %n застарілих елементів - - - - - Kept %n obsolete entries - - - Залишено %n застарілий елемент - - Залишено %n застарілих елементи - - Залишено %n застарілих елементів - - - - - Number heuristic provided %n translation(s) - - - Числова евристика надала %n переклад - - Числова евристика надала %n переклади - - Числова евристика надала %n перекладів - - - - - Same-text heuristic provided %n translation(s) - - - Евристика "однаковий текст" надала %n переклад - - Евристика "однаковий текст" надала %n переклади - - Евристика "однаковий текст" надала %n перекладів - - - - - Similar-text heuristic provided %n translation(s) - - - Евристика "схожий текст" надала %n переклад - - Евристика "схожий текст" надала %n переклади - - Евристика "схожий текст" надала %n перекладів - - - SourceCodeView diff --git a/translations/qt_help_uk.ts b/translations/qt_help_uk.ts index b8bc984..32e47b4 100644 --- a/translations/qt_help_uk.ts +++ b/translations/qt_help_uk.ts @@ -106,7 +106,7 @@ QHelpEngineCore Cannot open documentation file %1: %2! - Не можу відкрити файл документації %1: %2! + Неможливо відкрити файл документації %1: %2! The specified namespace does not exist! @@ -256,7 +256,7 @@ The input file %1 could not be opened! - Неможливо відкрити вхідний файл %1! + Не вдалось відкрити вхідний файл %1! diff --git a/translations/qt_uk.ts b/translations/qt_uk.ts index 7a223f4..e1716fb 100644 --- a/translations/qt_uk.ts +++ b/translations/qt_uk.ts @@ -1697,25 +1697,6 @@ to - QDeclarativeCompositeTypeManager - - Resource %1 unavailable - Ресурс %1 недоступний - - - Namespace %1 cannot be used as a type - Простір імен %1 не може бути використаний як тип - - - %1 %2 - %1 %2 - - - Type %1 unavailable - Тип %1 недоступний - - - QDeclarativeConnections Cannot assign to non-existent property "%1" @@ -2096,6 +2077,25 @@ to + QDeclarativeTypeData + + Script %1 unavailable + + + + Type %1 unavailable + Тип %1 недоступний + + + Namespace %1 cannot be used as a type + Простір імен %1 не може бути використаний як тип + + + %1 %2 + %1 %2 + + + QDeclarativeVME Unable to create object of type %1 @@ -3313,18 +3313,10 @@ Do you want to delete it anyway? QLibrary - Could not mmap '%1': %2 - Не вдалося виконати mmap '%1': %2 - - Plugin verification data mismatch in '%1' Дані верифікації додатку не збігаються для ’%1’ - Could not unmap '%1': %2 - Не вдалося виконати unmap '%1': %2 - - The shared library was not found. Динамічна бібліотека не знайдена. @@ -7917,7 +7909,7 @@ Do you want to overwrite it? QtXmlPatterns %1 is an unsupported encoding. - + Кодування %1 не підтримується. %1 contains octets which are disallowed in the requested encoding %2. @@ -7941,23 +7933,23 @@ Do you want to overwrite it? Year %1 is invalid because it begins with %2. - + Рік %1 неправильний, бо він починається з %2. Day %1 is outside the range %2..%3. - + День %1 поза межами діапазону %2..%3. Month %1 is outside the range %2..%3. - + Місяць %1 поза межами діапазону %2..%3. Overflow: Can't represent date %1. - + Переповнення: Не можу представити дату %1. Day %1 is invalid for month %2. - + Неправильний день %1 для місяця %2. Time 24:%1:%2.%3 is invalid. Hour is 24, but minutes, seconds, and milliseconds are not all 0; @@ -7965,15 +7957,15 @@ Do you want to overwrite it? Time %1:%2:%3.%4 is invalid. - + Неправильний час %1:%2:%3.%4. Overflow: Date can't be represented. - + Переповнення: Не можу представити дату. At least one component must be present. - + Щонайменше один компонент має бути присутнім. At least one time component must appear after the %1-delimiter. @@ -7981,7 +7973,7 @@ Do you want to overwrite it? %1 is not a valid value of type %2. - + %1 не є правильним значенням для типу %2. When casting to %1 from %2, the source value cannot be %3. @@ -7989,11 +7981,11 @@ Do you want to overwrite it? Integer division (%1) by zero (%2) is undefined. - + Цілочисельне ділення (%1) на нуль (%2) не визначене. Division (%1) by zero (%2) is undefined. - + Ділення (%1) на нуль (%2) не визначене. Modulus division (%1) by zero (%2) is undefined. @@ -8021,11 +8013,11 @@ Do you want to overwrite it? Value %1 of type %2 exceeds maximum (%3). - + Значення %1 типу %2 перевищує максимум (%3). Value %1 of type %2 is below minimum (%3). - + Значення %1 типу %2 менше за мінімум (%3). A value of type %1 must contain an even number of digits. The value %2 does not. @@ -8033,7 +8025,7 @@ Do you want to overwrite it? %1 is not valid as a value of type %2. - + %1 не є правильним значенням для типу %2. Ambiguous rule match. @@ -8041,11 +8033,11 @@ Do you want to overwrite it? Operator %1 cannot be used on type %2. - + Оператор %1 не може використовуватись для типу %2. Operator %1 cannot be used on atomic values of type %2 and %3. - + Оператор %1 не може використовуватись для атомарних значень типу %2 та %3. The namespace URI in the name for a computed attribute cannot be %1. @@ -8065,11 +8057,11 @@ Do you want to overwrite it? A comment cannot contain %1 - + Коментар не може містити %1 A comment cannot end with a %1. - + Коментар не може закінчувати на %1. In a namespace constructor, the value for a namespace cannot be an empty string. @@ -8081,7 +8073,7 @@ Do you want to overwrite it? The prefix %1 cannot be bound. - + Неможливо прив'язати префікс %1. Only the prefix %1 can be bound to %2 and vice versa. @@ -8147,12 +8139,16 @@ Do you want to overwrite it? %1 takes at most %n argument(s). %2 is therefore invalid. + + %1 requires at least %n argument(s). %2 is therefore invalid. + + @@ -8169,7 +8165,7 @@ Do you want to overwrite it? %1 is not a valid XML 1.0 character. - + %1 не є правильним символом XML 1.0. The root node of the second argument to function %1 must be a document node. %2 is not a document node. @@ -8257,11 +8253,11 @@ Do you want to overwrite it? The item %1 did not match the required type %2. - + Елемент %1 не відповідає необхідному типу %2. The variable %1 is unused - + Змінна %1 не використовується W3C XML Schema identity constraint selector @@ -8301,7 +8297,7 @@ Do you want to overwrite it? Version %1 is not supported. The supported XQuery version is 1.0. - + Версія %1 не підтримується. Підтримується XQuery версії 1.0. The encoding %1 is invalid. It must contain Latin characters only, must not contain whitespace, and must match the regular expression %2. @@ -8357,7 +8353,7 @@ Do you want to overwrite it? The module import feature is not supported - + Можливість імпорту модулів не підтримується A variable with name %1 has already been declared. @@ -8517,7 +8513,7 @@ Do you want to overwrite it? Parse error: %1 - + Помилка розбору: %1 The value of the XSL-T version attribute must be a value of type %1, which %2 isn't. @@ -8529,7 +8525,7 @@ Do you want to overwrite it? Unknown XSL-T attribute %1. - + Невідомий атрибут XSL-T %1. Attribute %1 and %2 are mutually exclusive. @@ -9041,11 +9037,11 @@ Do you want to overwrite it? %1 attribute of %2 element contains invalid content: {%3} is not a value of type %4. - + Атрибут %1 елемента %2 містить неправильний вміст: {%3} не є значенням типу %4. %1 attribute of %2 element contains invalid content: {%3}. - + Атрибут %1 елемента %2 містить неправильний вміст: {%3}. Target namespace %1 of included schema is different from the target namespace %2 as defined by the including schema. @@ -9077,7 +9073,7 @@ Do you want to overwrite it? %1 attribute of %2 element must be %3 or %4. - + Атрибут %1 елемента %2 має бути %3 або %4. %1 attribute of %2 element must have a value of %3. @@ -9157,7 +9153,7 @@ Do you want to overwrite it? Type %1 already defined. - + Тип %1 вже визначено. Attribute group %1 already defined. @@ -9297,7 +9293,7 @@ Do you want to overwrite it? %1 is not valid according to %2. - + %1 не є правильним відповідно до %2. String content does not match the length facet. @@ -9697,7 +9693,7 @@ Do you want to overwrite it? zero or one - + нуль чи один exactly one @@ -9705,15 +9701,15 @@ Do you want to overwrite it? one or more - + один чи більше zero or more - + нуль чи більше Required type is %1, but %2 was found. - + Вимагається тип %1, але знайдено %2. Promoting %1 to %2 may cause loss of precision. @@ -9721,7 +9717,7 @@ Do you want to overwrite it? The focus is undefined. - + Фокус не визначено. It's not possible to add attributes after any other kind of node. diff --git a/translations/qvfb_uk.ts b/translations/qvfb_uk.ts index 0e0c5da6..e857e9d 100644 --- a/translations/qvfb_uk.ts +++ b/translations/qvfb_uk.ts @@ -215,7 +215,7 @@ DeviceSkin The image file '%1' could not be loaded. - Неможливо завантажити файл зображення '%1'. + Не вдалось завантажити файл зображення '%1'. The skin directory '%1' does not contain a configuration file. @@ -223,11 +223,11 @@ The skin configuration file '%1' could not be opened. - Неможливо відкрити файл налаштувань '%1'. + Не вдалось відкрити файл налаштувань обкладинки '%1'. The skin configuration file '%1' could not be read: %2 - Неможливо прочитати файл налаштувань '%1': %2 + Не вдалось прочитати файл налаштувань обкладинки '%1': %2 Syntax error: %1 @@ -261,6 +261,126 @@ QVFb + &File + &Файл + + + &Configure... + &Налаштувати... + + + &Save image... + &Зберегти зображення... + + + &Animation... + &Анімація... + + + &Quit + Ви&йти + + + &View + &Вид + + + Show &Cursor + Показувати &курсор + + + &Refresh Rate... + Швидкість &оновлення... + + + &No rotation + &Без обертання + + + &90° rotation + Обернути на &90° + + + 1&80° rotation + Обернути на 1&80° + + + 2&70° rotation + Обернути на 2&70° + + + Zoom scale &0.5 + Коефіцієнт масштабування &0.5 + + + Zoom scale 0.7&5 + Коефіцієнт масштабування 0.7&5 + + + Zoom scale &1 + Коефіцієнт масштабування &1 + + + Zoom scale &2 + Коефіцієнт масштабування &2 + + + Zoom scale &3 + Коефіцієнт масштабування &3 + + + Zoom scale &4 + Коефіцієнт масштабування &4 + + + Zoom &scale... + Коефіцієнт &масштабування... + + + &Help + &Довідка + + + &About... + &Про... + + + Save Main Screen image + Зберегти зображення головного екрану + + + snapshot.png + + + + Portable Network Graphics (*.png) + Переносима мережева графіка (*.png) + + + Save Main Screen Image + Зберегти зображення головного екрану + + + Save failed. Check that you have permission to write to the target directory. + Збій збереження. Перевірте чи маєте ви право на запис в теку збереження. + + + Save Second Screen image + Зберегти зображення другого екрану + + + Save Second Screen Image + Зберегти зображення другого екрану + + + About QVFB + Про QVFB + + + <h2>The Qt for Embedded Linux Virtual X11 Framebuffer</h2><p>This application runs under Qt for X11, emulating a simple framebuffer, which the Qt for Embedded Linux server and clients can attach to just as if it was a hardware Linux framebuffer. <p>With the aid of this development tool, you can develop Qt for Embedded Linux applications under X11 without having to switch to a virtual console. This means you can comfortably use your other development tools such as GUI profilers and debuggers. + <h2>Віртуальний фреймбуфер X11 Qt для Embedded Linux</h2><p>Ця програма виконується під Qt для X11, емулюючи простий фреймбуфер, до якого сервер та клієнти Qt для Embedded Linux можуть приєднуватись так само, як би це був апаратний фреймбуфер Linux. <p>За допомогою цього інструменту ви можете розробляти програми Qt для Embedded Linux під X11, без потреби перемикатись на віртуальну консоль. Це означає, що ви можете зручно використовувати інші ваші інструменти розробки, такі як профайлери та зневаджувачі з графічним інтерфейсом користувача. + + Browse... Оглянути... @@ -273,4 +393,23 @@ Усі обкладинки QVFB (*.skin) + + QVFbRateDialog + + Target frame rate: + Швидкість оновлення: + + + %1fps + %1 кадрів в секунду + + + OK + + + + Cancel + Скасувати + + -- cgit v0.12 From 41a8c2280a3f454c457f811fc6428826b11b4754 Mon Sep 17 00:00:00 2001 From: Alessandro Portale Date: Thu, 2 Sep 2010 21:33:06 +0200 Subject: Symbian: return better default font for SansSerif style hint The latest QtWebkit will use QFont::defaultFamily() with style hints to ask for the appropriate default fonts on a system. This patch makes sure thath "Nokia Sans S60" and "Series 60 Sans" are prioritized for QFont::SansSerif, if they are present. Task-Number: QTBUG-12611 --- src/gui/text/qfont_s60.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/gui/text/qfont_s60.cpp b/src/gui/text/qfont_s60.cpp index f303419..2d547a9 100644 --- a/src/gui/text/qfont_s60.cpp +++ b/src/gui/text/qfont_s60.cpp @@ -40,6 +40,7 @@ ****************************************************************************/ #include "qfont.h" +#include "qfont_p.h" #include #include #include "qmutex.h" @@ -48,6 +49,17 @@ QT_BEGIN_NAMESPACE #ifdef QT_NO_FREETYPE Q_GLOBAL_STATIC(QMutex, lastResortFamilyMutex); +Q_GLOBAL_STATIC_WITH_INITIALIZER(QStringList, fontFamiliesOnFontServer, { + QSymbianFbsHeapLock lock(QSymbianFbsHeapLock::Unlock); + const int numTypeFaces = S60->screenDevice()->NumTypefaces(); + for (int i = 0; i < numTypeFaces; i++) { + TTypefaceSupport typefaceSupport; + S60->screenDevice()->TypefaceSupport(typefaceSupport, i); + const QString familyName((const QChar *)typefaceSupport.iTypeface.iName.Ptr(), typefaceSupport.iTypeface.iName.Length()); + x->append(familyName); + } + lock.relock(); +}); #endif // QT_NO_FREETYPE QString QFont::lastResortFamily() const @@ -84,6 +96,21 @@ QString QFont::lastResortFamily() const QString QFont::defaultFamily() const { +#ifdef QT_NO_FREETYPE + switch(d->request.styleHint) { + case QFont::SansSerif: { + static const char* const preferredSansSerif[] = {"Nokia Sans S60", "Series 60 Sans"}; + for (int i = 0; i < sizeof preferredSansSerif / sizeof preferredSansSerif[0]; ++i) { + const QString sansSerif = QLatin1String(preferredSansSerif[i]); + if (fontFamiliesOnFontServer()->contains(sansSerif)) + return sansSerif; + } + } + // No break. Intentional fall through. + default: + return lastResortFamily(); + } +#endif // QT_NO_FREETYPE return lastResortFamily(); } -- cgit v0.12 From 6939815182b31ab865184e40991eb339ff21ba2d Mon Sep 17 00:00:00 2001 From: Aaron McCarthy Date: Tue, 31 Aug 2010 16:33:41 +1000 Subject: Fix potential KERN-EXEC 0 on Symbian. SymbianEngine::updateConfigurationsL cannot be called from a non-main thread as it uses Symbian resources not shared between threads. Task-number: QTBUG-13064 --- src/plugins/bearer/symbian/qnetworksession_impl.cpp | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/plugins/bearer/symbian/qnetworksession_impl.cpp b/src/plugins/bearer/symbian/qnetworksession_impl.cpp index 2091898..7f81397 100644 --- a/src/plugins/bearer/symbian/qnetworksession_impl.cpp +++ b/src/plugins/bearer/symbian/qnetworksession_impl.cpp @@ -968,11 +968,17 @@ QNetworkConfiguration QNetworkSessionPrivateImpl::activeConfiguration(TUint32 ia } } else { #ifdef SNAP_FUNCTIONALITY_AVAILABLE - // On Symbian^3 (only, not earlier or Symbian^4) if the SNAP was not reachable, it triggers - // user choice type of activity (EasyWLAN). As a result, a new IAP may be created, and - // hence if was not found yet. Therefore update configurations and see if there is something new. + // On Symbian^3 (only, not earlier or Symbian^4) if the SNAP was not reachable, it + // triggers user choice type of activity (EasyWLAN). As a result, a new IAP may be + // created, and hence if was not found yet. Therefore update configurations and see if + // there is something new. + // 1. Update knowledge from the databases. - engine->requestUpdate(); + if (thread() != engine->thread()) + QMetaObject::invokeMethod(engine, "requestUpdate", Qt::BlockingQueuedConnection); + else + engine->requestUpdate(); + // 2. Check if new configuration was created during connection creation QList knownConfigs = engine->accessPointConfigurationIdentifiers(); #ifdef QT_BEARERMGMT_SYMBIAN_DEBUG @@ -1025,7 +1031,12 @@ QNetworkConfiguration QNetworkSessionPrivateImpl::activeConfiguration(TUint32 ia } else { // Check if new (WLAN) IAP was created in IAP/SNAP dialog // 1. Sync internal configurations array to commsdb first - engine->updateConfigurations(); + if (thread() != engine->thread()) { + QMetaObject::invokeMethod(engine, "requestUpdate", + Qt::BlockingQueuedConnection); + } else { + engine->requestUpdate(); + } // 2. Check if new configuration was created during connection creation QStringList knownConfigs = engine->accessPointConfigurationIdentifiers(); if (knownConfigs.count() > iKnownConfigsBeforeConnectionStart.count()) { -- cgit v0.12 From fc4d386f2cc8984b98957d83d8cdb57c1105890f Mon Sep 17 00:00:00 2001 From: Lorn Potter Date: Fri, 3 Sep 2010 13:49:36 +1000 Subject: protect nil dictionary from release. Task-number: QTBUG-13335 --- src/plugins/bearer/corewlan/qcorewlanengine.mm | 85 ++++++++++++++------------ 1 file changed, 47 insertions(+), 38 deletions(-) diff --git a/src/plugins/bearer/corewlan/qcorewlanengine.mm b/src/plugins/bearer/corewlan/qcorewlanengine.mm index 131f36d..844e38b 100644 --- a/src/plugins/bearer/corewlan/qcorewlanengine.mm +++ b/src/plugins/bearer/corewlan/qcorewlanengine.mm @@ -305,50 +305,53 @@ void QScanThread::getUserConfigurations() SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, (CFStringRef)@"Qt corewlan", nil, nil); NSDictionary * airportPlist = (NSDictionary *)SCDynamicStoreCopyValue(dynRef, (CFStringRef)[NSString stringWithFormat:@"Setup:/Network/Interface/%@/AirPort", nsInterfaceName]); CFRelease(dynRef); - - NSDictionary *prefNetDict = [airportPlist objectForKey:@"PreferredNetworks"]; - - NSArray *thisSsidarray = [prefNetDict valueForKey:@"SSID_STR"]; - for(NSString *ssidkey in thisSsidarray) { - QString thisSsid = qt_mac_NSStringToQString(ssidkey); - if(!userProfiles.contains(thisSsid)) { - QMap map; - map.insert(thisSsid, qt_mac_NSStringToQString(nsInterfaceName)); - userProfiles.insert(thisSsid, map); + if(airportPlist != nil) { + NSDictionary *prefNetDict = [airportPlist objectForKey:@"PreferredNetworks"]; + + NSArray *thisSsidarray = [prefNetDict valueForKey:@"SSID_STR"]; + for(NSString *ssidkey in thisSsidarray) { + QString thisSsid = qt_mac_NSStringToQString(ssidkey); + if(!userProfiles.contains(thisSsid)) { + QMap map; + map.insert(thisSsid, qt_mac_NSStringToQString(nsInterfaceName)); + userProfiles.insert(thisSsid, map); + } } + CFRelease(airportPlist); } - CFRelease(airportPlist); // 802.1X user profiles QString userProfilePath = QDir::homePath() + "/Library/Preferences/com.apple.eap.profiles.plist"; NSDictionary* eapDict = [[[NSDictionary alloc] initWithContentsOfFile:qt_mac_QStringToNSString(userProfilePath)] autorelease]; - NSString *profileStr= @"Profiles"; - NSString *nameStr = @"UserDefinedName"; - NSString *networkSsidStr = @"Wireless Network"; - for (id profileKey in eapDict) { - if ([profileStr isEqualToString:profileKey]) { - NSDictionary *itemDict = [eapDict objectForKey:profileKey]; - for (id itemKey in itemDict) { - - NSInteger dictSize = [itemKey count]; - id objects[dictSize]; - id keys[dictSize]; - - [itemKey getObjects:objects andKeys:keys]; - QString networkName; - QString ssid; - for(int i = 0; i < dictSize; i++) { - if([nameStr isEqualToString:keys[i]]) { - networkName = qt_mac_NSStringToQString(objects[i]); - } - if([networkSsidStr isEqualToString:keys[i]]) { - ssid = qt_mac_NSStringToQString(objects[i]); - } - if(!userProfiles.contains(networkName) - && !ssid.isEmpty()) { - QMap map; - map.insert(ssid, qt_mac_NSStringToQString(nsInterfaceName)); - userProfiles.insert(networkName, map); + if(eapDict != nil) { + NSString *profileStr= @"Profiles"; + NSString *nameStr = @"UserDefinedName"; + NSString *networkSsidStr = @"Wireless Network"; + for (id profileKey in eapDict) { + if ([profileStr isEqualToString:profileKey]) { + NSDictionary *itemDict = [eapDict objectForKey:profileKey]; + for (id itemKey in itemDict) { + + NSInteger dictSize = [itemKey count]; + id objects[dictSize]; + id keys[dictSize]; + + [itemKey getObjects:objects andKeys:keys]; + QString networkName; + QString ssid; + for(int i = 0; i < dictSize; i++) { + if([nameStr isEqualToString:keys[i]]) { + networkName = qt_mac_NSStringToQString(objects[i]); + } + if([networkSsidStr isEqualToString:keys[i]]) { + ssid = qt_mac_NSStringToQString(objects[i]); + } + if(!userProfiles.contains(networkName) + && !ssid.isEmpty()) { + QMap map; + map.insert(ssid, qt_mac_NSStringToQString(nsInterfaceName)); + userProfiles.insert(networkName, map); + } } } } @@ -855,6 +858,8 @@ quint64 QCoreWlanEngine::startTime(const QString &id) NSString *filePath = @"/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist"; NSDictionary* plistDict = [[[NSDictionary alloc] initWithContentsOfFile:filePath] autorelease]; + if(plistDict == nil) + return timestamp; NSString *input = @"KnownNetworks"; NSString *timeStampStr = @"_timeStamp"; @@ -864,9 +869,13 @@ quint64 QCoreWlanEngine::startTime(const QString &id) if ([input isEqualToString:key]) { NSDictionary *knownNetworksDict = [plistDict objectForKey:key]; + if(knownNetworksDict == nil) + return timestamp; for (id networkKey in knownNetworksDict) { bool isFound = false; NSDictionary *itemDict = [knownNetworksDict objectForKey:networkKey]; + if(itemDict == nil) + return timestamp; NSInteger dictSize = [itemDict count]; id objects[dictSize]; id keys[dictSize]; -- cgit v0.12