SailfishOS Logic: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
 
(Clean)
 
(7 intermediate revisions by 2 users not shown)
Line 1: Line 1:
'''English''' | [[SailfishOS Polish|Polski]]
{{Cleanup | reason=Auto-imported from ExpressionEngine.}}


=Logic=
[[Category:SailfishOS]]


Except showing nice pages containig widgets full of data usually application has to do some tasks to manipulate the data(in fact it is very common to treat providing data as a task itself). Obviously complexity of tasks vary between diffrent applications and use cases, but even the simplest ones maybe very important. For example the ‘add two given numbers’ opration in a calculator app is a very simple logic but without it the calculator app wouldn’t be very useful.
{{LangSwitch}}


==Available technology==
Except showing nice pages containig widgets full of data usually application has to do some tasks to manipulate the data(in fact it is very common to treat providing data as a task itself). Obviously complexity of tasks vary between diffrent applications and use cases, but even the simplest ones maybe very important. For example the 'add two given numbers' opration in a calculator app is a very simple logic but without it the calculator app wouldn't be very useful.
 
== Available technology ==


Currently there are three languages supported for implementing business logic. However SailfishOS offically support two of them(which are btw. standard solution for Qt/QML apps):
Currently there are three languages supported for implementing business logic. However SailfishOS offically support two of them(which are btw. standard solution for Qt/QML apps):
Line 12: Line 14:
* '''Javascript'''
* '''Javascript'''


Except C++ and Javascript there is also partial support for '''Python''' scripts. However it is not available to put apps based on python into [https://harbour.jolla.com/ jolla harbour] ''[harbour.jolla.com]'' yet, but you can still install them on devices manually. More info [https://wiki.merproject.org/wiki/Sailfish/Python_Development here] ''[wiki.merproject.org]''.
Except C+++ and Javascript there is also partial support for '''Python''' scripts. However it is not available to put apps based on python into [https://harbour.jolla.com/ jolla harbour] yet, but you can still install them on devices manually. More info [https://wiki.merproject.org/wiki/Sailfish/Python_Development here].  


==How can I put logic into my apps?==
== How can I put logic into my apps? ==


You can do it either implicitly write logic as a functions in qml file or explicitly call logic from external file. The implicit approach is only available with Javascript and it’s recommended only with simple routines. The external solution can be done with all of the supported technology and it’s considered as better approach. It lets you decouple code responsible for logic and code responsible for behaviour or appearence which is significat advantage while working on bigger projects.
You can do it either implicitly - write logic as a functions in qml file or explicitly - call logic from external file. The implicit approach is only available with Javascript and it's recommended only with simple routines. The external solution can be done with all of the supported technology and it's considered as better approach. It lets you decouple code responsible for logic and code responsible for behaviour or appearence which is significat advantage while working on bigger projects.


==C++==
== C++ ==




==Javascript==
== Javascript ==
 
Presented sinippets come from tutorial project 'calqlator' which is appeneded to SailfishOS IDE.
 
==== Importing external logic - .qml ====
 
<code>[…]
import "content/calculator.js" as CalcEngine
[…]
Rectangle {
[…]
function operatorPressed(operator) { CalcEngine.operatorPressed(operator) }
function digitPressed(digit) { CalcEngine.digitPressed(digit) }
[…]</code>


Presented sinippets come from tutorial project ‘calqlator’ which is appeneded to SailfishOS <span class="caps">IDE</span>.
==== Implicit behaviour code - .qml. ====


====Importing external logic – \calqlatr\qml\calqlatr.qml====
<code>[…]
Item {
[…]
function displayOperator(operator)
{
listView.model.append({ "operator": operator, "operand": "" })
enteringDigits = true
}
[…]
function appendDigit(digit)
{
if (!enteringDigits)
listView.model.append({ "operator": "", "operand": "" })
var i = listView.model.count - 1;
listView.model.get(i).operand = listView.model.get(i).operand + digit;
enteringDigits = true
}
[…]</code>


====Implicit behaviour code – \calqlatr\qml\content\Display.qml.====
==== Calling external functions - .qml. ====


====Calling external functions – \calqlatr\qml\content\Button.qml.====
<code>[…]
MouseArea {
[…]
onClicked: {
//parent.clicked()
if (operator)
window.operatorPressed(parent.text)
else
window.digitPressed(parent.text)
}
}
[…]</code>


====External module with logic \calqlatr\qml\content\calculator.js.====
==== External module with logic - .js. ====
 
<code>[…]
function disabled(op) {
if (op  "." && digits.toString().search(/\./) != -1) {
        return true
    } else if (op  window.squareRoot && digits.toString().search(/-/) != -1) {
return true
} else {
return false
}
}
 
function digitPressed(op)
{
if (disabled(op))
return
if (digits.toString().length >= 14)
return
if (lastOp.toString().length  1 && ((lastOp >= "0" && lastOp <= "9") || lastOp  ".") ) {
digits = digits + op.toString()
display.appendDigit(op.toString())
} else {
digits = op
display.appendDigit(op.toString())
}
lastOp = op
}
[…]</code>




==Python==


Currently the best approach to develop with python on SailfishOS is to use PyOtherSide qml plugin, as it was mentioned before it should be supported in jolla harbour soon. [http://pyotherside.readthedocs.org/en/latest/ Here] ''[pyotherside.readthedocs.org]'' you can find documentation of PyOtherSide. It contains some examples and describes general idea.
== Python ==
Currently the best approach to develop with python on SailfishOS is to use PyOtherSide qml plugin, as it was mentioned before it should be supported in jolla harbour soon. [http://pyotherside.readthedocs.org/en/latest/ Here] you can find documentation of PyOtherSide. It contains some examples and describes general idea.


Before deploying apps with PyOtherSide on targets with SailfishOS you need to follow guides from [https://lists.sailfishos.org/pipermail/devel/2013-September/000782.html this article] ''[lists.sailfishos.org]''. Generally you need to instal python3 and PyOtherSide plugin on target machine(either device or emulator). Please read it before trying to build example code presented below.
Before deploying apps with PyOtherSide on targets with SailfishOS you need to follow guides from [https://lists.sailfishos.org/pipermail/devel/2013-September/000782.html this article]. Generally you need to instal python3 and PyOtherSide plugin on target machine(either device or emulator). Please read it before trying to build example code presented below.


====External module with logic ProjectName\qml\pages\duration.py====
==== External module with logic- ProjectName\qml\pages\duration.py ====
<code>import os
import struct
import pyotherside


====Calling external functions – \calqlatr\qml\content\Page.qml.====
def get_item_list(count):
items = [
{ 'name': 'first' },
{ 'name': 'second' },
{ 'name': 'third' },
{ 'name': 'fourth' },
{ 'name': 'fifth' },
{ 'name': 'sixth' },
{ 'name': 'seventh' },
{ 'name': 'eight' },
{ 'name': 'ninth' },
{ 'name': 'tenth' },
]
return items[:count]


====Entry point for qml pages – \calqlatr\qml\ProjectName.qml.====
def get_other_item_list():
items = [
{ 'name': 'it works' },
{ 'name': 'like' },
{ 'name': 'charm' },
{ 'name': 'really!' },
]
return items[:]


pyotherside.atexit(get_item_list)
pyotherside.atexit(get_other_item_list)</code>
 
==== Calling external functions - .qml. ====
 
<code>import QtQuick 2.0
import Sailfish.Silica 1.0
import io.thp.pyotherside 1.0
 
Page {
id: page
 
Python {
id:py
Component.onCompleted: {
 
addImportPath(Qt.resolvedUrl('.').substr('file://'.length));
 
importModule('duration', function() {
call('duration.get_item_list', [5], function(result){
for (var i=0; i<result.length; i+'') {
listModel.append(result[i]);
}
});
});
}
onError: console.log('Python error: ''' traceback)
}
 
SilicaListView {
PullDownMenu {
MenuItem {
text: "Option 1"
onClicked: py.call('duration.get_other_item_list',[], function(result){
for (var i=0; i<result.length; i+'') {
listModel.append(result[i]);
}
});
}
}
id: listView
model: ListModel{
id: listModel
}
 
anchors.fill: parent
 
delegate: BackgroundItem {
id: delegate
 
Label {
x: Theme.paddingLarge
text: name'' " item"
anchors.verticalCenter: parent.verticalCenter
color: delegate.highlighted ? Theme.highlightColor : Theme.primaryColor
}
onClicked: console.log("Clicked " + name)
}
VerticalScrollDecorator {}
 
}
}</code>
 
==== Entry point for qml pages - .qml. ====
 
<code>import QtQuick 2.0
import Sailfish.Silica 1.0
import "pages"


===Categories:===
ApplicationWindow
{
initialPage: Component { Page { } }
}</code>


* [[:Category:SailfishOS|SailfishOS]]
** [[:Category:SailfishOS::Developer guide|Developer_guide]]

Latest revision as of 02:15, 27 March 2016

This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine.
Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean.

En Ar Bg De El Es Fa Fi Fr Hi Hu It Ja Kn Ko Ms Nl Pl Pt Ru Sq Th Tr Uk Zh

Except showing nice pages containig widgets full of data usually application has to do some tasks to manipulate the data(in fact it is very common to treat providing data as a task itself). Obviously complexity of tasks vary between diffrent applications and use cases, but even the simplest ones maybe very important. For example the 'add two given numbers' opration in a calculator app is a very simple logic but without it the calculator app wouldn't be very useful.

Available technology

Currently there are three languages supported for implementing business logic. However SailfishOS offically support two of them(which are btw. standard solution for Qt/QML apps):

  • C++
  • Javascript

Except C+++ and Javascript there is also partial support for Python scripts. However it is not available to put apps based on python into jolla harbour yet, but you can still install them on devices manually. More info here.

How can I put logic into my apps?

You can do it either implicitly - write logic as a functions in qml file or explicitly - call logic from external file. The implicit approach is only available with Javascript and it's recommended only with simple routines. The external solution can be done with all of the supported technology and it's considered as better approach. It lets you decouple code responsible for logic and code responsible for behaviour or appearence which is significat advantage while working on bigger projects.

C++

Javascript

Presented sinippets come from tutorial project 'calqlator' which is appeneded to SailfishOS IDE.

Importing external logic - .qml

[]
import "content/calculator.js" as CalcEngine
[]
Rectangle {
 []
 function operatorPressed(operator) { CalcEngine.operatorPressed(operator) }
 function digitPressed(digit) { CalcEngine.digitPressed(digit) }
[]

Implicit behaviour code - .qml.

[]
Item {
 []
 function displayOperator(operator)
 {
 listView.model.append({ "operator": operator, "operand": "" })
 enteringDigits = true
 }
 []
 function appendDigit(digit)
 {
 if (!enteringDigits)
 listView.model.append({ "operator": "", "operand": "" })
 var i = listView.model.count - 1;
 listView.model.get(i).operand = listView.model.get(i).operand + digit;
 enteringDigits = true
 }
[]

Calling external functions - .qml.

[]
MouseArea {
 []
 onClicked: {
 //parent.clicked()
 if (operator)
 window.operatorPressed(parent.text)
 else
 window.digitPressed(parent.text)
 }
 }
[]

External module with logic - .js.

[]
function disabled(op) {
 if (op  "." && digits.toString().search(/\./) != -1) {
        return true
    } else if (op  window.squareRoot && digits.toString().search(/-/) != -1) {
 return true
 } else {
 return false
 }
}

function digitPressed(op)
{
 if (disabled(op))
 return
 if (digits.toString().length >= 14)
 return
 if (lastOp.toString().length  1 && ((lastOp >= "0" && lastOp <= "9") || lastOp  ".") ) {
 digits = digits + op.toString()
 display.appendDigit(op.toString())
 } else {
 digits = op
 display.appendDigit(op.toString())
 }
 lastOp = op
}
[]


Python

Currently the best approach to develop with python on SailfishOS is to use PyOtherSide qml plugin, as it was mentioned before it should be supported in jolla harbour soon. Here you can find documentation of PyOtherSide. It contains some examples and describes general idea.

Before deploying apps with PyOtherSide on targets with SailfishOS you need to follow guides from this article. Generally you need to instal python3 and PyOtherSide plugin on target machine(either device or emulator). Please read it before trying to build example code presented below.

External module with logic- ProjectName\qml\pages\duration.py

import os
import struct
import pyotherside

def get_item_list(count):
 items = [
 { 'name': 'first' },
 { 'name': 'second' },
 { 'name': 'third' },
 { 'name': 'fourth' },
 { 'name': 'fifth' },
 { 'name': 'sixth' },
 { 'name': 'seventh' },
 { 'name': 'eight' },
 { 'name': 'ninth' },
 { 'name': 'tenth' },
 ]
 return items[:count]

def get_other_item_list():
 items = [
 { 'name': 'it works' },
 { 'name': 'like' },
 { 'name': 'charm' },
 { 'name': 'really!' },
 ]
 return items[:]

pyotherside.atexit(get_item_list)
pyotherside.atexit(get_other_item_list)

Calling external functions - .qml.

import QtQuick 2.0
import Sailfish.Silica 1.0
import io.thp.pyotherside 1.0

Page {
 id: page

Python {
 id:py
 Component.onCompleted: {

addImportPath(Qt.resolvedUrl('.').substr('file://'.length));

importModule('duration', function() {
 call('duration.get_item_list', [5], function(result){
 for (var i=0; i<result.length; i+'') {
 listModel.append(result[i]);
 }
 });
 });
 }
 onError: console.log('Python error: ''' traceback)
 }

SilicaListView {
 PullDownMenu {
 MenuItem {
 text: "Option 1"
 onClicked: py.call('duration.get_other_item_list',[], function(result){
 for (var i=0; i<result.length; i+'') {
 listModel.append(result[i]);
 }
 });
 }
 }
 id: listView
 model: ListModel{
 id: listModel
 }

 anchors.fill: parent

 delegate: BackgroundItem {
 id: delegate

 Label {
 x: Theme.paddingLarge
 text: name'' " item"
 anchors.verticalCenter: parent.verticalCenter
 color: delegate.highlighted ? Theme.highlightColor : Theme.primaryColor
 }
 onClicked: console.log("Clicked " + name)
 }
 VerticalScrollDecorator {}

}
}

Entry point for qml pages - .qml.

import QtQuick 2.0
import Sailfish.Silica 1.0
import "pages"

ApplicationWindow
{
 initialPage: Component { Page { } }
}