code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.admin.vo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import ims.framework.enumerations.SortOrder;
/**
* Linked to core.clinical.coding.snomed_concept business object (ID: 1065100006).
*/
public class TaxonomySnomedConceptVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<TaxonomySnomedConceptVo>
{
private static final long serialVersionUID = 1L;
private ArrayList<TaxonomySnomedConceptVo> col = new ArrayList<TaxonomySnomedConceptVo>();
public String getBoClassName()
{
return "ims.core.clinical.coding.domain.objects.snomed_concept";
}
public boolean add(TaxonomySnomedConceptVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
return this.col.add(value);
}
return false;
}
public boolean add(int index, TaxonomySnomedConceptVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
this.col.add(index, value);
return true;
}
return false;
}
public void clear()
{
this.col.clear();
}
public void remove(int index)
{
this.col.remove(index);
}
public int size()
{
return this.col.size();
}
public int indexOf(TaxonomySnomedConceptVo instance)
{
return col.indexOf(instance);
}
public TaxonomySnomedConceptVo get(int index)
{
return this.col.get(index);
}
public boolean set(int index, TaxonomySnomedConceptVo value)
{
if(value == null)
return false;
this.col.set(index, value);
return true;
}
public void remove(TaxonomySnomedConceptVo instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public boolean contains(TaxonomySnomedConceptVo instance)
{
return indexOf(instance) >= 0;
}
public Object clone()
{
TaxonomySnomedConceptVoCollection clone = new TaxonomySnomedConceptVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
if(this.col.get(x) != null)
clone.col.add((TaxonomySnomedConceptVo)this.col.get(x).clone());
else
clone.col.add(null);
}
return clone;
}
public boolean isValidated()
{
for(int x = 0; x < col.size(); x++)
if(!this.col.get(x).isValidated())
return false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(col.size() == 0)
return null;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
for(int x = 0; x < col.size(); x++)
{
String[] listOfOtherErrors = this.col.get(x).validate();
if(listOfOtherErrors != null)
{
for(int y = 0; y < listOfOtherErrors.length; y++)
{
listOfErrors.add(listOfOtherErrors[y]);
}
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
return null;
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
return result;
}
public TaxonomySnomedConceptVoCollection sort()
{
return sort(SortOrder.ASCENDING);
}
public TaxonomySnomedConceptVoCollection sort(boolean caseInsensitive)
{
return sort(SortOrder.ASCENDING, caseInsensitive);
}
public TaxonomySnomedConceptVoCollection sort(SortOrder order)
{
return sort(new TaxonomySnomedConceptVoComparator(order));
}
public TaxonomySnomedConceptVoCollection sort(SortOrder order, boolean caseInsensitive)
{
return sort(new TaxonomySnomedConceptVoComparator(order, caseInsensitive));
}
@SuppressWarnings("unchecked")
public TaxonomySnomedConceptVoCollection sort(Comparator comparator)
{
Collections.sort(col, comparator);
return this;
}
public ims.core.clinical.coding.vo.snomed_conceptRefVoCollection toRefVoCollection()
{
ims.core.clinical.coding.vo.snomed_conceptRefVoCollection result = new ims.core.clinical.coding.vo.snomed_conceptRefVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
result.add(this.col.get(x));
}
return result;
}
public TaxonomySnomedConceptVo[] toArray()
{
TaxonomySnomedConceptVo[] arr = new TaxonomySnomedConceptVo[col.size()];
col.toArray(arr);
return arr;
}
public Iterator<TaxonomySnomedConceptVo> iterator()
{
return col.iterator();
}
@Override
protected ArrayList getTypedCollection()
{
return col;
}
private class TaxonomySnomedConceptVoComparator implements Comparator
{
private int direction = 1;
private boolean caseInsensitive = true;
public TaxonomySnomedConceptVoComparator()
{
this(SortOrder.ASCENDING);
}
public TaxonomySnomedConceptVoComparator(SortOrder order)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
}
public TaxonomySnomedConceptVoComparator(SortOrder order, boolean caseInsensitive)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
this.caseInsensitive = caseInsensitive;
}
public int compare(Object obj1, Object obj2)
{
TaxonomySnomedConceptVo voObj1 = (TaxonomySnomedConceptVo)obj1;
TaxonomySnomedConceptVo voObj2 = (TaxonomySnomedConceptVo)obj2;
return direction*(voObj1.compareTo(voObj2, this.caseInsensitive));
}
public boolean equals(Object obj)
{
return false;
}
}
public ims.admin.vo.beans.TaxonomySnomedConceptVoBean[] getBeanCollection()
{
return getBeanCollectionArray();
}
public ims.admin.vo.beans.TaxonomySnomedConceptVoBean[] getBeanCollectionArray()
{
ims.admin.vo.beans.TaxonomySnomedConceptVoBean[] result = new ims.admin.vo.beans.TaxonomySnomedConceptVoBean[col.size()];
for(int i = 0; i < col.size(); i++)
{
TaxonomySnomedConceptVo vo = ((TaxonomySnomedConceptVo)col.get(i));
result[i] = (ims.admin.vo.beans.TaxonomySnomedConceptVoBean)vo.getBean();
}
return result;
}
public static TaxonomySnomedConceptVoCollection buildFromBeanCollection(java.util.Collection beans)
{
TaxonomySnomedConceptVoCollection coll = new TaxonomySnomedConceptVoCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while (iter.hasNext())
{
coll.add(((ims.admin.vo.beans.TaxonomySnomedConceptVoBean)iter.next()).buildVo());
}
return coll;
}
public static TaxonomySnomedConceptVoCollection buildFromBeanCollection(ims.admin.vo.beans.TaxonomySnomedConceptVoBean[] beans)
{
TaxonomySnomedConceptVoCollection coll = new TaxonomySnomedConceptVoCollection();
if(beans == null)
return coll;
for(int x = 0; x < beans.length; x++)
{
coll.add(beans[x].buildVo());
}
return coll;
}
}
|
open-health-hub/openmaxims-linux
|
openmaxims_workspace/ValueObjects/src/ims/admin/vo/TaxonomySnomedConceptVoCollection.java
|
Java
|
agpl-3.0
| 8,605
|
#
# Copyright (c) 2015 ThoughtWorks, Inc.
#
# Pixelated is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pixelated is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Pixelated. If not, see <http://www.gnu.org/licenses/>.
import time
import json
from twisted.internet import defer
from twisted.logger import Logger
from twisted.web.server import NOT_DONE_YET
from twisted.web.resource import Resource
from twisted.web import server
from leap.common import events
from pixelated.adapter.model.mail import InputMail
from pixelated.resources import respond_json_deferred, BaseResource
from pixelated.adapter.services.mail_sender import SMTPDownException
from pixelated.support.functional import to_unicode
log = Logger()
class MailsUnreadResource(Resource):
isLeaf = True
def __init__(self, mail_service):
Resource.__init__(self)
self._mail_service = mail_service
def render_POST(self, request):
idents = json.load(request.content).get('idents')
deferreds = []
for ident in idents:
deferreds.append(self._mail_service.mark_as_unread(ident))
d = defer.gatherResults(deferreds, consumeErrors=True)
d.addCallback(lambda _: respond_json_deferred(None, request))
d.addErrback(lambda _: respond_json_deferred(None, request, status_code=500))
return NOT_DONE_YET
class MailsReadResource(Resource):
isLeaf = True
def __init__(self, mail_service):
Resource.__init__(self)
self._mail_service = mail_service
def render_POST(self, request):
idents = json.load(request.content).get('idents')
deferreds = []
for ident in idents:
deferreds.append(self._mail_service.mark_as_read(ident))
d = defer.gatherResults(deferreds, consumeErrors=True)
d.addCallback(lambda _: respond_json_deferred(None, request))
d.addErrback(lambda _: respond_json_deferred(None, request, status_code=500))
return NOT_DONE_YET
class MailsDeleteResource(Resource):
isLeaf = True
def __init__(self, mail_service):
Resource.__init__(self)
self._mail_service = mail_service
def render_POST(self, request):
def response_failed(failure):
log.error('something failed: %s' % failure.getErrorMessage())
request.finish()
idents = json.loads(request.content.read())['idents']
deferreds = []
for ident in idents:
deferreds.append(self._mail_service.delete_mail(ident))
d = defer.gatherResults(deferreds, consumeErrors=True)
d.addCallback(lambda _: respond_json_deferred(None, request))
d.addErrback(response_failed)
return NOT_DONE_YET
class MailsRecoverResource(Resource):
isLeaf = True
def __init__(self, mail_service):
Resource.__init__(self)
self._mail_service = mail_service
def render_POST(self, request):
idents = json.loads(request.content.read())['idents']
deferreds = []
for ident in idents:
deferreds.append(self._mail_service.recover_mail(ident))
d = defer.gatherResults(deferreds, consumeErrors=True)
d.addCallback(lambda _: respond_json_deferred(None, request))
d.addErrback(lambda _: respond_json_deferred(None, request, status_code=500))
return NOT_DONE_YET
class MailsArchiveResource(Resource):
isLeaf = True
def __init__(self, mail_service):
Resource.__init__(self)
self._mail_service = mail_service
def render_POST(self, request):
idents = json.loads(request.content.read())['idents']
deferreds = []
for ident in idents:
deferreds.append(self._mail_service.archive_mail(ident))
d = defer.gatherResults(deferreds, consumeErrors=True)
d.addCallback(lambda _: respond_json_deferred({'successMessage': 'your-message-was-archived'}, request))
d.addErrback(lambda _: respond_json_deferred(None, request, status_code=500))
return NOT_DONE_YET
class MailsResource(BaseResource):
def _register_smtp_error_handler(self):
def on_error(event, content):
delivery_error_mail = InputMail.delivery_error_template(delivery_address=event.content)
self._mail_service.mailboxes.inbox.add(delivery_error_mail)
events.register(events.catalog.SMTP_SEND_MESSAGE_ERROR, callback=on_error)
def __init__(self, services_factory):
BaseResource.__init__(self, services_factory)
self._register_smtp_error_handler()
def getChild(self, action, request):
_mail_service = self.mail_service(request)
if action == 'delete':
return MailsDeleteResource(_mail_service)
if action == 'recover':
return MailsRecoverResource(_mail_service)
if action == 'archive':
return MailsArchiveResource(_mail_service)
if action == 'read':
return MailsReadResource(_mail_service)
if action == 'unread':
return MailsUnreadResource(_mail_service)
def _build_mails_response(self, (mails, total)):
return {
"stats": {
"total": total,
},
"mails": [mail.as_dict() for mail in mails]
}
def render_GET(self, request):
_mail_service = self.mail_service(request)
query, window_size, page = request.args.get('q')[0], request.args.get('w')[0], request.args.get('p')[0]
unicode_query = to_unicode(query)
d = _mail_service.mails(unicode_query, window_size, page)
d.addCallback(self._build_mails_response)
d.addCallback(lambda res: respond_json_deferred(res, request))
def error_handler(error):
print error
d.addErrback(error_handler)
return NOT_DONE_YET
def render_POST(self, request):
def onError(error):
if isinstance(error.value, SMTPDownException):
respond_json_deferred({'message': str(error.value)}, request, status_code=503)
else:
log.error('error occurred while sending: %s' % error.getErrorMessage())
respond_json_deferred({'message': 'an error occurred while sending'}, request, status_code=422)
deferred = self._handle_post(request)
deferred.addErrback(onError)
return server.NOT_DONE_YET
def render_PUT(self, request):
def onError(error):
log.error('error saving draft: %s' % error.getErrorMessage())
respond_json_deferred("", request, status_code=422)
deferred = self._handle_put(request)
deferred.addErrback(onError)
return server.NOT_DONE_YET
@defer.inlineCallbacks
def _fetch_attachment_contents(self, content_dict, _mail_service):
attachments = content_dict.get('attachments', []) if content_dict else []
for attachment in attachments:
retrieved_attachment = yield _mail_service.attachment(attachment['ident'])
attachment['raw'] = retrieved_attachment['content']
content_dict['attachments'] = attachments
defer.returnValue(content_dict)
@defer.inlineCallbacks
def _handle_post(self, request):
_mail_service = self.mail_service(request)
content_dict = json.loads(request.content.read())
with_attachment_content = yield self._fetch_attachment_contents(content_dict, _mail_service)
sent_mail = yield _mail_service.send_mail(with_attachment_content)
respond_json_deferred(sent_mail.as_dict(), request, status_code=201)
@defer.inlineCallbacks
def _handle_put(self, request):
_draft_service = self.draft_service(request)
_mail_service = self.mail_service(request)
content_dict = json.loads(request.content.read())
with_attachment_content = yield self._fetch_attachment_contents(content_dict, _mail_service)
_mail = InputMail.from_dict(with_attachment_content, from_address=_mail_service.account_email)
draft_id = content_dict.get('ident')
pixelated_mail = yield _draft_service.process_draft(draft_id, _mail)
if not pixelated_mail:
respond_json_deferred("", request, status_code=422)
else:
respond_json_deferred({'ident': pixelated_mail.ident}, request)
|
pixelated-project/pixelated-user-agent
|
service/pixelated/resources/mails_resource.py
|
Python
|
agpl-3.0
| 8,824
|
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.scheduling.vo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import ims.framework.enumerations.SortOrder;
/**
* Linked to Scheduling.Appt_Tracking_Status_History business object (ID: 1090100015).
*/
public class Appt_Tracking_Status_HistoryVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<Appt_Tracking_Status_HistoryVo>
{
private static final long serialVersionUID = 1L;
private ArrayList<Appt_Tracking_Status_HistoryVo> col = new ArrayList<Appt_Tracking_Status_HistoryVo>();
public String getBoClassName()
{
return "ims.scheduling.domain.objects.Appt_Tracking_Status_History";
}
public boolean add(Appt_Tracking_Status_HistoryVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
return this.col.add(value);
}
return false;
}
public boolean add(int index, Appt_Tracking_Status_HistoryVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
this.col.add(index, value);
return true;
}
return false;
}
public void clear()
{
this.col.clear();
}
public void remove(int index)
{
this.col.remove(index);
}
public int size()
{
return this.col.size();
}
public int indexOf(Appt_Tracking_Status_HistoryVo instance)
{
return col.indexOf(instance);
}
public Appt_Tracking_Status_HistoryVo get(int index)
{
return this.col.get(index);
}
public boolean set(int index, Appt_Tracking_Status_HistoryVo value)
{
if(value == null)
return false;
this.col.set(index, value);
return true;
}
public void remove(Appt_Tracking_Status_HistoryVo instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public boolean contains(Appt_Tracking_Status_HistoryVo instance)
{
return indexOf(instance) >= 0;
}
public Object clone()
{
Appt_Tracking_Status_HistoryVoCollection clone = new Appt_Tracking_Status_HistoryVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
if(this.col.get(x) != null)
clone.col.add((Appt_Tracking_Status_HistoryVo)this.col.get(x).clone());
else
clone.col.add(null);
}
return clone;
}
public boolean isValidated()
{
for(int x = 0; x < col.size(); x++)
if(!this.col.get(x).isValidated())
return false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(col.size() == 0)
return null;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
for(int x = 0; x < col.size(); x++)
{
String[] listOfOtherErrors = this.col.get(x).validate();
if(listOfOtherErrors != null)
{
for(int y = 0; y < listOfOtherErrors.length; y++)
{
listOfErrors.add(listOfOtherErrors[y]);
}
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
return null;
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
return result;
}
public Appt_Tracking_Status_HistoryVoCollection sort()
{
return sort(SortOrder.ASCENDING);
}
public Appt_Tracking_Status_HistoryVoCollection sort(boolean caseInsensitive)
{
return sort(SortOrder.ASCENDING, caseInsensitive);
}
public Appt_Tracking_Status_HistoryVoCollection sort(SortOrder order)
{
return sort(new Appt_Tracking_Status_HistoryVoComparator(order));
}
public Appt_Tracking_Status_HistoryVoCollection sort(SortOrder order, boolean caseInsensitive)
{
return sort(new Appt_Tracking_Status_HistoryVoComparator(order, caseInsensitive));
}
@SuppressWarnings("unchecked")
public Appt_Tracking_Status_HistoryVoCollection sort(Comparator comparator)
{
Collections.sort(col, comparator);
return this;
}
public ims.scheduling.vo.Appt_Tracking_Status_HistoryRefVoCollection toRefVoCollection()
{
ims.scheduling.vo.Appt_Tracking_Status_HistoryRefVoCollection result = new ims.scheduling.vo.Appt_Tracking_Status_HistoryRefVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
result.add(this.col.get(x));
}
return result;
}
public Appt_Tracking_Status_HistoryVo[] toArray()
{
Appt_Tracking_Status_HistoryVo[] arr = new Appt_Tracking_Status_HistoryVo[col.size()];
col.toArray(arr);
return arr;
}
public Iterator<Appt_Tracking_Status_HistoryVo> iterator()
{
return col.iterator();
}
@Override
protected ArrayList getTypedCollection()
{
return col;
}
private class Appt_Tracking_Status_HistoryVoComparator implements Comparator
{
private int direction = 1;
private boolean caseInsensitive = true;
public Appt_Tracking_Status_HistoryVoComparator()
{
this(SortOrder.ASCENDING);
}
public Appt_Tracking_Status_HistoryVoComparator(SortOrder order)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
}
public Appt_Tracking_Status_HistoryVoComparator(SortOrder order, boolean caseInsensitive)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
this.caseInsensitive = caseInsensitive;
}
public int compare(Object obj1, Object obj2)
{
Appt_Tracking_Status_HistoryVo voObj1 = (Appt_Tracking_Status_HistoryVo)obj1;
Appt_Tracking_Status_HistoryVo voObj2 = (Appt_Tracking_Status_HistoryVo)obj2;
return direction*(voObj1.compareTo(voObj2, this.caseInsensitive));
}
public boolean equals(Object obj)
{
return false;
}
}
public ims.scheduling.vo.beans.Appt_Tracking_Status_HistoryVoBean[] getBeanCollection()
{
return getBeanCollectionArray();
}
public ims.scheduling.vo.beans.Appt_Tracking_Status_HistoryVoBean[] getBeanCollectionArray()
{
ims.scheduling.vo.beans.Appt_Tracking_Status_HistoryVoBean[] result = new ims.scheduling.vo.beans.Appt_Tracking_Status_HistoryVoBean[col.size()];
for(int i = 0; i < col.size(); i++)
{
Appt_Tracking_Status_HistoryVo vo = ((Appt_Tracking_Status_HistoryVo)col.get(i));
result[i] = (ims.scheduling.vo.beans.Appt_Tracking_Status_HistoryVoBean)vo.getBean();
}
return result;
}
public static Appt_Tracking_Status_HistoryVoCollection buildFromBeanCollection(java.util.Collection beans)
{
Appt_Tracking_Status_HistoryVoCollection coll = new Appt_Tracking_Status_HistoryVoCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while (iter.hasNext())
{
coll.add(((ims.scheduling.vo.beans.Appt_Tracking_Status_HistoryVoBean)iter.next()).buildVo());
}
return coll;
}
public static Appt_Tracking_Status_HistoryVoCollection buildFromBeanCollection(ims.scheduling.vo.beans.Appt_Tracking_Status_HistoryVoBean[] beans)
{
Appt_Tracking_Status_HistoryVoCollection coll = new Appt_Tracking_Status_HistoryVoCollection();
if(beans == null)
return coll;
for(int x = 0; x < beans.length; x++)
{
coll.add(beans[x].buildVo());
}
return coll;
}
}
|
open-health-hub/openmaxims-linux
|
openmaxims_workspace/ValueObjects/src/ims/scheduling/vo/Appt_Tracking_Status_HistoryVoCollection.java
|
Java
|
agpl-3.0
| 9,001
|
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.oncology.vo.beans;
public class PatientDiagnosisForPrimaryTumourVoBean extends ims.vo.ValueObjectBean
{
public PatientDiagnosisForPrimaryTumourVoBean()
{
}
public PatientDiagnosisForPrimaryTumourVoBean(ims.oncology.vo.PatientDiagnosisForPrimaryTumourVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.diagnosisdescription = vo.getDiagnosisDescription();
this.diagnoseddate = vo.getDiagnosedDate() == null ? null : (ims.framework.utils.beans.PartialDateBean)vo.getDiagnosedDate().getBean();
this.authoringinfo = vo.getAuthoringInfo() == null ? null : (ims.core.vo.beans.AuthoringInformationVoBean)vo.getAuthoringInfo().getBean();
this.currentstatus = vo.getCurrentStatus() == null ? null : (ims.clinical.vo.beans.PatientDiagnosisStatusVoBean)vo.getCurrentStatus().getBean();
this.basisofdiagnosis = vo.getBasisofDiagnosis() == null ? null : vo.getBasisofDiagnosis().getBeanCollection();
this.diaglaterality = vo.getDiagLaterality() == null ? null : (ims.vo.LookupInstanceBean)vo.getDiagLaterality().getBean();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.oncology.vo.PatientDiagnosisForPrimaryTumourVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.diagnosisdescription = vo.getDiagnosisDescription();
this.diagnoseddate = vo.getDiagnosedDate() == null ? null : (ims.framework.utils.beans.PartialDateBean)vo.getDiagnosedDate().getBean();
this.authoringinfo = vo.getAuthoringInfo() == null ? null : (ims.core.vo.beans.AuthoringInformationVoBean)vo.getAuthoringInfo().getBean(map);
this.currentstatus = vo.getCurrentStatus() == null ? null : (ims.clinical.vo.beans.PatientDiagnosisStatusVoBean)vo.getCurrentStatus().getBean(map);
this.basisofdiagnosis = vo.getBasisofDiagnosis() == null ? null : vo.getBasisofDiagnosis().getBeanCollection();
this.diaglaterality = vo.getDiagLaterality() == null ? null : (ims.vo.LookupInstanceBean)vo.getDiagLaterality().getBean();
}
public ims.oncology.vo.PatientDiagnosisForPrimaryTumourVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.oncology.vo.PatientDiagnosisForPrimaryTumourVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.oncology.vo.PatientDiagnosisForPrimaryTumourVo vo = null;
if(map != null)
vo = (ims.oncology.vo.PatientDiagnosisForPrimaryTumourVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.oncology.vo.PatientDiagnosisForPrimaryTumourVo();
map.addValueObject(this, vo);
vo.populate(map, this);
}
return vo;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer value)
{
this.id = value;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int value)
{
this.version = value;
}
public String getDiagnosisDescription()
{
return this.diagnosisdescription;
}
public void setDiagnosisDescription(String value)
{
this.diagnosisdescription = value;
}
public ims.framework.utils.beans.PartialDateBean getDiagnosedDate()
{
return this.diagnoseddate;
}
public void setDiagnosedDate(ims.framework.utils.beans.PartialDateBean value)
{
this.diagnoseddate = value;
}
public ims.core.vo.beans.AuthoringInformationVoBean getAuthoringInfo()
{
return this.authoringinfo;
}
public void setAuthoringInfo(ims.core.vo.beans.AuthoringInformationVoBean value)
{
this.authoringinfo = value;
}
public ims.clinical.vo.beans.PatientDiagnosisStatusVoBean getCurrentStatus()
{
return this.currentstatus;
}
public void setCurrentStatus(ims.clinical.vo.beans.PatientDiagnosisStatusVoBean value)
{
this.currentstatus = value;
}
public java.util.Collection getBasisofDiagnosis()
{
return this.basisofdiagnosis;
}
public void setBasisofDiagnosis(java.util.Collection value)
{
this.basisofdiagnosis = value;
}
public void addBasisofDiagnosis(java.util.Collection value)
{
if(this.basisofdiagnosis == null)
this.basisofdiagnosis = new java.util.ArrayList();
this.basisofdiagnosis.add(value);
}
public ims.vo.LookupInstanceBean getDiagLaterality()
{
return this.diaglaterality;
}
public void setDiagLaterality(ims.vo.LookupInstanceBean value)
{
this.diaglaterality = value;
}
private Integer id;
private int version;
private String diagnosisdescription;
private ims.framework.utils.beans.PartialDateBean diagnoseddate;
private ims.core.vo.beans.AuthoringInformationVoBean authoringinfo;
private ims.clinical.vo.beans.PatientDiagnosisStatusVoBean currentstatus;
private java.util.Collection basisofdiagnosis;
private ims.vo.LookupInstanceBean diaglaterality;
}
|
open-health-hub/openmaxims-linux
|
openmaxims_workspace/ValueObjects/src/ims/oncology/vo/beans/PatientDiagnosisForPrimaryTumourVoBean.java
|
Java
|
agpl-3.0
| 6,420
|
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.oncology.forms.searchregimenmedication;
public final class FormInfo extends ims.framework.FormInfo
{
private static final long serialVersionUID = 1L;
public FormInfo(Integer formId)
{
super(formId);
}
public String getNamespaceName()
{
return "Oncology";
}
public String getFormName()
{
return "SearchRegimenMedication";
}
public int getWidth()
{
return 592;
}
public int getHeight()
{
return 144;
}
public String[] getContextVariables()
{
return new String[] { "_cv_Oncology.SelectedMedication" };
}
public String getLocalVariablesPrefix()
{
return "_lv_Oncology.SearchRegimenMedication.__internal_x_context__" + String.valueOf(getFormId());
}
public ims.framework.FormInfo[] getComponentsFormInfo()
{
ims.framework.FormInfo[] componentsInfo = new ims.framework.FormInfo[1];
componentsInfo[0] = new ims.clinical.forms.clinicalcoding.FormInfo(123133);
return componentsInfo;
}
public String getImagePath()
{
return "";
}
}
|
FreudianNM/openMAXIMS
|
Source Library/openmaxims_workspace/Oncology/src/ims/oncology/forms/searchregimenmedication/FormInfo.java
|
Java
|
agpl-3.0
| 3,130
|
/*
Copyright (C) 2014-2016 Leosac
This file is part of Leosac.
Leosac is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Leosac is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "UserGroupMembershipEventSerializer.hpp"
#include "AuditSerializer.hpp"
#include "core/SecurityContext.hpp"
#include "core/audit/IUserGroupMembershipEvent.hpp"
#include "tools/log.hpp"
namespace Leosac
{
namespace Audit
{
namespace Serializer
{
json UserGroupMembershipEventJSON::serialize(
const Audit::IUserGroupMembershipEvent &in, const SecurityContext &sc)
{
auto serialized = Audit::Serializer::AuditJSON::serialize(in, sc);
// Now we override the type.
ASSERT_LOG(serialized.at("type").is_string(),
"Base audit serialization did something unexpected.");
serialized["type"] = "audit-user-group-membership-event";
serialized["relationships"]["target-user"] = {
{{"id", in.target_user_id()}, {"type", "user"}}};
serialized["relationships"]["target-group"] = {
{{"id", in.target_group_id()}, {"type", "group"}}};
return serialized;
}
}
}
}
|
islog/leosac
|
src/core/audit/serializers/UserGroupMembershipEventSerializer.cpp
|
C++
|
agpl-3.0
| 1,654
|
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5007.25751)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 16/04/2014, 12:31
*
*/
package ims.therapies.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Peter Martin
*/
public class WheelchairSurfaceDistanceVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.therapies.vo.WheelchairSurfaceDistanceVo copy(ims.therapies.vo.WheelchairSurfaceDistanceVo valueObjectDest, ims.therapies.vo.WheelchairSurfaceDistanceVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_WheelchairSurfaceDistance(valueObjectSrc.getID_WheelchairSurfaceDistance());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// Surface
valueObjectDest.setSurface(valueObjectSrc.getSurface());
// Distance
valueObjectDest.setDistance(valueObjectSrc.getDistance());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #createWheelchairSurfaceDistanceVoCollectionFromWheelchairSurfaceDistance(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance objects.
*/
public static ims.therapies.vo.WheelchairSurfaceDistanceVoCollection createWheelchairSurfaceDistanceVoCollectionFromWheelchairSurfaceDistance(java.util.Set domainObjectSet)
{
return createWheelchairSurfaceDistanceVoCollectionFromWheelchairSurfaceDistance(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance objects.
*/
public static ims.therapies.vo.WheelchairSurfaceDistanceVoCollection createWheelchairSurfaceDistanceVoCollectionFromWheelchairSurfaceDistance(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.therapies.vo.WheelchairSurfaceDistanceVoCollection voList = new ims.therapies.vo.WheelchairSurfaceDistanceVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance domainObject = (ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance) iterator.next();
ims.therapies.vo.WheelchairSurfaceDistanceVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance objects.
*/
public static ims.therapies.vo.WheelchairSurfaceDistanceVoCollection createWheelchairSurfaceDistanceVoCollectionFromWheelchairSurfaceDistance(java.util.List domainObjectList)
{
return createWheelchairSurfaceDistanceVoCollectionFromWheelchairSurfaceDistance(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance objects.
*/
public static ims.therapies.vo.WheelchairSurfaceDistanceVoCollection createWheelchairSurfaceDistanceVoCollectionFromWheelchairSurfaceDistance(DomainObjectMap map, java.util.List domainObjectList)
{
ims.therapies.vo.WheelchairSurfaceDistanceVoCollection voList = new ims.therapies.vo.WheelchairSurfaceDistanceVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance domainObject = (ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance) domainObjectList.get(i);
ims.therapies.vo.WheelchairSurfaceDistanceVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractWheelchairSurfaceDistanceSet(ims.domain.ILightweightDomainFactory domainFactory, ims.therapies.vo.WheelchairSurfaceDistanceVoCollection voCollection)
{
return extractWheelchairSurfaceDistanceSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractWheelchairSurfaceDistanceSet(ims.domain.ILightweightDomainFactory domainFactory, ims.therapies.vo.WheelchairSurfaceDistanceVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.therapies.vo.WheelchairSurfaceDistanceVo vo = voCollection.get(i);
ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance domainObject = WheelchairSurfaceDistanceVoAssembler.extractWheelchairSurfaceDistance(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractWheelchairSurfaceDistanceList(ims.domain.ILightweightDomainFactory domainFactory, ims.therapies.vo.WheelchairSurfaceDistanceVoCollection voCollection)
{
return extractWheelchairSurfaceDistanceList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractWheelchairSurfaceDistanceList(ims.domain.ILightweightDomainFactory domainFactory, ims.therapies.vo.WheelchairSurfaceDistanceVoCollection voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.therapies.vo.WheelchairSurfaceDistanceVo vo = voCollection.get(i);
ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance domainObject = WheelchairSurfaceDistanceVoAssembler.extractWheelchairSurfaceDistance(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance object.
* @param domainObject ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance
*/
public static ims.therapies.vo.WheelchairSurfaceDistanceVo create(ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.therapies.vo.WheelchairSurfaceDistanceVo create(DomainObjectMap map, ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.therapies.vo.WheelchairSurfaceDistanceVo valueObject = (ims.therapies.vo.WheelchairSurfaceDistanceVo) map.getValueObject(domainObject, ims.therapies.vo.WheelchairSurfaceDistanceVo.class);
if ( null == valueObject )
{
valueObject = new ims.therapies.vo.WheelchairSurfaceDistanceVo(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance
*/
public static ims.therapies.vo.WheelchairSurfaceDistanceVo insert(ims.therapies.vo.WheelchairSurfaceDistanceVo valueObject, ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance
*/
public static ims.therapies.vo.WheelchairSurfaceDistanceVo insert(DomainObjectMap map, ims.therapies.vo.WheelchairSurfaceDistanceVo valueObject, ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_WheelchairSurfaceDistance(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// Surface
ims.domain.lookups.LookupInstance instance1 = domainObject.getSurface();
if ( null != instance1 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance1.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance1.getImage().getImageId(), instance1.getImage().getImagePath());
}
color = instance1.getColor();
if (color != null)
color.getValue();
ims.spinalinjuries.vo.lookups.WheelchairSurface voLookup1 = new ims.spinalinjuries.vo.lookups.WheelchairSurface(instance1.getId(),instance1.getText(), instance1.isActive(), null, img, color);
ims.spinalinjuries.vo.lookups.WheelchairSurface parentVoLookup1 = voLookup1;
ims.domain.lookups.LookupInstance parent1 = instance1.getParent();
while (parent1 != null)
{
if (parent1.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent1.getImage().getImageId(), parent1.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent1.getColor();
if (color != null)
color.getValue();
parentVoLookup1.setParent(new ims.spinalinjuries.vo.lookups.WheelchairSurface(parent1.getId(),parent1.getText(), parent1.isActive(), null, img, color));
parentVoLookup1 = parentVoLookup1.getParent();
parent1 = parent1.getParent();
}
valueObject.setSurface(voLookup1);
}
// Distance
valueObject.setDistance(domainObject.getDistance());
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance extractWheelchairSurfaceDistance(ims.domain.ILightweightDomainFactory domainFactory, ims.therapies.vo.WheelchairSurfaceDistanceVo valueObject)
{
return extractWheelchairSurfaceDistance(domainFactory, valueObject, new HashMap());
}
public static ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance extractWheelchairSurfaceDistance(ims.domain.ILightweightDomainFactory domainFactory, ims.therapies.vo.WheelchairSurfaceDistanceVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_WheelchairSurfaceDistance();
ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance)domMap.get(valueObject);
}
// ims.therapies.vo.WheelchairSurfaceDistanceVo ID_WheelchairSurfaceDistance field is unknown
domainObject = new ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_WheelchairSurfaceDistance());
if (domMap.get(key) != null)
{
return (ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance)domMap.get(key);
}
domainObject = (ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance) domainFactory.getDomainObject(ims.therapies.mobilitytransfers.domain.objects.WheelchairSurfaceDistance.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_WheelchairSurfaceDistance());
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value1 = null;
if ( null != valueObject.getSurface() )
{
value1 =
domainFactory.getLookupInstance(valueObject.getSurface().getID());
}
domainObject.setSurface(value1);
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getDistance() != null && valueObject.getDistance().equals(""))
{
valueObject.setDistance(null);
}
domainObject.setDistance(valueObject.getDistance());
return domainObject;
}
}
|
open-health-hub/openmaxims-linux
|
openmaxims_workspace/ValueObjects/src/ims/therapies/vo/domain/WheelchairSurfaceDistanceVoAssembler.java
|
Java
|
agpl-3.0
| 19,489
|
/*
Copyright (C) 2014 Omega software d.o.o.
This file is part of Rhetos.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Rhetos.Utilities.Test
{
[TestClass]
public class MsSqlUtilityTest
{
[TestMethod]
public void InterpretSqlExceptionUserMessage()
{
var msSqlUtility = new MsSqlUtility();
var interpretedException = msSqlUtility.InterpretSqlException(
NewSqlException("test message", 50000, 16, 101)); // State 101 is Rhetos convention for user error message.
Assert.AreEqual("UserException: test message", interpretedException.GetType().Name + ": " + interpretedException.Message);
}
[TestMethod]
public void InterpretSqlExceptionWrapping()
{
TestInterpretedException(new ListOfTuples<Exception, string>
{
{ null, null },
{ new FrameworkException("abc"), null },
{ new Exception(), null },
{ NewSqlException("test message", 50000, 16, 101), "UserException: test message" },
{ NewSqlException("test message", 50000, 16, 0), null },
{ new Exception("ex1", NewSqlException("test message", 50000, 16, 101)), "UserException: test message" },
{ new Exception("ex1", NewSqlException("test message", 50000, 16, 0)), null },
{ new Exception("ex1", new Exception("ex2", NewSqlException("test message", 50000, 16, 101))), "UserException: test message" },
});
}
[TestMethod]
public void InterpretUniqueConstraint()
{
TestInterpretedException(new ListOfTuples<Exception, string>
{
// SQL2014:
{
NewSqlException(
"Cannot insert duplicate key row in object 'Common.Principal' with unique index 'IX_Principal_Name'. The duplicate key value is (test1).",
2601, 14, 1),
"UserException: It is not allowed to enter a duplicate record., Constraint=Unique, ConstraintName=IX_Principal_Name, DuplicateValue=test1, Table=Common.Principal"
},
// SQL2008, SQL2000:
{
NewSqlException(
"Cannot insert duplicate key row in object 'Common.Principal' with unique index 'IX_Principal_Name'.",
2601, 14, 1),
"UserException: It is not allowed to enter a duplicate record., Constraint=Unique, ConstraintName=IX_Principal_Name, Table=Common.Principal"
},
});
}
[TestMethod]
public void InterpretReferenceConstraint()
{
TestInterpretedException(new ListOfTuples<Exception, string>
{
// SQL2014:
{
NewSqlException(
"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_PrincipalPermission_Principal_PrincipalID\". The conflict occurred in database \"Rhetos\", table \"Common.Principal\", column 'ID'.",
547, 16, 0),
"UserException: It is not allowed to enter the record. The entered value references nonexistent record."
+ ", Action=INSERT, Constraint=Reference, ConstraintName=FK_PrincipalPermission_Principal_PrincipalID, ReferencedColumn=ID, ReferencedTable=Common.Principal"
},
{
NewSqlException(
"The UPDATE statement conflicted with the FOREIGN KEY constraint \"FK_PrincipalHasRole_Role_RoleID\". The conflict occurred in database \"Rhetos\", table \"Common.Role\", column 'ID'.",
547, 16, 0),
"UserException: It is not allowed to edit the record. The entered value references nonexistent record."
+ ", Action=UPDATE, Constraint=Reference, ConstraintName=FK_PrincipalHasRole_Role_RoleID, ReferencedColumn=ID, ReferencedTable=Common.Role"
},
{
NewSqlException(
"The DELETE statement conflicted with the REFERENCE constraint \"FK_PrincipalHasRole_Role_RoleID\". The conflict occurred in database \"Rhetos\", table \"Common.PrincipalHasRole\", column 'RoleID'.",
547, 16, 0),
"UserException: It is not allowed to delete a record that is referenced by other records."
+ ", Action=DELETE, Constraint=Reference, ConstraintName=FK_PrincipalHasRole_Role_RoleID, DependentColumn=RoleID, DependentTable=Common.PrincipalHasRole"
},
{
NewSqlException(
"The DELETE statement conflicted with the SAME TABLE REFERENCE constraint \"FK_PrincipalHasRole_Role_RoleID\". The conflict occurred in database \"Rhetos\", table \"Common.PrincipalHasRole\", column 'RoleID'.",
547, 16, 0),
"UserException: It is not allowed to delete a record that is referenced by other records."
+ ", Action=DELETE, Constraint=Reference, ConstraintName=FK_PrincipalHasRole_Role_RoleID, DependentColumn=RoleID, DependentTable=Common.PrincipalHasRole"
},
// SQL2000:
{
NewSqlException(
"INSERT statement conflicted with COLUMN FOREIGN KEY constraint 'FK1'. The conflict occurred in database 'D1', table 'T1', column 'C1'.",
547, 16, 0),
"UserException: It is not allowed to enter the record. The entered value references nonexistent record."
+ ", Action=INSERT, Constraint=Reference, ConstraintName=FK1, ReferencedColumn=C1, ReferencedTable=T1"
},
});
}
[TestMethod]
public void InterpretPrimaryKeyConstraint()
{
TestInterpretedException(new ListOfTuples<Exception, string>
{
// SQL2016:
{
NewSqlException(
"Violation of PRIMARY KEY constraint 'PK_Principal'. Cannot insert duplicate key in object 'Common.Principal'. The duplicate key value is (d28a180d-96da-478f-ad7a-e9a071833bad).\r\nThe statement has been terminated.",
2627, 14, 1),
"FrameworkException: Inserting a record that already exists in database., Constraint=Primary key, ConstraintName=PK_Principal, DuplicateValue=d28a180d-96da-478f-ad7a-e9a071833bad, Table=Common.Principal"
},
// SQL2000:
{
NewSqlException(
"Violation of PRIMARY KEY constraint 'PK_Principal'. Cannot insert duplicate key in object 'Common.Principal'.",
2627, 14, 1),
"FrameworkException: Inserting a record that already exists in database., Constraint=Primary key, ConstraintName=PK_Principal, Table=Common.Principal"
},
});
}
private void TestInterpretedException(ListOfTuples<Exception, string> tests)
{
var msSqlUtility = new MsSqlUtility();
foreach (var test in tests)
{
string reportInput = "Input: " + (test.Item1 != null ? test.Item1.ToString() : "null");
Console.WriteLine(reportInput);
var interpretedException = msSqlUtility.InterpretSqlException(test.Item1);
Console.WriteLine("Output: " + (interpretedException != null ? interpretedException.ToString() : "null"));
Assert.AreEqual(test.Item2, Report(interpretedException), reportInput);
}
}
string Report(RhetosException ex)
{
if (ex == null)
return null;
return ex.GetType().Name + ": " + ex.Message
+ string.Concat(ex.Info.OrderBy(info => info.Key).Select(info => ", " + info.Key + "=" + info.Value.ToString()));
}
#region SqlExceptionCreator, thanks to Sam Saffron at http://stackoverflow.com/a/1387030
internal static SqlException NewSqlException(string message, int number, int level, int state)
{
SqlErrorCollection collection = Construct<SqlErrorCollection>();
SqlError error = Construct<SqlError>(number, (byte)state, (byte)level, "test server", message, "test procedure", state);
typeof(SqlErrorCollection)
.GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance)
.Invoke(collection, new object[] { error });
return typeof(SqlException)
.GetMethod("CreateException", BindingFlags.NonPublic | BindingFlags.Static,
null,
CallingConventions.ExplicitThis,
new[] { typeof(SqlErrorCollection), typeof(string) },
new ParameterModifier[] { })
.Invoke(null, new object[] { collection, "7.0.0" }) as SqlException;
}
private static T Construct<T>(params object[] p)
{
var ctors = typeof(T).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance);
return (T)ctors.Single(ctor => ctor.GetParameters().Length == p.Length).Invoke(p);
}
#endregion
}
}
|
bantolov/Rhetos
|
Source/Rhetos.Utilities.Test/MsSqlUtilityTest.cs
|
C#
|
agpl-3.0
| 10,598
|
<?php
/**
* PEAR_Installer_Role
*
* PHP versions 4 and 5
*
* @category pear
* @package PEAR
* @author Greg Beaver <cellog@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version CVS: $Id$
* @link http://pear.php.net/package/PEAR
* @since File available since Release 1.4.0a1
*/
/**
* base class for installer roles
*/
require_once 'PEAR/Installer/Role/Common.php';
require_once 'PEAR/XMLParser.php';
/**
* @category pear
* @package PEAR
* @author Greg Beaver <cellog@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version Release: @package_version@
* @link http://pear.php.net/package/PEAR
* @since Class available since Release 1.4.0a1
*/
class PEAR_Installer_Role
{
/**
* Set up any additional configuration variables that file roles require
*
* Never call this directly, it is called by the PEAR_Config constructor
* @param PEAR_Config
* @access private
* @static
*/
function initializeConfig(&$config)
{
if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) {
PEAR_Installer_Role::registerRoles();
}
foreach ($GLOBALS['_PEAR_INSTALLER_ROLES'] as $class => $info) {
if (!$info['config_vars']) {
continue;
}
$config->_addConfigVars($class, $info['config_vars']);
}
}
/**
* @param PEAR_PackageFile_v2
* @param string role name
* @param PEAR_Config
* @return PEAR_Installer_Role_Common
* @static
*/
function &factory($pkg, $role, &$config)
{
if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) {
PEAR_Installer_Role::registerRoles();
}
if (!in_array($role, PEAR_Installer_Role::getValidRoles($pkg->getPackageType()))) {
$a = false;
return $a;
}
$a = 'PEAR_Installer_Role_' . ucfirst($role);
if (!class_exists($a)) {
require_once str_replace('_', '/', $a) . '.php';
}
$b = new $a($config);
return $b;
}
/**
* Get a list of file roles that are valid for the particular release type.
*
* For instance, src files serve no purpose in regular php releases.
* @param string
* @param bool clear cache
* @return array
* @static
*/
function getValidRoles($release, $clear = false)
{
if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) {
PEAR_Installer_Role::registerRoles();
}
static $ret = array();
if ($clear) {
$ret = array();
}
if (isset($ret[$release])) {
return $ret[$release];
}
$ret[$release] = array();
foreach ($GLOBALS['_PEAR_INSTALLER_ROLES'] as $role => $okreleases) {
if (in_array($release, $okreleases['releasetypes'])) {
$ret[$release][] = strtolower(str_replace('PEAR_Installer_Role_', '', $role));
}
}
return $ret[$release];
}
/**
* Get a list of roles that require their files to be installed
*
* Most roles must be installed, but src and package roles, for instance
* are pseudo-roles. src files are compiled into a new extension. Package
* roles are actually fully bundled releases of a package
* @param bool clear cache
* @return array
* @static
*/
function getInstallableRoles($clear = false)
{
if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) {
PEAR_Installer_Role::registerRoles();
}
static $ret;
if ($clear) {
unset($ret);
}
if (isset($ret)) {
return $ret;
}
$ret = array();
foreach ($GLOBALS['_PEAR_INSTALLER_ROLES'] as $role => $okreleases) {
if ($okreleases['installable']) {
$ret[] = strtolower(str_replace('PEAR_Installer_Role_', '', $role));
}
}
return $ret;
}
/**
* Return an array of roles that are affected by the baseinstalldir attribute
*
* Most roles ignore this attribute, and instead install directly into:
* PackageName/filepath
* so a tests file tests/file.phpt is installed into PackageName/tests/filepath.php
* @param bool clear cache
* @return array
* @static
*/
function getBaseinstallRoles($clear = false)
{
if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) {
PEAR_Installer_Role::registerRoles();
}
static $ret;
if ($clear) {
unset($ret);
}
if (isset($ret)) {
return $ret;
}
$ret = array();
foreach ($GLOBALS['_PEAR_INSTALLER_ROLES'] as $role => $okreleases) {
if ($okreleases['honorsbaseinstall']) {
$ret[] = strtolower(str_replace('PEAR_Installer_Role_', '', $role));
}
}
return $ret;
}
/**
* Return an array of file roles that should be analyzed for PHP content at package time,
* like the "php" role.
* @param bool clear cache
* @return array
* @static
*/
function getPhpRoles($clear = false)
{
if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) {
PEAR_Installer_Role::registerRoles();
}
static $ret;
if ($clear) {
unset($ret);
}
if (isset($ret)) {
return $ret;
}
$ret = array();
foreach ($GLOBALS['_PEAR_INSTALLER_ROLES'] as $role => $okreleases) {
if ($okreleases['phpfile']) {
$ret[] = strtolower(str_replace('PEAR_Installer_Role_', '', $role));
}
}
return $ret;
}
/**
* Scan through the Command directory looking for classes
* and see what commands they implement.
* @param string which directory to look for classes, defaults to
* the Installer/Roles subdirectory of
* the directory from where this file (__FILE__) is
* included.
*
* @return bool TRUE on success, a PEAR error on failure
* @access public
* @static
*/
function registerRoles($dir = null)
{
$GLOBALS['_PEAR_INSTALLER_ROLES'] = array();
$parser = new PEAR_XMLParser;
if ($dir === null) {
$dir = dirname(__FILE__) . '/Role';
}
if (!file_exists($dir) || !is_dir($dir)) {
return PEAR::raiseError("registerRoles: opendir($dir) failed: does not exist/is not directory");
}
$dp = @opendir($dir);
if (empty($dp)) {
return PEAR::raiseError("registerRoles: opendir($dir) failed: $php_errmsg");
}
while ($entry = readdir($dp)) {
if ($entry{0} == '.' || substr($entry, -4) != '.xml') {
continue;
}
$class = "PEAR_Installer_Role_".substr($entry, 0, -4);
// List of roles
if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'][$class])) {
$file = "$dir/$entry";
$parser->parse(file_get_contents($file));
$data = $parser->getData();
if (!is_array($data['releasetypes'])) {
$data['releasetypes'] = array($data['releasetypes']);
}
$GLOBALS['_PEAR_INSTALLER_ROLES'][$class] = $data;
}
}
closedir($dp);
ksort($GLOBALS['_PEAR_INSTALLER_ROLES']);
PEAR_Installer_Role::getBaseinstallRoles(true);
PEAR_Installer_Role::getInstallableRoles(true);
PEAR_Installer_Role::getPhpRoles(true);
PEAR_Installer_Role::getValidRoles('****', true);
return true;
}
}
|
PricelessPHP/Base
|
library/PEAR/Installer/Role.php
|
PHP
|
agpl-3.0
| 8,230
|
/* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/. */
package com.db4o.internal;
import com.db4o.foundation.*;
import com.db4o.internal.marshall.*;
/**
* @exclude
*/
public class NullFieldMetadata extends FieldMetadata {
public NullFieldMetadata(){
super(null);
}
/**
* @param obj
*/
public PreparedComparison prepareComparison(Object obj) {
return Null.INSTANCE;
}
public final Object read(ObjectIdContext context) {
return null;
}
}
|
xionghuiCoder/db4o
|
src/main/java/com/db4o/internal/NullFieldMetadata.java
|
Java
|
agpl-3.0
| 1,128
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace Kaltura
{
public class KalturaParams : SortedList<string, string>
{
public string ToQueryString()
{
string str = "";
foreach (KeyValuePair<string, string> item in this)
str += (item.Key + "=" + HttpUtility.UrlEncode(item.Value) + "&");
if (str.EndsWith("&"))
str = str.Substring(0, str.Length - 1);
return str;
}
public void Add(string objectName, KalturaParams objectProperties)
{
foreach (KeyValuePair<string, string> item in objectProperties)
{
this.Add(objectName + ":" + item.Key, item.Value);
}
}
public void Add(KalturaParams objectProperties)
{
foreach (KeyValuePair<string, string> item in objectProperties)
{
this.Add(item.Key, item.Value);
}
}
public void AddStringIfNotNull(string key, string value)
{
if (value != null)
this.Add(key, value);
}
public void AddIntIfNotNull(string key, int value)
{
if (value != int.MinValue)
this.Add(key, value.ToString());
}
public void AddFloatIfNotNull(string key, float value)
{
if (value != Single.MinValue)
this.Add(key, value.ToString());
}
public void AddEnumIfNotNull(string key, Enum value)
{
this.AddIntIfNotNull(key, value.GetHashCode());
}
public void AddStringEnumIfNotNull(string key, KalturaStringEnum value)
{
if (value != null)
this.AddStringIfNotNull(key, value.ToString());
}
public void AddBoolIfNotNull(string key, bool? value)
{
if (value.HasValue)
this.Add(key, (value.Value) ? "1" : "0");
}
}
}
|
MimocomMedia/kaltura
|
package/app/app/generator/sources/dotnet/KalturaClient/KalturaParams.cs
|
C#
|
agpl-3.0
| 2,114
|
# -*- coding: utf-8 -*-
from openerp import fields, models, api, _
class account_account_interest(models.Model):
_name = "account.account.interest"
_description = 'Account Account Interest'
account_id = fields.Many2one(
'account.account',
'Account',
required=True,
ondelete="cascade")
interest_account_id = fields.Many2one(
'account.account',
'Interest Account',
required=True,
domain=[('type', '!=', 'view')])
analytic_account_id = fields.Many2one(
'account.analytic.account',
'Analytic account',
domain=[('type', '!=', 'view')])
interest_rate = fields.Float(
'Interest',
required=True,
digits=(7, 4))
date_from = fields.Date(
'Date From',
required=True)
date_to = fields.Date('Date To')
class account_account(models.Model):
_inherit = "account.account"
account_account_interest_ids = fields.One2many(
'account.account.interest',
'account_id',
'Interest Rates')
def get_active_interest_data(self, cr, uid, ids, dt_from, dt_to, context=None):
if context is None:
context = {}
interest_obj = self.pool.get('account.account.interest')
res = {}
for record_id in ids:
interest_domain = [
('account_id.id', '=', record_id),
('date_from', '<=', dt_from),
'|', ('date_to', '>=', dt_to),
('date_to', '=', False)]
interest_ids = interest_obj.search(
cr, uid, interest_domain, context=context)
if interest_ids:
res[record_id] = interest_obj.browse(
cr, uid, interest_ids[0], context=context)
return res
|
syci/ingadhoc-odoo-addons
|
account_interests/interest.py
|
Python
|
agpl-3.0
| 1,803
|
# Generated by Django 2.1.7 on 2019-05-12 16:08
from django.db import migrations, models
class Migration(migrations.Migration):
atomic = False
dependencies = [
('publishers', '0007_publisher_romeo_parent_id'),
]
operations = [
migrations.AlterField(
model_name='journal',
name='title',
field=models.CharField(max_length=256),
),
migrations.AlterField(
model_name='publisher',
name='name',
field=models.CharField(max_length=256),
),
migrations.RunSQL(
sql="""
CREATE INDEX CONCURRENTLY papers_journal_title_upper ON public.papers_journal USING btree (UPPER(title));
""",
reverse_sql="""
DROP INDEX CONCURRENTLY papers_journal_title_upper;
""",
),
migrations.RunSQL(
sql="""
CREATE INDEX CONCURRENTLY papers_publisher_name_upper ON public.papers_publisher USING btree (UPPER(name));
""",
reverse_sql="""
DROP INDEX CONCURRENTLY papers_publisher_name_upper;
"""
),
]
|
wetneb/dissemin
|
publishers/migrations/0008_fix_name_indices.py
|
Python
|
agpl-3.0
| 1,178
|
/*
* Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license: http://github.com/azerothcore/azerothcore-wotlk/LICENSE-GPL2
* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*/
#include "MapTree.h"
#include "ModelInstance.h"
#include "VMapManager2.h"
#include "VMapDefinitions.h"
#include "Log.h"
#include "Errors.h"
#include <string>
#include <sstream>
#include <iomanip>
#include <limits>
using G3D::Vector3;
namespace VMAP
{
class MapRayCallback
{
public:
MapRayCallback(ModelInstance* val): prims(val), hit(false) {}
bool operator()(const G3D::Ray& ray, uint32 entry, float& distance, bool StopAtFirstHit)
{
bool result = prims[entry].intersectRay(ray, distance, StopAtFirstHit);
if (result)
hit = true;
return result;
}
bool didHit() { return hit; }
protected:
ModelInstance* prims;
bool hit;
};
class AreaInfoCallback
{
public:
AreaInfoCallback(ModelInstance* val): prims(val) {}
void operator()(const Vector3& point, uint32 entry)
{
#ifdef VMAP_DEBUG
;//sLog->outDebug(LOG_FILTER_MAPS, "AreaInfoCallback: trying to intersect '%s'", prims[entry].name.c_str());
#endif
prims[entry].intersectPoint(point, aInfo);
}
ModelInstance* prims;
AreaInfo aInfo;
};
class LocationInfoCallback
{
public:
LocationInfoCallback(ModelInstance* val, LocationInfo &info): prims(val), locInfo(info), result(false) {}
void operator()(const Vector3& point, uint32 entry)
{
#ifdef VMAP_DEBUG
;//sLog->outDebug(LOG_FILTER_MAPS, "LocationInfoCallback: trying to intersect '%s'", prims[entry].name.c_str());
#endif
if (prims[entry].GetLocationInfo(point, locInfo))
result = true;
}
ModelInstance* prims;
LocationInfo &locInfo;
bool result;
};
//=========================================================
std::string StaticMapTree::getTileFileName(uint32 mapID, uint32 tileX, uint32 tileY)
{
std::stringstream tilefilename;
tilefilename.fill('0');
tilefilename << std::setw(3) << mapID << '_';
//tilefilename << std::setw(2) << tileX << '_' << std::setw(2) << tileY << ".vmtile";
tilefilename << std::setw(2) << tileY << '_' << std::setw(2) << tileX << ".vmtile";
return tilefilename.str();
}
bool StaticMapTree::getAreaInfo(Vector3 &pos, uint32 &flags, int32 &adtId, int32 &rootId, int32 &groupId) const
{
AreaInfoCallback intersectionCallBack(iTreeValues);
iTree.intersectPoint(pos, intersectionCallBack);
if (intersectionCallBack.aInfo.result)
{
flags = intersectionCallBack.aInfo.flags;
adtId = intersectionCallBack.aInfo.adtId;
rootId = intersectionCallBack.aInfo.rootId;
groupId = intersectionCallBack.aInfo.groupId;
pos.z = intersectionCallBack.aInfo.ground_Z;
return true;
}
return false;
}
bool StaticMapTree::GetLocationInfo(const Vector3 &pos, LocationInfo &info) const
{
LocationInfoCallback intersectionCallBack(iTreeValues, info);
iTree.intersectPoint(pos, intersectionCallBack);
return intersectionCallBack.result;
}
StaticMapTree::StaticMapTree(uint32 mapID, const std::string &basePath)
: iMapID(mapID), iIsTiled(false), iTreeValues(0), iBasePath(basePath)
{
if (iBasePath.length() > 0 && iBasePath[iBasePath.length()-1] != '/' && iBasePath[iBasePath.length()-1] != '\\')
{
iBasePath.push_back('/');
}
}
//=========================================================
//! Make sure to call unloadMap() to unregister acquired model references before destroying
StaticMapTree::~StaticMapTree()
{
delete[] iTreeValues;
}
//=========================================================
/**
If intersection is found within pMaxDist, sets pMaxDist to intersection distance and returns true.
Else, pMaxDist is not modified and returns false;
*/
bool StaticMapTree::getIntersectionTime(const G3D::Ray& pRay, float &pMaxDist, bool StopAtFirstHit) const
{
float distance = pMaxDist;
MapRayCallback intersectionCallBack(iTreeValues);
iTree.intersectRay(pRay, intersectionCallBack, distance, StopAtFirstHit);
if (intersectionCallBack.didHit())
pMaxDist = distance;
return intersectionCallBack.didHit();
}
//=========================================================
bool StaticMapTree::isInLineOfSight(const Vector3& pos1, const Vector3& pos2) const
{
float maxDist = (pos2 - pos1).magnitude();
// return false if distance is over max float, in case of cheater teleporting to the end of the universe
if (maxDist == std::numeric_limits<float>::max() || !myisfinite(maxDist))
return false;
// valid map coords should *never ever* produce float overflow, but this would produce NaNs too
ASSERT(maxDist < std::numeric_limits<float>::max());
// prevent NaN values which can cause BIH intersection to enter infinite loop
if (maxDist < 1e-10f)
return true;
// direction with length of 1
G3D::Ray ray = G3D::Ray::fromOriginAndDirection(pos1, (pos2 - pos1)/maxDist);
if (getIntersectionTime(ray, maxDist, true))
return false;
return true;
}
//=========================================================
/**
When moving from pos1 to pos2 check if we hit an object. Return true and the position if we hit one
Return the hit pos or the original dest pos
*/
bool StaticMapTree::getObjectHitPos(const Vector3& pPos1, const Vector3& pPos2, Vector3& pResultHitPos, float pModifyDist) const
{
bool result=false;
float maxDist = (pPos2 - pPos1).magnitude();
// valid map coords should *never ever* produce float overflow, but this would produce NaNs too
ASSERT(maxDist < std::numeric_limits<float>::max());
// prevent NaN values which can cause BIH intersection to enter infinite loop
if (maxDist < 1e-10f)
{
pResultHitPos = pPos2;
return false;
}
Vector3 dir = (pPos2 - pPos1)/maxDist; // direction with length of 1
G3D::Ray ray(pPos1, dir);
float dist = maxDist;
if (getIntersectionTime(ray, dist, false))
{
pResultHitPos = pPos1 + dir * dist;
if (pModifyDist < 0)
{
if ((pResultHitPos - pPos1).magnitude() > -pModifyDist)
{
pResultHitPos = pResultHitPos + dir*pModifyDist;
}
else
{
pResultHitPos = pPos1;
}
}
else
{
pResultHitPos = pResultHitPos + dir*pModifyDist;
}
result = true;
}
else
{
pResultHitPos = pPos2;
result = false;
}
return result;
}
//=========================================================
float StaticMapTree::getHeight(const Vector3& pPos, float maxSearchDist) const
{
float height = G3D::inf();
Vector3 dir = Vector3(0, 0, -1);
G3D::Ray ray(pPos, dir); // direction with length of 1
float maxDist = maxSearchDist;
if (getIntersectionTime(ray, maxDist, false))
{
height = pPos.z - maxDist;
}
return(height);
}
//=========================================================
bool StaticMapTree::CanLoadMap(const std::string &vmapPath, uint32 mapID, uint32 tileX, uint32 tileY)
{
std::string basePath = vmapPath;
if (basePath.length() > 0 && basePath[basePath.length()-1] != '/' && basePath[basePath.length()-1] != '\\')
basePath.push_back('/');
std::string fullname = basePath + VMapManager2::getMapFileName(mapID);
bool success = true;
FILE* rf = fopen(fullname.c_str(), "rb");
if (!rf)
return false;
// TODO: check magic number when implemented...
char tiled;
char chunk[8];
if (!readChunk(rf, chunk, VMAP_MAGIC, 8) || fread(&tiled, sizeof(char), 1, rf) != 1)
{
fclose(rf);
return false;
}
if (tiled)
{
std::string tilefile = basePath + getTileFileName(mapID, tileX, tileY);
FILE* tf = fopen(tilefile.c_str(), "rb");
if (!tf)
success = false;
else
{
if (!readChunk(tf, chunk, VMAP_MAGIC, 8))
success = false;
fclose(tf);
}
}
fclose(rf);
return success;
}
//=========================================================
bool StaticMapTree::InitMap(const std::string &fname, VMapManager2* vm)
{
//VMAP_DEBUG_LOG(LOG_FILTER_MAPS, "StaticMapTree::InitMap() : initializing StaticMapTree '%s'", fname.c_str());
bool success = false;
std::string fullname = iBasePath + fname;
FILE* rf = fopen(fullname.c_str(), "rb");
if (!rf)
return false;
char chunk[8];
char tiled = '\0';
if (readChunk(rf, chunk, VMAP_MAGIC, 8) && fread(&tiled, sizeof(char), 1, rf) == 1 &&
readChunk(rf, chunk, "NODE", 4) && iTree.readFromFile(rf))
{
iNTreeValues = iTree.primCount();
iTreeValues = new ModelInstance[iNTreeValues];
success = readChunk(rf, chunk, "GOBJ", 4);
}
iIsTiled = bool(tiled);
// global model spawns
// only non-tiled maps have them, and if so exactly one (so far at least...)
ModelSpawn spawn;
#ifdef VMAP_DEBUG
//TC_LOG_DEBUG(LOG_FILTER_MAPS, "StaticMapTree::InitMap() : map isTiled: %u", static_cast<uint32>(iIsTiled));
#endif
if (!iIsTiled && ModelSpawn::readFromFile(rf, spawn))
{
WorldModel* model = vm->acquireModelInstance(iBasePath, spawn.name);
//VMAP_DEBUG_LOG(LOG_FILTER_MAPS, "StaticMapTree::InitMap() : loading %s", spawn.name.c_str());
if (model)
{
// assume that global model always is the first and only tree value (could be improved...)
iTreeValues[0] = ModelInstance(spawn, model);
iLoadedSpawns[0] = 1;
}
else
{
success = false;
//VMAP_ERROR_LOG(LOG_FILTER_GENERAL, "StaticMapTree::InitMap() : could not acquire WorldModel pointer for '%s'", spawn.name.c_str());
}
}
fclose(rf);
return success;
}
//=========================================================
void StaticMapTree::UnloadMap(VMapManager2* vm)
{
for (loadedSpawnMap::iterator i = iLoadedSpawns.begin(); i != iLoadedSpawns.end(); ++i)
{
iTreeValues[i->first].setUnloaded();
for (uint32 refCount = 0; refCount < i->second; ++refCount)
vm->releaseModelInstance(iTreeValues[i->first].name);
}
iLoadedSpawns.clear();
iLoadedTiles.clear();
}
//=========================================================
bool StaticMapTree::LoadMapTile(uint32 tileX, uint32 tileY, VMapManager2* vm)
{
if (!iIsTiled)
{
// currently, core creates grids for all maps, whether it has terrain tiles or not
// so we need "fake" tile loads to know when we can unload map geometry
iLoadedTiles[packTileID(tileX, tileY)] = false;
return true;
}
if (!iTreeValues)
{
sLog->outError("StaticMapTree::LoadMapTile() : tree has not been initialized [%u, %u]", tileX, tileY);
return false;
}
bool result = true;
std::string tilefile = iBasePath + getTileFileName(iMapID, tileX, tileY);
FILE* tf = fopen(tilefile.c_str(), "rb");
if (tf)
{
char chunk[8];
if (!readChunk(tf, chunk, VMAP_MAGIC, 8))
result = false;
uint32 numSpawns = 0;
if (result && fread(&numSpawns, sizeof(uint32), 1, tf) != 1)
result = false;
for (uint32 i=0; i<numSpawns && result; ++i)
{
// read model spawns
ModelSpawn spawn;
result = ModelSpawn::readFromFile(tf, spawn);
if (result)
{
// acquire model instance
WorldModel* model = vm->acquireModelInstance(iBasePath, spawn.name);
if (!model)
sLog->outError("StaticMapTree::LoadMapTile() : could not acquire WorldModel pointer [%u, %u]", tileX, tileY);
// update tree
uint32 referencedVal;
if (fread(&referencedVal, sizeof(uint32), 1, tf) == 1)
{
if (!iLoadedSpawns.count(referencedVal))
{
#ifdef VMAP_DEBUG
if (referencedVal > iNTreeValues)
{
;//sLog->outDebug(LOG_FILTER_MAPS, "StaticMapTree::LoadMapTile() : invalid tree element (%u/%u)", referencedVal, iNTreeValues);
continue;
}
#endif
iTreeValues[referencedVal] = ModelInstance(spawn, model);
iLoadedSpawns[referencedVal] = 1;
}
else
{
++iLoadedSpawns[referencedVal];
#ifdef VMAP_DEBUG
if (iTreeValues[referencedVal].ID != spawn.ID)
;//sLog->outDebug(LOG_FILTER_MAPS, "StaticMapTree::LoadMapTile() : trying to load wrong spawn in node");
else if (iTreeValues[referencedVal].name != spawn.name)
;//sLog->outDebug(LOG_FILTER_MAPS, "StaticMapTree::LoadMapTile() : name collision on GUID=%u", spawn.ID);
#endif
}
}
else
result = false;
}
}
iLoadedTiles[packTileID(tileX, tileY)] = true;
fclose(tf);
}
else
iLoadedTiles[packTileID(tileX, tileY)] = false;
return result;
}
//=========================================================
void StaticMapTree::UnloadMapTile(uint32 tileX, uint32 tileY, VMapManager2* vm)
{
uint32 tileID = packTileID(tileX, tileY);
loadedTileMap::iterator tile = iLoadedTiles.find(tileID);
if (tile == iLoadedTiles.end())
{
sLog->outError("StaticMapTree::UnloadMapTile() : trying to unload non-loaded tile - Map:%u X:%u Y:%u", iMapID, tileX, tileY);
return;
}
if (tile->second) // file associated with tile
{
std::string tilefile = iBasePath + getTileFileName(iMapID, tileX, tileY);
FILE* tf = fopen(tilefile.c_str(), "rb");
if (tf)
{
bool result=true;
char chunk[8];
if (!readChunk(tf, chunk, VMAP_MAGIC, 8))
result = false;
uint32 numSpawns;
if (fread(&numSpawns, sizeof(uint32), 1, tf) != 1)
result = false;
for (uint32 i=0; i<numSpawns && result; ++i)
{
// read model spawns
ModelSpawn spawn;
result = ModelSpawn::readFromFile(tf, spawn);
if (result)
{
// release model instance
vm->releaseModelInstance(spawn.name);
// update tree
uint32 referencedNode;
if (fread(&referencedNode, sizeof(uint32), 1, tf) != 1)
result = false;
else
{
if (!iLoadedSpawns.count(referencedNode))
sLog->outError("StaticMapTree::UnloadMapTile() : trying to unload non-referenced model '%s' (ID:%u)", spawn.name.c_str(), spawn.ID);
else if (--iLoadedSpawns[referencedNode] == 0)
{
iTreeValues[referencedNode].setUnloaded();
iLoadedSpawns.erase(referencedNode);
}
}
}
}
fclose(tf);
}
}
iLoadedTiles.erase(tile);
}
}
|
DantestyleXD/azerothcore-wotlk
|
modules/worldengine/lib-collision/src/Maps/MapTree.cpp
|
C++
|
agpl-3.0
| 17,431
|
import { t } from '@lingui/macro';
import { formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import { SpellLink } from 'interface';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import BoringSpellValue from 'parser/ui/BoringSpellValue';
import Statistic from 'parser/ui/Statistic';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';
const GOE_DURATION = 15000;
const debug = false;
class GuardianOfElune extends Analyzer {
GoEProcsTotal = 0;
lastGoEProcTime = 0;
consumedGoEProc = 0;
overwrittenGoEProc = 0;
nonGoEIronFur = 0;
GoEIronFur = 0;
nonGoEFRegen = 0;
GoEFRegen = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.GUARDIAN_OF_ELUNE_TALENT.id);
this.addEventListener(
Events.applybuff.by(SELECTED_PLAYER).spell(SPELLS.GUARDIAN_OF_ELUNE),
this.onApplyBuff,
);
this.addEventListener(
Events.refreshbuff.by(SELECTED_PLAYER).spell(SPELLS.GUARDIAN_OF_ELUNE),
this.onRefreshBuff,
);
this.addEventListener(
Events.cast.by(SELECTED_PLAYER).spell(SPELLS.IRONFUR),
this.onCastIronfur,
);
this.addEventListener(
Events.cast.by(SELECTED_PLAYER).spell(SPELLS.FRENZIED_REGENERATION),
this.onCastFrenziedRegen,
);
}
onApplyBuff(event) {
this.lastGoEProcTime = event.timestamp;
debug && console.log('Guardian of Elune applied');
this.GoEProcsTotal += 1;
}
onRefreshBuff(event) {
// Captured Overwritten GoE Buffs for use in wasted buff calculations
this.lastGoEProcTime = event.timestamp;
debug && console.log('Guardian of Elune Overwritten');
this.GoEProcsTotal += 1;
this.overwrittenGoEProc += 1;
}
onCastIronfur(event) {
if (this.lastGoEProcTime !== event.timestamp) {
if (this.lastGoEProcTime === null) {
this.nonGoEIronFur += 1;
return;
}
const GoETimeframe = this.lastGoEProcTime + GOE_DURATION;
if (event.timestamp > GoETimeframe) {
this.nonGoEIronFur += 1;
} else {
this.consumedGoEProc += 1;
this.GoEIronFur += 1;
debug && console.log(`Guardian of Elune Proc Consumed / Timestamp: ${event.timestamp}`);
this.lastGoEProcTime = null;
}
}
}
onCastFrenziedRegen(event) {
if (this.lastGoEProcTime !== event.timestamp) {
if (this.lastGoEProcTime === null) {
this.nonGoEFRegen += 1;
return;
}
const GoETimeframe = this.lastGoEProcTime + GOE_DURATION;
if (event.timestamp > GoETimeframe) {
this.nonGoEFRegen += 1;
} else {
this.consumedGoEProc += 1;
this.GoEFRegen += 1;
debug && console.log(`Guardian of Elune Proc Consumed / Timestamp: ${event.timestamp}`);
this.lastGoEProcTime = null;
}
}
}
suggestions(when) {
const unusedGoEProcs = 1 - this.consumedGoEProc / this.GoEProcsTotal;
when(unusedGoEProcs)
.isGreaterThan(0.3)
.addSuggestion((suggest, actual, recommended) =>
suggest(
<span>
You wasted {formatPercentage(unusedGoEProcs)}% of your{' '}
<SpellLink id={SPELLS.GUARDIAN_OF_ELUNE.id} /> procs. Try to use the procs as soon as
you get them so they are not overwritten.
</span>,
)
.icon(SPELLS.GUARDIAN_OF_ELUNE.icon)
.actual(
t({
id: 'druid.guardian.suggestions.guardianOfElune.unused',
message: `${formatPercentage(unusedGoEProcs)}% unused`,
}),
)
.recommended(`${Math.round(formatPercentage(recommended))}% or less is recommended`)
.regular(recommended + 0.15)
.major(recommended + 0.3),
);
}
statistic() {
const unusedGoEProcs = 1 - this.consumedGoEProc / this.GoEProcsTotal;
return (
<Statistic
position={STATISTIC_ORDER.CORE(7)}
category={STATISTIC_CATEGORY.TALENTS}
size="flexible"
tooltip={
<>
You got total <strong>{this.GGProcsTotal}</strong> galactic guardian procs and{' '}
<strong>used {this.consumedGGProc}</strong> of them.
</>
}
>
<BoringSpellValue
spellId={SPELLS.GUARDIAN_OF_ELUNE.id}
value={`${formatPercentage(unusedGoEProcs)}%`}
label="Unused Guardian of Elune"
/>
</Statistic>
);
}
}
export default GuardianOfElune;
|
Juko8/WoWAnalyzer
|
analysis/druidguardian/src/modules/features/GuardianOfElune.js
|
JavaScript
|
agpl-3.0
| 4,590
|
og.PrintCalendar = {};
og.PrintCalendar.printCalendar = function(genid){
var printWindow = this.createPrintWindow(genid);
var html = document.getElementById(genid + 'view_calendar').innerHTML.replace(/gridcontainer/, '');
printWindow.document.write(html);
og.PrintCalendar.closePrintWindow(printWindow);
}
og.PrintCalendar.createPrintWindow = function(genid){
var ancho = document.getElementById(genid + 'view_calendar').offsetWidth;
var alto = document.getElementById(genid + 'view_calendar').offsetHeight;
var disp_setting = "toolbar=yes,location=no,directories=yes,menubar=yes,scrollbars=yes,width="+ancho+", height="+(alto+20)+", left=100, top=25";
var printWindow = window.open("","",disp_setting);
var cal_height = 0;
var container = $('#calendar');
while ($(container) && $(container).height() == 0) {
container = $(container).parent();
}
if ($(container)) cal_height = $(container).height();
if (cal_height > 0) {
cal_height = (cal_height > 600 ? cal_height : 600) + 'px';
} else {
cal_height = '100%';
}
printWindow.document.open();
printWindow.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml">');
printWindow.document.write('<html><head><title>' + lang('print') + '</title>');
printWindow.document.write('<link href="' + og.hostName + '/public/assets/themes/default/stylesheets/website.css" rel="stylesheet" type="text/css">');
printWindow.document.write('<link href="' + og.hostName + '/public/assets/themes/default/stylesheets/event/week.css" rel="stylesheet" type="text/css">');
printWindow.document.write('<link href="' + og.hostName + '/public/assets/themes/default/stylesheets/event/day.css" rel="stylesheet" type="text/css">');
printWindow.document.write('<link href="' + og.hostName + '/public/assets/themes/default/stylesheets/calendar_print.css" rel="stylesheet" type="text/css">');
//printWindow.document.write('<style type="text/css" media="print">div.page {writing-mode: tb-rl;height: 80%;margin: 10% 0%;}</style>');
printWindow.document.write('</head><body onLoad="self.print()"><div class="page">');
return printWindow;
}
og.PrintCalendar.closePrintWindow = function(printWindow){
printWindow.document.write('</div></body></html>');
printWindow.document.close();
printWindow.focus();
}
|
fengoffice/fengoffice
|
public/assets/javascript/og/CalendarPrint.js
|
JavaScript
|
agpl-3.0
| 2,377
|
-- Convert schema '/home/abeverley/git/GADS/share/migrations/_source/deploy/65/001-auto.yml' to '/home/abeverley/git/GADS/share/migrations/_source/deploy/64/001-auto.yml':;
;
BEGIN;
;
ALTER TABLE site DROP COLUMN remember_user_location;
;
COMMIT;
|
ctrlo/GADS
|
share/migrations/PostgreSQL/downgrade/65-64/001-auto.sql
|
SQL
|
agpl-3.0
| 252
|
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
/**
* @ngdoc react
* @name SidePanel
* @description SidePanel Component used usually for Advanced Search panels
*/
export const SidePanel: React.StatelessComponent<any> = (
{children, shadowRight, shadowLeft, transparent, className},
) => (
<div
className={classNames(
'side-panel',
{'side-panel--shadow-right': shadowRight},
{'side-panel--transparent': transparent},
{'side-panel--shadow-left': shadowLeft},
className,
)}
>
{children}
</div>
);
SidePanel.propTypes = {
children: PropTypes.node,
shadowRight: PropTypes.bool,
shadowLeft: PropTypes.bool,
transparent: PropTypes.bool,
className: PropTypes.string,
};
SidePanel.defaultProps = {
shadowRight: false,
shadowLeft: false,
transparent: false,
className: '',
};
|
superdesk/superdesk-client-core
|
scripts/core/ui/components/SidePanel/SidePanel.tsx
|
TypeScript
|
agpl-3.0
| 961
|
dojo.provide("dojo.widget.ShowSlide");
dojo.require("dojo.widget.*");
dojo.require("dojo.lang.common");
dojo.widget.ShowSlide = function(){
}
dojo.lang.extend(dojo.widget.ShowSlide, {
title: "",
_action: -1,
isContainer: true,
_components: {},
_actions: [],
gotoAction: function(/*int*/ action){
this._action = action;
},
nextAction: function(/*Event?*/ event){
if((this._action + 1) != this._actions.length){
++this._action;
return true; // boolean
}
return false; // boolean
},
previousAction: function(/*Event?*/ event){
if((this._action - 1) != -1){
--this._action;
return true; // boolean
}
return false; // boolean
}
});
dojo.requireAfterIf("html", "dojo.widget.html.ShowSlide");
|
dedomenon/dedomenon
|
public/javascripts/dojo/src/widget/ShowSlide.js
|
JavaScript
|
agpl-3.0
| 725
|
-- Convert schema '/home/abeverley/git/GADS/share/migrations/_source/deploy/82/001-auto.yml' to '/home/abeverley/git/GADS/share/migrations/_source/deploy/81/001-auto.yml':;
;
BEGIN;
;
ALTER TABLE site DROP COLUMN user_editable_fields;
;
COMMIT;
|
ctrlo/GADS
|
share/migrations/PostgreSQL/downgrade/82-81/001-auto.sql
|
SQL
|
agpl-3.0
| 250
|
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'UserFeeds'
db.create_table(u'core_userfeeds', (
('user', self.gf('django.db.models.fields.related.OneToOneField')(related_name='feeds', unique=True, primary_key=True, to=orm['base.User'])),
('imported_items', self.gf('django.db.models.fields.related.OneToOneField')(blank=True, related_name='imported_items', unique=True, null=True, to=orm['core.BaseFeed'])),
('sent_items', self.gf('django.db.models.fields.related.OneToOneField')(blank=True, related_name='sent_items', unique=True, null=True, to=orm['core.BaseFeed'])),
('received_items', self.gf('django.db.models.fields.related.OneToOneField')(blank=True, related_name='received_items', unique=True, null=True, to=orm['core.BaseFeed'])),
('written_items', self.gf('django.db.models.fields.related.OneToOneField')(blank=True, related_name='written_items', unique=True, null=True, to=orm['core.BaseFeed'])),
))
db.send_create_signal('core', ['UserFeeds'])
# Adding M2M table for field blogs on 'UserFeeds'
m2m_table_name = db.shorten_name(u'core_userfeeds_blogs')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('userfeeds', models.ForeignKey(orm['core.userfeeds'], null=False)),
('basefeed', models.ForeignKey(orm['core.basefeed'], null=False))
))
db.create_unique(m2m_table_name, ['userfeeds_id', 'basefeed_id'])
# Adding model 'UserSubscriptions'
db.create_table(u'core_usersubscriptions', (
('user', self.gf('django.db.models.fields.related.OneToOneField')(related_name='subscriptions', unique=True, primary_key=True, to=orm['base.User'])),
('imported_items', self.gf('django.db.models.fields.related.OneToOneField')(blank=True, related_name='imported_items', unique=True, null=True, to=orm['core.Subscription'])),
('sent_items', self.gf('django.db.models.fields.related.OneToOneField')(blank=True, related_name='sent_items', unique=True, null=True, to=orm['core.Subscription'])),
('received_items', self.gf('django.db.models.fields.related.OneToOneField')(blank=True, related_name='received_items', unique=True, null=True, to=orm['core.Subscription'])),
('written_items', self.gf('django.db.models.fields.related.OneToOneField')(blank=True, related_name='written_items', unique=True, null=True, to=orm['core.Subscription'])),
))
db.send_create_signal('core', ['UserSubscriptions'])
# Adding M2M table for field blogs on 'UserSubscriptions'
m2m_table_name = db.shorten_name(u'core_usersubscriptions_blogs')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('usersubscriptions', models.ForeignKey(orm['core.usersubscriptions'], null=False)),
('subscription', models.ForeignKey(orm['core.subscription'], null=False))
))
db.create_unique(m2m_table_name, ['usersubscriptions_id', 'subscription_id'])
def backwards(self, orm):
# Deleting model 'UserFeeds'
db.delete_table(u'core_userfeeds')
# Removing M2M table for field blogs on 'UserFeeds'
db.delete_table(db.shorten_name(u'core_userfeeds_blogs'))
# Deleting model 'UserSubscriptions'
db.delete_table(u'core_usersubscriptions')
# Removing M2M table for field blogs on 'UserSubscriptions'
db.delete_table(db.shorten_name(u'core_usersubscriptions_blogs'))
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'base.user': {
'Meta': {'object_name': 'User'},
'data': ('jsonfield.fields.JSONField', [], {'default': '{}', 'blank': 'True'}),
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '254', 'db_index': 'True'}),
'email_announcements': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '64', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
'hash_codes': ('jsonfield.fields.JSONField', [], {'default': "{'unsubscribe': 'a2a11d045c484d9cb16448cca4075f1d'}", 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '64', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'register_data': ('jsonfield.fields.JSONField', [], {'default': '{}', 'blank': 'True'}),
'sent_emails': ('jsonfield.fields.JSONField', [], {'default': '{}', 'blank': 'True'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '254', 'db_index': 'True'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'core.article': {
'Meta': {'object_name': 'Article', '_ormbases': ['core.BaseItem']},
u'baseitem_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['core.BaseItem']", 'unique': 'True', 'primary_key': 'True'}),
'content': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'content_error': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'content_type': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'date_published': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'is_orphaned': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'pages_urls': ('jsonfield.fields.JSONField', [], {'default': "u'[]'", 'blank': 'True'}),
'publishers': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['base.User']", 'symmetrical': 'False', 'blank': 'True'}),
'url': ('django.db.models.fields.URLField', [], {'unique': 'True', 'max_length': '200'}),
'url_absolute': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'url_error': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'word_count': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'})
},
'core.basefeed': {
'Meta': {'object_name': 'BaseFeed'},
'closed_reason': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'date_closed': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'date_created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'auto_now_add': 'True', 'blank': 'True'}),
'date_last_fetch': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'description_en': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'description_fr': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'description_nt': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'duplicate_of': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.BaseFeed']", 'null': 'True', 'blank': 'True'}),
'errors': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}),
'fetch_interval': ('django.db.models.fields.IntegerField', [], {'default': '43200', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_good': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_internal': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_restricted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'items': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.BaseItem']", 'symmetrical': 'False', 'blank': 'True'}),
'languages': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.Language']", 'symmetrical': 'False', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'notes': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'options': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}),
'polymorphic_ctype': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'polymorphic_core.basefeed_set'", 'null': 'True', 'to': u"orm['contenttypes.ContentType']"}),
'short_description_en': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}),
'short_description_fr': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}),
'short_description_nt': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'thumbnail': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'thumbnail_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['base.User']", 'null': 'True', 'blank': 'True'})
},
'core.baseitem': {
'Meta': {'object_name': 'BaseItem'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'default_rating': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'blank': 'True'}),
'duplicate_of': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.BaseItem']"}),
'excerpt': ('django.db.models.fields.TextField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'is_restricted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'language': ('django.db.models.fields.CharField', [], {'max_length': '5'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '256'}),
'origin': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'polymorphic_ctype': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'polymorphic_core.baseitem_set'", 'null': 'True', 'to': u"orm['contenttypes.ContentType']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}),
'sources': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'sources_rel_+'", 'blank': 'True', 'to': "orm['core.BaseItem']"}),
'tags': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.SimpleTag']", 'symmetrical': 'False', 'blank': 'True'}),
'text_direction': ('django.db.models.fields.CharField', [], {'default': "u'ltr'", 'max_length': '3'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['base.User']", 'null': 'True', 'blank': 'True'})
},
'core.combinedfeed': {
'Meta': {'object_name': 'CombinedFeed'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_restricted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['base.User']"})
},
'core.combinedfeedrule': {
'Meta': {'ordering': "('position',)", 'object_name': 'CombinedFeedRule'},
'check_error': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}),
'clone_of': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.MailFeedRule']", 'null': 'True', 'blank': 'True'}),
'combinedfeed': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.CombinedFeed']"}),
'feeds': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.BaseFeed']", 'symmetrical': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_valid': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'position': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'})
},
'core.corepermissions': {
'Meta': {'object_name': 'CorePermissions'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'core.folder': {
'Meta': {'unique_together': "(('name', 'user', 'parent'),)", 'object_name': 'Folder'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
u'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
u'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'parent': ('mptt.fields.TreeForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['core.Folder']"}),
u'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
u'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['base.User']"})
},
'core.helpcontent': {
'Meta': {'ordering': "['ordering', 'id']", 'object_name': 'HelpContent'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'content_en': ('django.db.models.fields.TextField', [], {}),
'content_fr': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'content_nt': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'label': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}),
'name_en': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'name_fr': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
'name_nt': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
'ordering': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
'core.historyentry': {
'Meta': {'object_name': 'HistoryEntry'},
'date_created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'polymorphic_ctype': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'polymorphic_core.historyentry_set'", 'null': 'True', 'to': u"orm['contenttypes.ContentType']"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['base.User']"})
},
'core.language': {
'Meta': {'object_name': 'Language'},
'dj_code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '16'}),
'duplicate_of': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Language']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
u'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
u'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'parent': ('mptt.fields.TreeForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['core.Language']"}),
u'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
u'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
},
'core.mailaccount': {
'Meta': {'unique_together': "(('user', 'hostname', 'username'),)", 'object_name': 'MailAccount'},
'conn_error': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}),
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_last_conn': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2007, 1, 1, 0, 0)'}),
'hostname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_usable': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}),
'port': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'use_ssl': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['base.User']"}),
'username': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'})
},
'core.mailfeed': {
'Meta': {'object_name': 'MailFeed', '_ormbases': ['core.BaseFeed']},
'account': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['core.MailAccount']", 'null': 'True', 'blank': 'True'}),
u'basefeed_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['core.BaseFeed']", 'unique': 'True', 'primary_key': 'True'}),
'finish_action': ('django.db.models.fields.CharField', [], {'default': "u'markread'", 'max_length': '10'}),
'match_action': ('django.db.models.fields.CharField', [], {'default': "u'scrape'", 'max_length': '10'}),
'rules_operation': ('django.db.models.fields.CharField', [], {'default': "u'any'", 'max_length': '10'}),
'scrape_blacklist': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'scrape_whitelist': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'null': 'True', 'blank': 'True'})
},
'core.mailfeedrule': {
'Meta': {'ordering': "('group', 'position')", 'object_name': 'MailFeedRule'},
'check_error': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}),
'clone_of': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.MailFeedRule']", 'null': 'True', 'blank': 'True'}),
'group': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'group_operation': ('django.db.models.fields.CharField', [], {'default': "u'any'", 'max_length': '10', 'null': 'True', 'blank': 'True'}),
'header_field': ('django.db.models.fields.CharField', [], {'default': "u'any'", 'max_length': '10'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_valid': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'mailfeed': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.MailFeed']"}),
'match_case': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'match_type': ('django.db.models.fields.CharField', [], {'default': "u'contains'", 'max_length': '10'}),
'match_value': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '1024'}),
'other_header': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'position': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'})
},
'core.read': {
'Meta': {'unique_together': "(('user', 'item'),)", 'object_name': 'Read'},
'bookmark_type': ('django.db.models.fields.CharField', [], {'default': "u'U'", 'max_length': '2'}),
'check_set_subscriptions_131004_done': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'date_analysis': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'date_archived': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'date_auto_read': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'date_bookmarked': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'date_created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'date_fact': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'date_fun': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'date_knowhow': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'date_knowledge': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'date_number': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'date_prospective': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'date_quote': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'date_read': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'date_rules': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'date_starred': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_analysis': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_archived': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_auto_read': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_bookmarked': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_fact': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_fun': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_good': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_knowhow': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_knowledge': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_number': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_prospective': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_quote': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_read': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_rules': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_starred': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),
'item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.BaseItem']"}),
'knowledge_type': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}),
'rating': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'senders': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'senders'", 'symmetrical': 'False', 'to': u"orm['base.User']"}),
'tags': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.SimpleTag']", 'symmetrical': 'False'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['base.User']"})
},
'core.rssatomfeed': {
'Meta': {'object_name': 'RssAtomFeed', '_ormbases': ['core.BaseFeed']},
u'basefeed_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['core.BaseFeed']", 'unique': 'True', 'primary_key': 'True'}),
'last_etag': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}),
'last_modified': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}),
'tags': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.SimpleTag']", 'symmetrical': 'False', 'blank': 'True'}),
'url': ('django.db.models.fields.URLField', [], {'unique': 'True', 'max_length': '200'}),
'website': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.WebSite']", 'null': 'True', 'blank': 'True'})
},
'core.simpletag': {
'Meta': {'unique_together': "(('name', 'language'),)", 'object_name': 'SimpleTag'},
'duplicate_of': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.SimpleTag']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Language']", 'null': 'True'}),
u'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
u'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'origin_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'origin_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
'parent': ('mptt.fields.TreeForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['core.SimpleTag']"}),
u'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True'}),
u'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
},
'core.subscription': {
'Meta': {'unique_together': "(('feed', 'user'),)", 'object_name': 'Subscription'},
'feed': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.BaseFeed']"}),
'folders': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.Folder']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'items': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.Read']", 'symmetrical': 'False', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'notes': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'tags': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.SimpleTag']", 'symmetrical': 'False', 'blank': 'True'}),
'thumbnail': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'thumbnail_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['base.User']"})
},
'core.userfeeds': {
'Meta': {'object_name': 'UserFeeds'},
'blogs': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['core.BaseFeed']", 'null': 'True', 'blank': 'True'}),
'imported_items': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'imported_items'", 'unique': 'True', 'null': 'True', 'to': "orm['core.BaseFeed']"}),
'received_items': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'received_items'", 'unique': 'True', 'null': 'True', 'to': "orm['core.BaseFeed']"}),
'sent_items': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'sent_items'", 'unique': 'True', 'null': 'True', 'to': "orm['core.BaseFeed']"}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'feeds'", 'unique': 'True', 'primary_key': 'True', 'to': u"orm['base.User']"}),
'written_items': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'written_items'", 'unique': 'True', 'null': 'True', 'to': "orm['core.BaseFeed']"})
},
'core.userimport': {
'Meta': {'object_name': 'UserImport', '_ormbases': ['core.HistoryEntry']},
'date_finished': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'date_started': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
u'historyentry_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['core.HistoryEntry']", 'unique': 'True', 'primary_key': 'True'}),
'lines': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'results': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}),
'urls': ('django.db.models.fields.TextField', [], {})
},
'core.usersubscriptions': {
'Meta': {'object_name': 'UserSubscriptions'},
'blogs': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'blogs'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['core.Subscription']"}),
'imported_items': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'imported_items'", 'unique': 'True', 'null': 'True', 'to': "orm['core.Subscription']"}),
'received_items': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'received_items'", 'unique': 'True', 'null': 'True', 'to': "orm['core.Subscription']"}),
'sent_items': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'sent_items'", 'unique': 'True', 'null': 'True', 'to': "orm['core.Subscription']"}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'subscriptions'", 'unique': 'True', 'primary_key': 'True', 'to': u"orm['base.User']"}),
'written_items': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'written_items'", 'unique': 'True', 'null': 'True', 'to': "orm['core.Subscription']"})
},
'core.website': {
'Meta': {'object_name': 'WebSite'},
'description_en': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'description_fr': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'description_nt': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'duplicate_of': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.WebSite']", 'null': 'True', 'blank': 'True'}),
'fetch_limit_nr': ('django.db.models.fields.IntegerField', [], {'default': '16', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'image_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
u'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
u'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'mail_warned': ('jsonfield.fields.JSONField', [], {'default': "u'[]'", 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
'parent': ('mptt.fields.TreeForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['core.WebSite']"}),
u'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'short_description_en': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}),
'short_description_fr': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}),
'short_description_nt': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
u'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'url': ('django.db.models.fields.URLField', [], {'unique': 'True', 'max_length': '200', 'blank': 'True'})
}
}
complete_apps = ['core']
|
1flow/1flow
|
oneflow/core/migrations/0036_auto__add_userfeeds__add_usersubscriptions.py
|
Python
|
agpl-3.0
| 37,603
|
/*
* Copyright (C)
*
* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*/
#include "MPQManager.h"
#include "WDT.h"
#include "ContinentBuilder.h"
#include "Cache.h"
#include "DBC.h"
#include "Constants.h"
#include "Model.h"
#include "Recast.h"
#include "DetourNavMesh.h"
#include "DetourNavMeshQuery.h"
#include <stdio.h>
#include <set>
MPQManager* MPQHandler;
CacheClass* Cache;
void ExtractMMaps(std::set<uint32>& mapIds, uint32 threads)
{
DBC* dbc = MPQHandler->GetDBC("Map");
printf("Map.dbc contains %u rows.\n", dbc->Records.size());
for (std::vector<Record*>::iterator itr = dbc->Records.begin(); itr != dbc->Records.end(); ++itr)
{
uint32 mapId = (*itr)->Values[0];
// Skip this map if a list of specific maps was provided and this one is not contained in it.
if (!mapIds.empty() && mapIds.find(mapId) == mapIds.end())
{
if (Constants::Debug)
printf("Map %u will not be built.\n", mapId);
continue;
}
std::string name = (*itr)->GetString(1);
WDT wdt("World\\maps\\" + name + "\\" + name + ".wdt");
if (!wdt.IsValid)
{
printf("Could not find WDT data for map %u (%s)\n", mapId, name.c_str());
continue;
}
printf("Building %s MapId %u\n", name.c_str(), mapId);
ContinentBuilder builder(name, mapId, &wdt, threads);
builder.Build();
}
}
void ExtractDBCs()
{
printf("Extracting DBCs\n");
// Create the file system structure
std::string baseDBCPath = "dbc/";
Utils::CreateDir(baseDBCPath);
std::set<std::string> DBCFiles;
const size_t extLen = strlen(".dbc");
// Populate list of DBC files
// We get the DBC names by going over the (guaranteed to exist) default locale files
// Then we look in other locale files in case that they are available.
for (std::vector<std::string>::iterator itr = MPQHandler->LocaleFiles[MPQHandler->BaseLocale]->Files.begin(); itr != MPQHandler->LocaleFiles[MPQHandler->BaseLocale]->Files.end(); ++itr)
if (itr->rfind(".dbc") == itr->length() - extLen) // Check if the extension is ".dbc"
DBCFiles.insert(*itr);
const size_t folderLen = strlen("DBFilesClient\\");
// Iterate over all available locales
for (std::set<uint32>::iterator itr = MPQHandler->AvailableLocales.begin(); itr != MPQHandler->AvailableLocales.end(); ++itr)
{
printf("Extracting DBCs for locale %s\n", MPQManager::Languages[*itr]);
std::string path = baseDBCPath;
if (*itr != uint32(MPQHandler->BaseLocale))
{
path += std::string(MPQManager::Languages[*itr]) + "/";
Utils::CreateDir(path);
}
std::string component = "component.wow-" + std::string(MPQManager::Languages[*itr]) + ".txt";
// Extract the component file
Utils::SaveToDisk(MPQHandler->GetFileFrom(component, MPQHandler->LocaleFiles[*itr]), path + component);
// Extract the DBC files for the given locale
for (std::set<std::string>::iterator itr2 = DBCFiles.begin(); itr2 != DBCFiles.end(); ++itr2)
Utils::SaveToDisk(MPQHandler->GetFileFrom(*itr2, MPQHandler->LocaleFiles[*itr]), path + (itr2->c_str() + folderLen));
}
printf("DBC extraction finished!\n");
}
void ExtractGameobjectModels()
{
Constants::ToWoWCoords = true;
printf("Extracting GameObject models\n");
std::string baseBuildingsPath = "Buildings/";
std::string baseVmapsPath = "vmaps/";
Utils::CreateDir(baseVmapsPath);
Utils::CreateDir(baseBuildingsPath);
FILE* modelList = fopen((baseVmapsPath + "GameObjectModels.list").c_str(), "wb");
if (!modelList)
{
printf("Could not create file vmaps/GameObjectModels.list, please make sure that you have the write permissions in the folder\n");
return;
}
DBC* dbc = MPQHandler->GetDBC("GameObjectDisplayInfo");
for (std::vector<Record*>::iterator itr = dbc->Records.begin(); itr != dbc->Records.end(); ++itr)
{
std::string path = (*itr)->GetString(1);
std::string fileName = Utils::GetPlainName(path.c_str());
std::string extension = Utils::GetExtension(fileName);
// Convert the extension to lowercase
std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
if (extension == "mdx" || extension == "m2")
{
fileName = Utils::FixModelPath(fileName);
Model model(path);
if (model.IsBad)
continue;
FILE* output = fopen((baseBuildingsPath + fileName).c_str(), "wb");
if (!output)
{
printf("Could not create file %s, please check that you have write permissions\n", (baseBuildingsPath + fileName).c_str());
continue;
}
// Placeholder for 0 values
int Nop[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
fwrite(Constants::VMAPMagic, 8, 1, output);
uint32 numVerts = model.Header.CountBoundingVertices;
fwrite(&numVerts, sizeof(uint32), 1, output);
uint32 numGroups = 1;
fwrite(&numGroups, sizeof(uint32), 1, output);
fwrite(Nop, 4 * 3 , 1, output); // rootwmoid, flags, groupid
fwrite(Nop, sizeof(float), 3 * 2, output);//bbox, only needed for WMO currently
fwrite(Nop, 4, 1, output);// liquidflags
fwrite("GRP ", 4, 1, output);
uint32 branches = 1;
uint32 wsize = sizeof(branches) + sizeof(uint32) * branches;
fwrite(&wsize, sizeof(uint32), 1, output);
fwrite(&branches, sizeof(branches), 1, output);
uint32 numTris = model.Header.CountBoundingTriangles;
fwrite(&numTris, sizeof(uint32), 1, output);
fwrite("INDX", 4, 1, output);
wsize = sizeof(uint32) + sizeof(unsigned short) * numTris;
fwrite(&wsize, sizeof(int), 1, output);
fwrite(&numTris, sizeof(uint32), 1, output);
uint16* indices = new uint16[numTris];
if (numTris > 0)
{
uint32 i = 0;
for (std::vector<Triangle<uint16> >::iterator itr2 = model.Triangles.begin(); itr2 != model.Triangles.end(); ++itr2, ++i)
{
indices[i * 3 + 0] = itr2->V0;
indices[i * 3 + 1] = itr2->V1;
indices[i * 3 + 2] = itr2->V2;
}
fwrite(indices, sizeof(uint16), numTris, output);
}
fwrite("VERT", 4, 1, output);
wsize = sizeof(int) + sizeof(float) * 3 * numVerts;
fwrite(&wsize, sizeof(int), 1, output);
fwrite(&numVerts, sizeof(int), 1, output);
float* vertices = new float[numVerts*3];
if (numVerts > 0)
{
uint32 i = 0;
for (std::vector<Vector3>::iterator itr2 = model.Vertices.begin(); itr2 != model.Vertices.end(); ++itr2, ++i)
{
vertices[i * 3 + 0] = itr2->x;
vertices[i * 3 + 1] = itr2->y;
vertices[i * 3 + 2] = itr2->z;
}
fwrite(vertices, sizeof(float), numVerts * 3, output);
}
fclose(output);
delete[] indices;
delete[] vertices;
uint32 displayId = (*itr)->Values[0];
uint32 pathLength = fileName.size();
fwrite(&displayId, sizeof(uint32), 1, modelList);
fwrite(&pathLength, sizeof(uint32), 1, modelList);
fwrite(fileName.c_str(), sizeof(char), pathLength, modelList);
}
else if (extension == "wmo")
{
WorldModelRoot model(path);
FILE* output = fopen((baseBuildingsPath + fileName).c_str(), "wb");
if (!output)
{
printf("Could not create file %s, please check that you have write permissions\n", (baseBuildingsPath + fileName).c_str());
continue;
}
fwrite(Constants::VMAPMagic, 1, 8, output);
uint32 numVertices = 0;
fwrite(&numVertices, sizeof(uint32), 1, output); // will be filled later
fwrite(&model.Header.CountGroups, sizeof(uint32), 1, output);
fwrite(&model.Header.WmoId, sizeof(uint32), 1, output);
const char grp[] = { 'G' , 'R' , 'P', ' ' };
for (std::vector<WorldModelGroup>::iterator itr2 = model.Groups.begin(); itr2 != model.Groups.end(); ++itr2)
{
const WMOGroupHeader& header = itr2->Header;
fwrite(&header.Flags, sizeof(uint32), 1, output);
fwrite(&header.WmoId, sizeof(uint32), 1, output);
fwrite(&header.BoundingBox[0], sizeof(uint32), 1, output);
fwrite(&header.BoundingBox[1], sizeof(uint32), 1, output);
uint32 LiquidFlags = itr2->HasLiquidData ? 1 : 0;
fwrite(&LiquidFlags, sizeof(uint32), 1, output);
fwrite(grp, sizeof(char), sizeof(grp), output);
uint32 k = 0;
uint32 mobaBatch = itr2->MOBALength / 12;
uint32* MobaEx = new uint32[mobaBatch*4];
for(uint32 i = 8; i < itr2->MOBALength; i += 12)
MobaEx[k++] = itr2->MOBA[i];
int mobaSizeGrp = mobaBatch * 4 + 4;
fwrite(&mobaSizeGrp, 4, 1, output);
fwrite(&mobaBatch, 4, 1, output);
fwrite(MobaEx, 4, k, output);
delete[] MobaEx;
//@TODO: Finish this.
}
fclose(output);
}
}
fclose(modelList);
printf("GameObject models extraction finished!");
Constants::ToWoWCoords = false;
}
bool HandleArgs(int argc, char** argv, uint32& threads, std::set<uint32>& mapList, bool& debugOutput, uint32& extractFlags)
{
char* param = NULL;
extractFlags = 0;
for (int i = 1; i < argc; ++i)
{
if (strcmp(argv[i], "--threads") == 0)
{
param = argv[++i];
if (!param)
return false;
threads = atoi(param);
printf("Using %u threads\n", threads);
}
else if (strcmp(argv[i], "--maps") == 0)
{
param = argv[++i];
if (!param)
return false;
char* copy = strdup(param);
char* token = strtok(copy, ",");
while (token)
{
mapList.insert(atoi(token));
token = strtok(NULL, ",");
}
free(copy);
printf("Extracting only provided list of maps (%u).\n", uint32(mapList.size()));
}
else if (strcmp(argv[i], "--debug") == 0)
{
param = argv[++i];
if (!param)
return false;
debugOutput = atoi(param);
if (debugOutput)
printf("Output will contain debug information (.obj files)\n");
}
else if (strcmp(argv[i], "--extract") == 0)
{
param = argv[++i];
if (!param)
return false;
extractFlags = atoi(param);
if (!(extractFlags & Constants::EXTRACT_FLAG_ALLOWED)) // Tried to use an invalid flag
return false;
printf("Detected flags: \n");
printf("* Extract DBCs: %s\n", (extractFlags & Constants::EXTRACT_FLAG_DBC) ? "Yes" : "No");
printf("* Extract Maps: %s\n", (extractFlags & Constants::EXTRACT_FLAG_MAPS) ? "Yes" : "No");
printf("* Extract VMaps: %s\n", (extractFlags & Constants::EXTRACT_FLAG_VMAPS) ? "Yes" : "No");
printf("* Extract GameObject Models: %s\n", (extractFlags & Constants::EXTRACT_FLAG_GOB_MODELS) ? "Yes" : "No");
printf("* Extract MMaps: %s\n", (extractFlags & Constants::EXTRACT_FLAG_MMAPS) ? "Yes" : "No");
}
}
return true;
}
void PrintUsage()
{
printf("MeshExtractor help.\n");
printf("* Use \"--threads <number>\" to specify <number> threads, default to 4 (Only available when extracting MMaps)\n");
printf("* Use \"--maps a,b,c,d,e\" to extract only the maps specified (Do not use spaces)\n");
printf("* Use \"--debug 1\" to generate debug information of the tiles (Only available when extracting MMaps)\n");
printf("* Use \"--extract X\" to extract the data specified by the flag X (Note: You can combine the flags with the bitwise OR operator |). Available flags are: \n");
{
printf("- %u to extract DBCs\n", Constants::EXTRACT_FLAG_DBC);
printf("- %u to extract Maps (Not yet implemented)\n", Constants::EXTRACT_FLAG_MAPS);
printf("- %u to extract VMaps (Not yet implemented)\n", Constants::EXTRACT_FLAG_VMAPS);
printf("- %u to extract GameObject models (Not yet finished, you need to run VMapAssembler on the extracted files)\n", Constants::EXTRACT_FLAG_GOB_MODELS);
printf("- %u to extract MMaps (Not yet finished)\n", Constants::EXTRACT_FLAG_MMAPS);
}
}
void LoadTile(dtNavMesh*& navMesh, const char* tile)
{
FILE* f = fopen(tile, "rb");
if (!f)
return;
MmapTileHeader header;
if (fread(&header, sizeof(MmapTileHeader), 1, f) != 1)
return;
uint8* nav = new uint8[header.size];
if (fread(nav, header.size, 1, f) != 1)
return;
navMesh->addTile(nav, header.size, DT_TILE_FREE_DATA, 0, NULL);
fclose(f);
}
int main(int argc, char* argv[])
{
_setmaxstdio(2048);
uint32 threads = 4, extractFlags = 0;
std::set<uint32> mapIds;
if (!HandleArgs(argc, argv, threads, mapIds, Constants::Debug, extractFlags))
{
PrintUsage();
return -1;
}
if (extractFlags == 0)
{
printf("You must provide valid extract flags.\n");
PrintUsage();
return -1;
}
Cache = new CacheClass();
MPQHandler = new MPQManager();
MPQHandler->Initialize();
if (extractFlags & Constants::EXTRACT_FLAG_DBC)
ExtractDBCs();
if (extractFlags & Constants::EXTRACT_FLAG_MMAPS)
ExtractMMaps(mapIds, threads);
if (extractFlags & Constants::EXTRACT_FLAG_GOB_MODELS)
ExtractGameobjectModels();
if (extractFlags & Constants::EXTRACT_FLAG_TEST)
{
float start[] = { 16226.200195f, 16257.000000f, 13.202200f };
float end[] = { 16245.725586f, 16382.465820f, 47.384956f };
//
float m_spos[3];
m_spos[0] = -start[1];
m_spos[1] = start[2];
m_spos[2] = -start[0];
//
float m_epos[3];
m_epos[0] = -end[1];
m_epos[1] = end[2];
m_epos[2] = -end[0];
//
dtQueryFilter m_filter;
m_filter.setIncludeFlags(Constants::POLY_AREA_ROAD | Constants::POLY_AREA_TERRAIN);
m_filter.setExcludeFlags(Constants::POLY_AREA_WATER);
//
float m_polyPickExt[3];
m_polyPickExt[0] = 2.5f;
m_polyPickExt[1] = 2.5f;
m_polyPickExt[2] = 2.5f;
//
dtPolyRef m_startRef;
dtPolyRef m_endRef;
FILE* mmap = fopen("mmaps/001.mmap", "rb");
dtNavMeshParams params;
int count = fread(¶ms, sizeof(dtNavMeshParams), 1, mmap);
fclose(mmap);
if (count != 1)
{
printf("main: Error reading from .mmap\n");
return 0;
}
dtNavMesh* navMesh = new dtNavMesh();
dtNavMeshQuery* navMeshQuery = new dtNavMeshQuery();
navMesh->init(¶ms);
for (int i = 0; i <= 32; ++i)
{
for (int j = 0; j <= 32; ++j)
{
char buff[100];
sprintf(buff, "mmaps/001%02i%02i.mmtile", i, j);
LoadTile(navMesh, buff);
}
}
navMeshQuery->init(navMesh, 2048);
float nearestPt[3];
navMeshQuery->findNearestPoly(m_spos, m_polyPickExt, &m_filter, &m_startRef, nearestPt);
navMeshQuery->findNearestPoly(m_epos, m_polyPickExt, &m_filter, &m_endRef, nearestPt);
if ( !m_startRef || !m_endRef )
{
std::cerr << "Could not find any nearby poly's (" << m_startRef << "," << m_endRef << ")" << std::endl;
return 0;
}
int hops;
dtPolyRef* hopBuffer = new dtPolyRef[8192];
dtStatus status = navMeshQuery->findPath(m_startRef, m_endRef, m_spos, m_epos, &m_filter, hopBuffer, &hops, 8192);
int resultHopCount;
float* straightPath = new float[2048*3];
unsigned char* pathFlags = new unsigned char[2048];
dtPolyRef* pathRefs = new dtPolyRef[2048];
status = navMeshQuery->findStraightPath(m_spos, m_epos, hopBuffer, hops, straightPath, pathFlags, pathRefs, &resultHopCount, 2048);
std::vector<Vector3> FinalPath;
FinalPath.reserve(resultHopCount);
for (int32 i = 0; i < resultHopCount; ++i)
{
Vector3 finalV = Utils::ToWoWCoords(Vector3(straightPath[i * 3 + 0], straightPath[i * 3 + 1], straightPath[i * 3 + 2]));
FinalPath.push_back(finalV);
printf("Point %f %f %f\n", finalV.x, finalV.y, finalV.z);
}
}
return 0;
}
|
DantestyleXD/azerothcore-wotlk
|
modules/acore/extractors/mesh_extractor/MeshExtractor.cpp
|
C++
|
agpl-3.0
| 17,473
|
/*
* Copyright (c) 1997-1999, 2003 Massachusetts Institute of Technology
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/* This file was automatically generated --- DO NOT EDIT */
/* Generated on Mon Mar 24 02:08:11 EST 2003 */
#include "fftw-int.h"
#include "fftw.h"
/* Generated by: /homee/stevenj/cvs/fftw/gensrc/genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -hc2hc-forward 16 */
/*
* This function contains 298 FP additions, 130 FP multiplications,
* (or, 244 additions, 76 multiplications, 54 fused multiply/add),
* 51 stack variables, and 128 memory accesses
*/
static const fftw_real K277785116 =
FFTW_KONST(+0.277785116509801112371415406974266437187468595);
static const fftw_real K415734806 =
FFTW_KONST(+0.415734806151272618539394188808952878369280406);
static const fftw_real K490392640 =
FFTW_KONST(+0.490392640201615224563091118067119518486966865);
static const fftw_real K097545161 =
FFTW_KONST(+0.097545161008064133924142434238511120463845809);
static const fftw_real K1_414213562 =
FFTW_KONST(+1.414213562373095048801688724209698078569671875);
static const fftw_real K2_000000000 =
FFTW_KONST(+2.000000000000000000000000000000000000000000000);
static const fftw_real K707106781 =
FFTW_KONST(+0.707106781186547524400844362104849039284835938);
static const fftw_real K923879532 =
FFTW_KONST(+0.923879532511286756128183189396788286822416626);
static const fftw_real K382683432 =
FFTW_KONST(+0.382683432365089771728459984030398866761344562);
/*
* Generator Id's :
* $Id: exprdag.ml,v 1.43 2003/03/16 23:43:46 stevenj Exp $
* $Id: fft.ml,v 1.44 2003/03/16 23:43:46 stevenj Exp $
* $Id: to_c.ml,v 1.26 2003/03/16 23:43:46 stevenj Exp $
*/
void fftw_hc2hc_forward_16(fftw_real *A, const fftw_complex *W,
int iostride, int m, int dist)
{
int i;
fftw_real *X;
fftw_real *Y;
X = A;
Y = A + (16 * iostride);
{
fftw_real tmp277;
fftw_real tmp280;
fftw_real tmp281;
fftw_real tmp309;
fftw_real tmp292;
fftw_real tmp307;
fftw_real tmp314;
fftw_real tmp322;
fftw_real tmp330;
fftw_real tmp284;
fftw_real tmp287;
fftw_real tmp288;
fftw_real tmp310;
fftw_real tmp291;
fftw_real tmp300;
fftw_real tmp315;
fftw_real tmp325;
fftw_real tmp331;
fftw_real tmp290;
fftw_real tmp289;
fftw_real tmp317;
fftw_real tmp318;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp275;
fftw_real tmp276;
fftw_real tmp278;
fftw_real tmp279;
ASSERT_ALIGNED_DOUBLE;
tmp275 = X[0];
tmp276 = X[8 * iostride];
tmp277 = tmp275 + tmp276;
tmp278 = X[4 * iostride];
tmp279 = X[12 * iostride];
tmp280 = tmp278 + tmp279;
tmp281 = tmp277 + tmp280;
tmp309 = tmp275 - tmp276;
tmp292 = tmp278 - tmp279;
}
{
fftw_real tmp303;
fftw_real tmp320;
fftw_real tmp306;
fftw_real tmp321;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp301;
fftw_real tmp302;
fftw_real tmp304;
fftw_real tmp305;
ASSERT_ALIGNED_DOUBLE;
tmp301 = X[iostride];
tmp302 = X[9 * iostride];
tmp303 = tmp301 - tmp302;
tmp320 = tmp301 + tmp302;
tmp304 = X[5 * iostride];
tmp305 = X[13 * iostride];
tmp306 = tmp304 - tmp305;
tmp321 = tmp304 + tmp305;
}
tmp307 = (K382683432 * tmp303) + (K923879532 * tmp306);
tmp314 = (K923879532 * tmp303) - (K382683432 * tmp306);
tmp322 = tmp320 - tmp321;
tmp330 = tmp320 + tmp321;
}
{
fftw_real tmp282;
fftw_real tmp283;
fftw_real tmp285;
fftw_real tmp286;
ASSERT_ALIGNED_DOUBLE;
tmp282 = X[2 * iostride];
tmp283 = X[10 * iostride];
tmp284 = tmp282 + tmp283;
tmp290 = tmp282 - tmp283;
tmp285 = X[14 * iostride];
tmp286 = X[6 * iostride];
tmp287 = tmp285 + tmp286;
tmp289 = tmp285 - tmp286;
}
tmp288 = tmp284 + tmp287;
tmp310 = K707106781 * (tmp290 + tmp289);
tmp291 = K707106781 * (tmp289 - tmp290);
{
fftw_real tmp296;
fftw_real tmp323;
fftw_real tmp299;
fftw_real tmp324;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp294;
fftw_real tmp295;
fftw_real tmp297;
fftw_real tmp298;
ASSERT_ALIGNED_DOUBLE;
tmp294 = X[15 * iostride];
tmp295 = X[7 * iostride];
tmp296 = tmp294 - tmp295;
tmp323 = tmp294 + tmp295;
tmp297 = X[3 * iostride];
tmp298 = X[11 * iostride];
tmp299 = tmp297 - tmp298;
tmp324 = tmp297 + tmp298;
}
tmp300 = (K382683432 * tmp296) - (K923879532 * tmp299);
tmp315 = (K923879532 * tmp296) + (K382683432 * tmp299);
tmp325 = tmp323 - tmp324;
tmp331 = tmp323 + tmp324;
}
{
fftw_real tmp329;
fftw_real tmp332;
fftw_real tmp327;
fftw_real tmp328;
ASSERT_ALIGNED_DOUBLE;
X[4 * iostride] = tmp281 - tmp288;
tmp329 = tmp281 + tmp288;
tmp332 = tmp330 + tmp331;
X[8 * iostride] = tmp329 - tmp332;
X[0] = tmp329 + tmp332;
Y[-4 * iostride] = tmp331 - tmp330;
tmp327 = tmp287 - tmp284;
tmp328 = K707106781 * (tmp325 - tmp322);
Y[-2 * iostride] = tmp327 + tmp328;
Y[-6 * iostride] = tmp328 - tmp327;
}
{
fftw_real tmp319;
fftw_real tmp326;
fftw_real tmp313;
fftw_real tmp316;
ASSERT_ALIGNED_DOUBLE;
tmp319 = tmp277 - tmp280;
tmp326 = K707106781 * (tmp322 + tmp325);
X[6 * iostride] = tmp319 - tmp326;
X[2 * iostride] = tmp319 + tmp326;
tmp313 = tmp309 + tmp310;
tmp316 = tmp314 + tmp315;
X[7 * iostride] = tmp313 - tmp316;
X[iostride] = tmp313 + tmp316;
}
tmp317 = tmp292 + tmp291;
tmp318 = tmp315 - tmp314;
Y[-3 * iostride] = tmp317 + tmp318;
Y[-5 * iostride] = tmp318 - tmp317;
{
fftw_real tmp293;
fftw_real tmp308;
fftw_real tmp311;
fftw_real tmp312;
ASSERT_ALIGNED_DOUBLE;
tmp293 = tmp291 - tmp292;
tmp308 = tmp300 - tmp307;
Y[-iostride] = tmp293 + tmp308;
Y[-7 * iostride] = tmp308 - tmp293;
tmp311 = tmp309 - tmp310;
tmp312 = tmp307 + tmp300;
X[5 * iostride] = tmp311 - tmp312;
X[3 * iostride] = tmp311 + tmp312;
}
}
X = X + dist;
Y = Y - dist;
for (i = 2; i < m; i = i + 2, X = X + dist, Y = Y - dist, W = W + 15) {
fftw_real tmp77;
fftw_real tmp161;
fftw_real tmp249;
fftw_real tmp262;
fftw_real tmp88;
fftw_real tmp263;
fftw_real tmp164;
fftw_real tmp246;
fftw_real tmp147;
fftw_real tmp158;
fftw_real tmp231;
fftw_real tmp198;
fftw_real tmp214;
fftw_real tmp232;
fftw_real tmp233;
fftw_real tmp234;
fftw_real tmp193;
fftw_real tmp213;
fftw_real tmp100;
fftw_real tmp222;
fftw_real tmp170;
fftw_real tmp206;
fftw_real tmp111;
fftw_real tmp223;
fftw_real tmp175;
fftw_real tmp207;
fftw_real tmp124;
fftw_real tmp135;
fftw_real tmp226;
fftw_real tmp187;
fftw_real tmp211;
fftw_real tmp227;
fftw_real tmp228;
fftw_real tmp229;
fftw_real tmp182;
fftw_real tmp210;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp71;
fftw_real tmp248;
fftw_real tmp76;
fftw_real tmp247;
ASSERT_ALIGNED_DOUBLE;
tmp71 = X[0];
tmp248 = Y[-15 * iostride];
{
fftw_real tmp73;
fftw_real tmp75;
fftw_real tmp72;
fftw_real tmp74;
ASSERT_ALIGNED_DOUBLE;
tmp73 = X[8 * iostride];
tmp75 = Y[-7 * iostride];
tmp72 = c_re(W[7]);
tmp74 = c_im(W[7]);
tmp76 = (tmp72 * tmp73) - (tmp74 * tmp75);
tmp247 = (tmp74 * tmp73) + (tmp72 * tmp75);
}
tmp77 = tmp71 + tmp76;
tmp161 = tmp71 - tmp76;
tmp249 = tmp247 + tmp248;
tmp262 = tmp248 - tmp247;
}
{
fftw_real tmp82;
fftw_real tmp162;
fftw_real tmp87;
fftw_real tmp163;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp79;
fftw_real tmp81;
fftw_real tmp78;
fftw_real tmp80;
ASSERT_ALIGNED_DOUBLE;
tmp79 = X[4 * iostride];
tmp81 = Y[-11 * iostride];
tmp78 = c_re(W[3]);
tmp80 = c_im(W[3]);
tmp82 = (tmp78 * tmp79) - (tmp80 * tmp81);
tmp162 = (tmp80 * tmp79) + (tmp78 * tmp81);
}
{
fftw_real tmp84;
fftw_real tmp86;
fftw_real tmp83;
fftw_real tmp85;
ASSERT_ALIGNED_DOUBLE;
tmp84 = X[12 * iostride];
tmp86 = Y[-3 * iostride];
tmp83 = c_re(W[11]);
tmp85 = c_im(W[11]);
tmp87 = (tmp83 * tmp84) - (tmp85 * tmp86);
tmp163 = (tmp85 * tmp84) + (tmp83 * tmp86);
}
tmp88 = tmp82 + tmp87;
tmp263 = tmp82 - tmp87;
tmp164 = tmp162 - tmp163;
tmp246 = tmp162 + tmp163;
}
{
fftw_real tmp141;
fftw_real tmp194;
fftw_real tmp157;
fftw_real tmp191;
fftw_real tmp146;
fftw_real tmp195;
fftw_real tmp152;
fftw_real tmp190;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp138;
fftw_real tmp140;
fftw_real tmp137;
fftw_real tmp139;
ASSERT_ALIGNED_DOUBLE;
tmp138 = X[15 * iostride];
tmp140 = Y[0];
tmp137 = c_re(W[14]);
tmp139 = c_im(W[14]);
tmp141 = (tmp137 * tmp138) - (tmp139 * tmp140);
tmp194 = (tmp139 * tmp138) + (tmp137 * tmp140);
}
{
fftw_real tmp154;
fftw_real tmp156;
fftw_real tmp153;
fftw_real tmp155;
ASSERT_ALIGNED_DOUBLE;
tmp154 = X[11 * iostride];
tmp156 = Y[-4 * iostride];
tmp153 = c_re(W[10]);
tmp155 = c_im(W[10]);
tmp157 = (tmp153 * tmp154) - (tmp155 * tmp156);
tmp191 = (tmp155 * tmp154) + (tmp153 * tmp156);
}
{
fftw_real tmp143;
fftw_real tmp145;
fftw_real tmp142;
fftw_real tmp144;
ASSERT_ALIGNED_DOUBLE;
tmp143 = X[7 * iostride];
tmp145 = Y[-8 * iostride];
tmp142 = c_re(W[6]);
tmp144 = c_im(W[6]);
tmp146 = (tmp142 * tmp143) - (tmp144 * tmp145);
tmp195 = (tmp144 * tmp143) + (tmp142 * tmp145);
}
{
fftw_real tmp149;
fftw_real tmp151;
fftw_real tmp148;
fftw_real tmp150;
ASSERT_ALIGNED_DOUBLE;
tmp149 = X[3 * iostride];
tmp151 = Y[-12 * iostride];
tmp148 = c_re(W[2]);
tmp150 = c_im(W[2]);
tmp152 = (tmp148 * tmp149) - (tmp150 * tmp151);
tmp190 = (tmp150 * tmp149) + (tmp148 * tmp151);
}
{
fftw_real tmp196;
fftw_real tmp197;
fftw_real tmp189;
fftw_real tmp192;
ASSERT_ALIGNED_DOUBLE;
tmp147 = tmp141 + tmp146;
tmp158 = tmp152 + tmp157;
tmp231 = tmp147 - tmp158;
tmp196 = tmp194 - tmp195;
tmp197 = tmp152 - tmp157;
tmp198 = tmp196 + tmp197;
tmp214 = tmp196 - tmp197;
tmp232 = tmp194 + tmp195;
tmp233 = tmp190 + tmp191;
tmp234 = tmp232 - tmp233;
tmp189 = tmp141 - tmp146;
tmp192 = tmp190 - tmp191;
tmp193 = tmp189 - tmp192;
tmp213 = tmp189 + tmp192;
}
}
{
fftw_real tmp94;
fftw_real tmp166;
fftw_real tmp99;
fftw_real tmp167;
fftw_real tmp168;
fftw_real tmp169;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp91;
fftw_real tmp93;
fftw_real tmp90;
fftw_real tmp92;
ASSERT_ALIGNED_DOUBLE;
tmp91 = X[2 * iostride];
tmp93 = Y[-13 * iostride];
tmp90 = c_re(W[1]);
tmp92 = c_im(W[1]);
tmp94 = (tmp90 * tmp91) - (tmp92 * tmp93);
tmp166 = (tmp92 * tmp91) + (tmp90 * tmp93);
}
{
fftw_real tmp96;
fftw_real tmp98;
fftw_real tmp95;
fftw_real tmp97;
ASSERT_ALIGNED_DOUBLE;
tmp96 = X[10 * iostride];
tmp98 = Y[-5 * iostride];
tmp95 = c_re(W[9]);
tmp97 = c_im(W[9]);
tmp99 = (tmp95 * tmp96) - (tmp97 * tmp98);
tmp167 = (tmp97 * tmp96) + (tmp95 * tmp98);
}
tmp100 = tmp94 + tmp99;
tmp222 = tmp166 + tmp167;
tmp168 = tmp166 - tmp167;
tmp169 = tmp94 - tmp99;
tmp170 = tmp168 - tmp169;
tmp206 = tmp169 + tmp168;
}
{
fftw_real tmp105;
fftw_real tmp172;
fftw_real tmp110;
fftw_real tmp173;
fftw_real tmp171;
fftw_real tmp174;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp102;
fftw_real tmp104;
fftw_real tmp101;
fftw_real tmp103;
ASSERT_ALIGNED_DOUBLE;
tmp102 = X[14 * iostride];
tmp104 = Y[-iostride];
tmp101 = c_re(W[13]);
tmp103 = c_im(W[13]);
tmp105 = (tmp101 * tmp102) - (tmp103 * tmp104);
tmp172 = (tmp103 * tmp102) + (tmp101 * tmp104);
}
{
fftw_real tmp107;
fftw_real tmp109;
fftw_real tmp106;
fftw_real tmp108;
ASSERT_ALIGNED_DOUBLE;
tmp107 = X[6 * iostride];
tmp109 = Y[-9 * iostride];
tmp106 = c_re(W[5]);
tmp108 = c_im(W[5]);
tmp110 = (tmp106 * tmp107) - (tmp108 * tmp109);
tmp173 = (tmp108 * tmp107) + (tmp106 * tmp109);
}
tmp111 = tmp105 + tmp110;
tmp223 = tmp172 + tmp173;
tmp171 = tmp105 - tmp110;
tmp174 = tmp172 - tmp173;
tmp175 = tmp171 + tmp174;
tmp207 = tmp171 - tmp174;
}
{
fftw_real tmp118;
fftw_real tmp178;
fftw_real tmp134;
fftw_real tmp185;
fftw_real tmp123;
fftw_real tmp179;
fftw_real tmp129;
fftw_real tmp184;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp115;
fftw_real tmp117;
fftw_real tmp114;
fftw_real tmp116;
ASSERT_ALIGNED_DOUBLE;
tmp115 = X[iostride];
tmp117 = Y[-14 * iostride];
tmp114 = c_re(W[0]);
tmp116 = c_im(W[0]);
tmp118 = (tmp114 * tmp115) - (tmp116 * tmp117);
tmp178 = (tmp116 * tmp115) + (tmp114 * tmp117);
}
{
fftw_real tmp131;
fftw_real tmp133;
fftw_real tmp130;
fftw_real tmp132;
ASSERT_ALIGNED_DOUBLE;
tmp131 = X[13 * iostride];
tmp133 = Y[-2 * iostride];
tmp130 = c_re(W[12]);
tmp132 = c_im(W[12]);
tmp134 = (tmp130 * tmp131) - (tmp132 * tmp133);
tmp185 = (tmp132 * tmp131) + (tmp130 * tmp133);
}
{
fftw_real tmp120;
fftw_real tmp122;
fftw_real tmp119;
fftw_real tmp121;
ASSERT_ALIGNED_DOUBLE;
tmp120 = X[9 * iostride];
tmp122 = Y[-6 * iostride];
tmp119 = c_re(W[8]);
tmp121 = c_im(W[8]);
tmp123 = (tmp119 * tmp120) - (tmp121 * tmp122);
tmp179 = (tmp121 * tmp120) + (tmp119 * tmp122);
}
{
fftw_real tmp126;
fftw_real tmp128;
fftw_real tmp125;
fftw_real tmp127;
ASSERT_ALIGNED_DOUBLE;
tmp126 = X[5 * iostride];
tmp128 = Y[-10 * iostride];
tmp125 = c_re(W[4]);
tmp127 = c_im(W[4]);
tmp129 = (tmp125 * tmp126) - (tmp127 * tmp128);
tmp184 = (tmp127 * tmp126) + (tmp125 * tmp128);
}
{
fftw_real tmp183;
fftw_real tmp186;
fftw_real tmp180;
fftw_real tmp181;
ASSERT_ALIGNED_DOUBLE;
tmp124 = tmp118 + tmp123;
tmp135 = tmp129 + tmp134;
tmp226 = tmp124 - tmp135;
tmp183 = tmp118 - tmp123;
tmp186 = tmp184 - tmp185;
tmp187 = tmp183 - tmp186;
tmp211 = tmp183 + tmp186;
tmp227 = tmp178 + tmp179;
tmp228 = tmp184 + tmp185;
tmp229 = tmp227 - tmp228;
tmp180 = tmp178 - tmp179;
tmp181 = tmp129 - tmp134;
tmp182 = tmp180 + tmp181;
tmp210 = tmp180 - tmp181;
}
}
{
fftw_real tmp177;
fftw_real tmp201;
fftw_real tmp271;
fftw_real tmp273;
fftw_real tmp200;
fftw_real tmp274;
fftw_real tmp204;
fftw_real tmp272;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp165;
fftw_real tmp176;
fftw_real tmp269;
fftw_real tmp270;
ASSERT_ALIGNED_DOUBLE;
tmp165 = tmp161 - tmp164;
tmp176 = K707106781 * (tmp170 - tmp175);
tmp177 = tmp165 + tmp176;
tmp201 = tmp165 - tmp176;
tmp269 = K707106781 * (tmp207 - tmp206);
tmp270 = tmp263 + tmp262;
tmp271 = tmp269 + tmp270;
tmp273 = tmp270 - tmp269;
}
{
fftw_real tmp188;
fftw_real tmp199;
fftw_real tmp202;
fftw_real tmp203;
ASSERT_ALIGNED_DOUBLE;
tmp188 = (K923879532 * tmp182) + (K382683432 * tmp187);
tmp199 = (K382683432 * tmp193) - (K923879532 * tmp198);
tmp200 = tmp188 + tmp199;
tmp274 = tmp199 - tmp188;
tmp202 = (K382683432 * tmp182) - (K923879532 * tmp187);
tmp203 = (K382683432 * tmp198) + (K923879532 * tmp193);
tmp204 = tmp202 - tmp203;
tmp272 = tmp202 + tmp203;
}
Y[-11 * iostride] = tmp177 - tmp200;
X[3 * iostride] = tmp177 + tmp200;
Y[-15 * iostride] = tmp201 - tmp204;
X[7 * iostride] = tmp201 + tmp204;
X[11 * iostride] = -(tmp271 - tmp272);
Y[-3 * iostride] = tmp272 + tmp271;
X[15 * iostride] = -(tmp273 - tmp274);
Y[-7 * iostride] = tmp274 + tmp273;
}
{
fftw_real tmp209;
fftw_real tmp217;
fftw_real tmp265;
fftw_real tmp267;
fftw_real tmp216;
fftw_real tmp268;
fftw_real tmp220;
fftw_real tmp266;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp205;
fftw_real tmp208;
fftw_real tmp261;
fftw_real tmp264;
ASSERT_ALIGNED_DOUBLE;
tmp205 = tmp161 + tmp164;
tmp208 = K707106781 * (tmp206 + tmp207);
tmp209 = tmp205 + tmp208;
tmp217 = tmp205 - tmp208;
tmp261 = K707106781 * (tmp170 + tmp175);
tmp264 = tmp262 - tmp263;
tmp265 = tmp261 + tmp264;
tmp267 = tmp264 - tmp261;
}
{
fftw_real tmp212;
fftw_real tmp215;
fftw_real tmp218;
fftw_real tmp219;
ASSERT_ALIGNED_DOUBLE;
tmp212 = (K382683432 * tmp210) + (K923879532 * tmp211);
tmp215 = (K923879532 * tmp213) - (K382683432 * tmp214);
tmp216 = tmp212 + tmp215;
tmp268 = tmp215 - tmp212;
tmp218 = (K923879532 * tmp210) - (K382683432 * tmp211);
tmp219 = (K923879532 * tmp214) + (K382683432 * tmp213);
tmp220 = tmp218 - tmp219;
tmp266 = tmp218 + tmp219;
}
Y[-9 * iostride] = tmp209 - tmp216;
X[iostride] = tmp209 + tmp216;
Y[-13 * iostride] = tmp217 - tmp220;
X[5 * iostride] = tmp217 + tmp220;
X[9 * iostride] = -(tmp265 - tmp266);
Y[-iostride] = tmp266 + tmp265;
X[13 * iostride] = -(tmp267 - tmp268);
Y[-5 * iostride] = tmp268 + tmp267;
}
{
fftw_real tmp225;
fftw_real tmp237;
fftw_real tmp257;
fftw_real tmp259;
fftw_real tmp236;
fftw_real tmp260;
fftw_real tmp240;
fftw_real tmp258;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp221;
fftw_real tmp224;
fftw_real tmp255;
fftw_real tmp256;
ASSERT_ALIGNED_DOUBLE;
tmp221 = tmp77 - tmp88;
tmp224 = tmp222 - tmp223;
tmp225 = tmp221 + tmp224;
tmp237 = tmp221 - tmp224;
tmp255 = tmp111 - tmp100;
tmp256 = tmp249 - tmp246;
tmp257 = tmp255 + tmp256;
tmp259 = tmp256 - tmp255;
}
{
fftw_real tmp230;
fftw_real tmp235;
fftw_real tmp238;
fftw_real tmp239;
ASSERT_ALIGNED_DOUBLE;
tmp230 = tmp226 + tmp229;
tmp235 = tmp231 - tmp234;
tmp236 = K707106781 * (tmp230 + tmp235);
tmp260 = K707106781 * (tmp235 - tmp230);
tmp238 = tmp229 - tmp226;
tmp239 = tmp231 + tmp234;
tmp240 = K707106781 * (tmp238 - tmp239);
tmp258 = K707106781 * (tmp238 + tmp239);
}
Y[-10 * iostride] = tmp225 - tmp236;
X[2 * iostride] = tmp225 + tmp236;
Y[-14 * iostride] = tmp237 - tmp240;
X[6 * iostride] = tmp237 + tmp240;
X[10 * iostride] = -(tmp257 - tmp258);
Y[-2 * iostride] = tmp258 + tmp257;
X[14 * iostride] = -(tmp259 - tmp260);
Y[-6 * iostride] = tmp260 + tmp259;
}
{
fftw_real tmp113;
fftw_real tmp241;
fftw_real tmp251;
fftw_real tmp253;
fftw_real tmp160;
fftw_real tmp254;
fftw_real tmp244;
fftw_real tmp252;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp89;
fftw_real tmp112;
fftw_real tmp245;
fftw_real tmp250;
ASSERT_ALIGNED_DOUBLE;
tmp89 = tmp77 + tmp88;
tmp112 = tmp100 + tmp111;
tmp113 = tmp89 + tmp112;
tmp241 = tmp89 - tmp112;
tmp245 = tmp222 + tmp223;
tmp250 = tmp246 + tmp249;
tmp251 = tmp245 + tmp250;
tmp253 = tmp250 - tmp245;
}
{
fftw_real tmp136;
fftw_real tmp159;
fftw_real tmp242;
fftw_real tmp243;
ASSERT_ALIGNED_DOUBLE;
tmp136 = tmp124 + tmp135;
tmp159 = tmp147 + tmp158;
tmp160 = tmp136 + tmp159;
tmp254 = tmp159 - tmp136;
tmp242 = tmp227 + tmp228;
tmp243 = tmp232 + tmp233;
tmp244 = tmp242 - tmp243;
tmp252 = tmp242 + tmp243;
}
Y[-8 * iostride] = tmp113 - tmp160;
X[0] = tmp113 + tmp160;
Y[-12 * iostride] = tmp241 - tmp244;
X[4 * iostride] = tmp241 + tmp244;
X[8 * iostride] = -(tmp251 - tmp252);
Y[0] = tmp252 + tmp251;
X[12 * iostride] = -(tmp253 - tmp254);
Y[-4 * iostride] = tmp254 + tmp253;
}
}
if (i == m) {
fftw_real tmp5;
fftw_real tmp41;
fftw_real tmp61;
fftw_real tmp67;
fftw_real tmp30;
fftw_real tmp49;
fftw_real tmp34;
fftw_real tmp50;
fftw_real tmp12;
fftw_real tmp66;
fftw_real tmp44;
fftw_real tmp58;
fftw_real tmp19;
fftw_real tmp46;
fftw_real tmp23;
fftw_real tmp47;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp1;
fftw_real tmp60;
fftw_real tmp4;
fftw_real tmp59;
fftw_real tmp2;
fftw_real tmp3;
ASSERT_ALIGNED_DOUBLE;
tmp1 = X[0];
tmp60 = X[8 * iostride];
tmp2 = X[4 * iostride];
tmp3 = X[12 * iostride];
tmp4 = K707106781 * (tmp2 - tmp3);
tmp59 = K707106781 * (tmp2 + tmp3);
tmp5 = tmp1 + tmp4;
tmp41 = tmp1 - tmp4;
tmp61 = tmp59 + tmp60;
tmp67 = tmp60 - tmp59;
}
{
fftw_real tmp29;
fftw_real tmp33;
fftw_real tmp27;
fftw_real tmp31;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp28;
fftw_real tmp32;
fftw_real tmp25;
fftw_real tmp26;
ASSERT_ALIGNED_DOUBLE;
tmp28 = X[15 * iostride];
tmp29 = K2_000000000 * tmp28;
tmp32 = X[7 * iostride];
tmp33 = K2_000000000 * tmp32;
tmp25 = X[3 * iostride];
tmp26 = X[11 * iostride];
tmp27 = K1_414213562 * (tmp25 - tmp26);
tmp31 = K1_414213562 * (tmp25 + tmp26);
}
tmp30 = tmp27 - tmp29;
tmp49 = tmp27 + tmp29;
tmp34 = tmp31 + tmp33;
tmp50 = tmp33 - tmp31;
}
{
fftw_real tmp8;
fftw_real tmp42;
fftw_real tmp11;
fftw_real tmp43;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp6;
fftw_real tmp7;
fftw_real tmp9;
fftw_real tmp10;
ASSERT_ALIGNED_DOUBLE;
tmp6 = X[2 * iostride];
tmp7 = X[10 * iostride];
tmp8 = (K923879532 * tmp6) - (K382683432 * tmp7);
tmp42 = (K382683432 * tmp6) + (K923879532 * tmp7);
tmp9 = X[6 * iostride];
tmp10 = X[14 * iostride];
tmp11 = (K382683432 * tmp9) - (K923879532 * tmp10);
tmp43 = (K923879532 * tmp9) + (K382683432 * tmp10);
}
tmp12 = tmp8 + tmp11;
tmp66 = tmp11 - tmp8;
tmp44 = tmp42 - tmp43;
tmp58 = tmp42 + tmp43;
}
{
fftw_real tmp15;
fftw_real tmp22;
fftw_real tmp18;
fftw_real tmp20;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp14;
fftw_real tmp21;
fftw_real tmp16;
fftw_real tmp17;
ASSERT_ALIGNED_DOUBLE;
tmp14 = X[iostride];
tmp15 = K2_000000000 * tmp14;
tmp21 = X[9 * iostride];
tmp22 = K2_000000000 * tmp21;
tmp16 = X[5 * iostride];
tmp17 = X[13 * iostride];
tmp18 = K1_414213562 * (tmp16 - tmp17);
tmp20 = K1_414213562 * (tmp16 + tmp17);
}
tmp19 = tmp15 + tmp18;
tmp46 = tmp15 - tmp18;
tmp23 = tmp20 + tmp22;
tmp47 = tmp22 - tmp20;
}
{
fftw_real tmp13;
fftw_real tmp62;
fftw_real tmp36;
fftw_real tmp57;
fftw_real tmp24;
fftw_real tmp35;
ASSERT_ALIGNED_DOUBLE;
tmp13 = tmp5 - tmp12;
tmp62 = tmp58 + tmp61;
tmp24 = (K097545161 * tmp19) + (K490392640 * tmp23);
tmp35 = (K097545161 * tmp30) - (K490392640 * tmp34);
tmp36 = tmp24 + tmp35;
tmp57 = tmp35 - tmp24;
X[4 * iostride] = tmp13 - tmp36;
X[3 * iostride] = tmp13 + tmp36;
Y[0] = tmp57 - tmp62;
Y[-7 * iostride] = tmp57 + tmp62;
}
{
fftw_real tmp37;
fftw_real tmp64;
fftw_real tmp40;
fftw_real tmp63;
fftw_real tmp38;
fftw_real tmp39;
ASSERT_ALIGNED_DOUBLE;
tmp37 = tmp5 + tmp12;
tmp64 = tmp61 - tmp58;
tmp38 = (K490392640 * tmp19) - (K097545161 * tmp23);
tmp39 = (K490392640 * tmp30) + (K097545161 * tmp34);
tmp40 = tmp38 + tmp39;
tmp63 = tmp39 - tmp38;
X[7 * iostride] = tmp37 - tmp40;
X[0] = tmp37 + tmp40;
Y[-4 * iostride] = tmp63 - tmp64;
Y[-3 * iostride] = tmp63 + tmp64;
}
{
fftw_real tmp45;
fftw_real tmp68;
fftw_real tmp52;
fftw_real tmp65;
fftw_real tmp48;
fftw_real tmp51;
ASSERT_ALIGNED_DOUBLE;
tmp45 = tmp41 + tmp44;
tmp68 = tmp66 - tmp67;
tmp48 = (K415734806 * tmp46) + (K277785116 * tmp47);
tmp51 = (K415734806 * tmp49) + (K277785116 * tmp50);
tmp52 = tmp48 - tmp51;
tmp65 = tmp48 + tmp51;
X[6 * iostride] = tmp45 - tmp52;
X[iostride] = tmp45 + tmp52;
Y[-5 * iostride] = -(tmp65 + tmp68);
Y[-2 * iostride] = tmp68 - tmp65;
}
{
fftw_real tmp53;
fftw_real tmp70;
fftw_real tmp56;
fftw_real tmp69;
fftw_real tmp54;
fftw_real tmp55;
ASSERT_ALIGNED_DOUBLE;
tmp53 = tmp41 - tmp44;
tmp70 = tmp66 + tmp67;
tmp54 = (K415734806 * tmp50) - (K277785116 * tmp49);
tmp55 = (K415734806 * tmp47) - (K277785116 * tmp46);
tmp56 = tmp54 - tmp55;
tmp69 = tmp55 + tmp54;
X[5 * iostride] = tmp53 - tmp56;
X[2 * iostride] = tmp53 + tmp56;
Y[-6 * iostride] = tmp69 - tmp70;
Y[-iostride] = tmp69 + tmp70;
}
}
}
static const int twiddle_order[] =
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
fftw_codelet_desc fftw_hc2hc_forward_16_desc = {
"fftw_hc2hc_forward_16",
(void (*)()) fftw_hc2hc_forward_16,
16,
FFTW_FORWARD,
FFTW_HC2HC,
355,
15,
twiddle_order,
};
|
HoerTech-gGmbH/openMHA
|
external_libs/fftw-2.1.5/rfftw/fhf_16.c
|
C
|
agpl-3.0
| 28,281
|
<?php
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*/
namespace Shopware\Bundle\ESIndexingBundle\Property;
use Doctrine\DBAL\Connection;
use Shopware\Bundle\ESIndexingBundle\LastIdQuery;
/**
* Class PropertyQueryFactory
*/
class PropertyQueryFactory
{
/**
* @var Connection
*/
private $connection;
/**
* @param Connection $connection
*/
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
/**
* @return LastIdQuery
*/
public function createQuery()
{
return new LastIdQuery($this->createOptionQuery());
}
/**
* @return \Doctrine\DBAL\Query\QueryBuilder
*/
private function createOptionQuery()
{
$query = $this->connection->createQueryBuilder();
$query->select(['propertyGroups.id', 'propertyGroups.id'])
->from('s_filter_options', 'propertyGroups')
->where('propertyGroups.id > :lastId')
->setParameter(':lastId', 0);
return $query;
}
}
|
wolv-dev/shopware
|
engine/Shopware/Bundle/ESIndexingBundle/Property/PropertyQueryFactory.php
|
PHP
|
agpl-3.0
| 1,937
|
# Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
module AWS
class SimpleDB
# @private
module ConsistentReadOption
# Determines if SimpleDB should be read consistently or not.
#
# Precedence is given to:
#
# * +:consistent_read+ option
# * SimpleDB.consistent_reads block value
# * AWS.config.simple_db_consistent_reads?
#
# @return [Boolean] Returns true if a read should be made consistently
# to SimpleDB.
def consistent_read options
if options.has_key?(:consistent_read)
options[:consistent_read] ? true : false
elsif SimpleDB.send(:in_consistent_reads_block?)
SimpleDB.send(:consistent_reads_state)
else
config.simple_db_consistent_reads?
end
end
end
end
end
|
wrdsb/canvas-lms
|
vendor/bundle/ruby/1.9.1/gems/aws-sdk-1.8.3.1/lib/aws/simple_db/consistent_read_option.rb
|
Ruby
|
agpl-3.0
| 1,355
|
//
// NCPriceManager.h
// Neocom
//
// Created by Артем Шиманский on 03.03.14.
// Copyright (c) 2014 Artem Shimanski. All rights reserved.
//
#import <Foundation/Foundation.h>
#define NCPriceManagerDidUpdateNotification @"NCPriceManagerDidUpdateNotification"
@interface NCPriceManager : NSObject
+ (instancetype) sharedManager;
- (void) requestPriceWithType:(NSInteger) typeID completionBlock:(void(^)(NSNumber* price)) completionBlock;
- (void) requestPricesWithTypes:(NSArray*) typeIDs completionBlock:(void(^)(NSDictionary* prices)) completionBlock;
- (void) updateIfNeeded;
@end
|
mrdepth/EVEUniverse
|
Legacy/Old/Neocom/NCPriceManager.h
|
C
|
lgpl-2.1
| 605
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- qml-examples.qdoc -->
<title>Qt 4.8: Models and Views: Inline HTML WebView Example</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<script src="scripts/jquery.js" type="text/javascript"></script>
<script src="scripts/functions.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style/superfish.css" />
<link rel="stylesheet" type="text/css" href="style/narrow.css" />
<!--[if IE]>
<meta name="MSSmartTagsPreventParsing" content="true">
<meta http-equiv="imagetoolbar" content="no">
<![endif]-->
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie6.css">
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie7.css">
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="style/style_ie8.css">
<![endif]-->
<script src="scripts/superfish.js" type="text/javascript"></script>
<script src="scripts/narrow.js" type="text/javascript"></script>
</head>
<body class="" onload="CheckEmptyAndLoadList();">
<div class="header" id="qtdocheader">
<div class="content">
<div id="nav-logo">
<a href="index.html">Home</a></div>
<a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a>
<div id="narrowsearch"></div>
<div id="nav-topright">
<ul>
<li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li>
<li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li>
<li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/">
DOC</a></li>
<li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li>
</ul>
</div>
<div id="shortCut">
<ul>
<li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li>
<li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li>
</ul>
</div>
<ul class="sf-menu" id="narrowmenu">
<li><a href="#">API Lookup</a>
<ul>
<li><a href="classes.html">Class index</a></li>
<li><a href="functions.html">Function index</a></li>
<li><a href="modules.html">Modules</a></li>
<li><a href="namespaces.html">Namespaces</a></li>
<li><a href="qtglobal.html">Global Declarations</a></li>
<li><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</li>
<li><a href="#">Qt Topics</a>
<ul>
<li><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li><a href="supported-platforms.html">Supported Platforms</a></li>
<li><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</li>
<li><a href="#">Examples</a>
<ul>
<li><a href="all-examples.html">Examples</a></li>
<li><a href="tutorials.html">Tutorials</a></li>
<li><a href="demos.html">Demos</a></li>
<li><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="wrapper">
<div class="hd">
<span></span>
</div>
<div class="bd group">
<div class="sidebar">
<div class="searchlabel">
Search index:</div>
<div class="search" id="sidebarsearch">
<form id="qtdocsearch" action="" onsubmit="return false;">
<fieldset>
<input type="text" name="searchstring" id="pageType" value="" />
<div id="resultdialog">
<a href="#" id="resultclose">Close</a>
<p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p>
<p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span> results:</p>
<ul id="resultlist" class="all">
</ul>
</div>
</fieldset>
</form>
</div>
<div class="box first bottombar" id="lookup">
<h2 title="API Lookup"><span></span>
API Lookup</h2>
<div id="list001" class="list">
<ul id="ul001" >
<li class="defaultLink"><a href="classes.html">Class index</a></li>
<li class="defaultLink"><a href="functions.html">Function index</a></li>
<li class="defaultLink"><a href="modules.html">Modules</a></li>
<li class="defaultLink"><a href="namespaces.html">Namespaces</a></li>
<li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li>
<li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</div>
</div>
<div class="box bottombar" id="topics">
<h2 title="Qt Topics"><span></span>
Qt Topics</h2>
<div id="list002" class="list">
<ul id="ul002" >
<li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li class="defaultLink"><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li>
<li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</div>
</div>
<div class="box" id="examples">
<h2 title="Examples"><span></span>
Examples</h2>
<div id="list003" class="list">
<ul id="ul003">
<li class="defaultLink"><a href="all-examples.html">Examples</a></li>
<li class="defaultLink"><a href="tutorials.html">Tutorials</a></li>
<li class="defaultLink"><a href="demos.html">Demos</a></li>
<li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</div>
</div>
</div>
<div class="wrap">
<div class="toolbar">
<div class="breadcrumb toolblock">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<!-- Breadcrumbs go here -->
<li><a href="all-examples.html">Examples</a></li>
<li>QML Examples & Demos</li>
<li>Models and Views: Inline HTML WebView Example</li>
</ul>
</div>
<div class="toolbuttons toolblock">
<ul>
<li id="smallA" class="t_button">A</li>
<li id="medA" class="t_button active">A</li>
<li id="bigA" class="t_button">A</li>
<li id="print" class="t_button"><a href="javascript:this.print();">
<span>Print</span></a></li>
</ul>
</div>
</div>
<div class="content mainContent">
<h1 class="title">Models and Views: Inline HTML WebView Example</h1>
<span class="subtitle"></span>
<!-- $$$declarative/modelviews/webview/inlinehtml-description -->
<div class="descr"> <a name="details"></a>
<p>Files:</p>
<ul>
<li><a href="declarative-modelviews-webview-inlinehtml-inlinehtml-svg.html">declarative/modelviews/webview/inlinehtml/inlinehtml.svg</a></li>
<li><a href="declarative-modelviews-webview-inlinehtml-qml-inlinehtml-inlinehtml-qml.html">declarative/modelviews/webview/inlinehtml/qml/inlinehtml/inlinehtml.qml</a></li>
<li><a href="declarative-modelviews-webview-inlinehtml-main-cpp.html">declarative/modelviews/webview/inlinehtml/main.cpp</a></li>
<li><a href="declarative-modelviews-webview-inlinehtml-inlinehtml-pro.html">declarative/modelviews/webview/inlinehtml/inlinehtml.pro</a></li>
<li><a href="declarative-modelviews-webview-inlinehtml-inlinehtml-qmlproject.html">declarative/modelviews/webview/inlinehtml/inlinehtml.qmlproject</a></li>
</ul>
<p>This example shows how to use inline HTML with the <a href="qml-webview.html">WebView</a> element.<table class="generic">
<tr valign="top" class="odd"><td ><p class="centerAlign"><img src="images/qml-webview-inlinehtml-example.png" alt="" /></p></td></tr>
<tr valign="top" class="even"><td >inlinehtml.qml</td></tr>
</table>
</div>
<!-- @@@declarative/modelviews/webview/inlinehtml -->
</div>
</div>
</div>
<div class="ft">
<span></span>
</div>
</div>
<div class="footer">
<p>
<acronym title="Copyright">©</acronym> 2014 Digia Plc and/or its
subsidiaries. Documentation contributions included herein are the copyrights of
their respective owners.</p>
<br />
<p>
The documentation provided herein is licensed under the terms of the
<a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation
License version 1.3</a> as published by the Free Software Foundation.</p>
<p>
Documentation sources may be obtained from <a href="http://www.qt-project.org">
www.qt-project.org</a>.</p>
<br />
<p>
Digia, Qt and their respective logos are trademarks of Digia Plc
in Finland and/or other countries worldwide. All other trademarks are property
of their respective owners. <a title="Privacy Policy"
href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p>
</div>
<script src="scripts/functions.js" type="text/javascript"></script>
</body>
</html>
|
eric100lin/Qt-4.8.6
|
doc/html/declarative-modelviews-webview-inlinehtml.html
|
HTML
|
lgpl-2.1
| 10,492
|
; Copyright 2000, 2002 Free Software Foundation, Inc.
;
; This file is part of the GNU MP Library.
;
; The GNU MP Library is free software; you can redistribute it and/or
; modify it under the terms of the GNU Lesser General Public License as
; published by the Free Software Foundation; either version 2.1 of the
; License, or (at your option) any later version.
;
; The GNU MP Library is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
; Lesser General Public License for more details.
;
; You should have received a copy of the GNU Lesser General Public
; License along with the GNU MP Library; see the file COPYING.LIB. If
; not, write to the Free Software Foundation, Inc., 59 Temple Place -
; Suite 330, Boston, MA 02111-1307, USA.
;
; Translation of AT&T syntax code by Brian Gladman
%define REG_AAAAAAAAAAAAAAAA mm7
%define REG_3333333333333333 mm6
%define REG_0F0F0F0F0F0F0F0F mm5
%define REG_0000000000000000 mm4
%ifndef PIC
section .data
align 8
Lrodata_AAAAAAAAAAAAAAAA:
dd 0AAAAAAAAh
dd 0AAAAAAAAh
Lrodata_3333333333333333:
dd 033333333h
dd 033333333h
Lrodata_0F0F0F0F0F0F0F0F:
dd 00F0F0F0Fh
dd 00F0F0F0Fh
%endif
%macro ph_fun 3
align 32
global %1%2
%ifdef DLL
export %1%2
%endif
%1%2:
mov ecx,[PARAM_SIZE]
%ifdef PIC
mov eax,0xAAAAAAAA
mov edx,0x33333333
movd mm7,eax
movd mm6,edx
mov eax,0x0F0F0F0F
punpckldq mm7,mm7
punpckldq mm6,mm6
movd mm5,eax
movd mm4,edx
punpckldq mm5,mm5
%else
movq mm7,[Lrodata_AAAAAAAAAAAAAAAA]
movq mm6,[Lrodata_3333333333333333]
movq mm5,[Lrodata_0F0F0F0F0F0F0F0F]
%endif
pxor mm4,mm4
mov eax,[PARAM_SRC]
%if %3 == 1
mov edx,[PARAM_SRC2]
%endif
pxor mm2,mm2
shr ecx,1
jnc %%Ltop
movd mm1,[eax+ecx*8]
%if %3 == 1
movd mm0,[edx+ecx*8]
pxor mm1,mm0
%endif
or ecx,ecx
jmp %%Lloaded
; eax src
; ebx
; ecx counter,qwords,decrementing
; edx [hamdist] src2
;
; mm0 (scratch)
; mm1 (scratch)
; mm2 total (low dword)
; mm3
; mm4 \
; mm5 | special constants
; mm6 |
; mm7 /
align 16
%%Ltop:
movq mm1,[eax+ecx*8-8]
%if %3 == 1
pxor mm1,[edx+ecx*8-8]
%endif
dec ecx
%%Lloaded:
movq mm0,mm1
pand mm1,REG_AAAAAAAAAAAAAAAA
psrlq mm1,1
psubd mm0,mm1 ; bit pairs
movq mm1,mm0
psrlq mm0,2
pand mm0,REG_3333333333333333
pand mm1,REG_3333333333333333
paddd mm0,mm1 ; nibbles
movq mm1,mm0
psrlq mm0,4
pand mm0,REG_0F0F0F0F0F0F0F0F
pand mm1,REG_0F0F0F0F0F0F0F0F
paddd mm0,mm1 ; bytes
psadbw mm0,mm4
paddd mm2,mm0 ; add to total
jnz %%Ltop
movd eax,mm2
emms
ret
%endmacro
section .text
%define PARAM_SIZE esp+frame+8
%define PARAM_SRC esp+frame+4
%define frame 0
; global ___gmpn_popcount
ph_fun ___g,mpn_popcount,0
end
|
ufasoft/foreign
|
mpir/mpn/x86w/p3/p3mmx/popcount.asm
|
Assembly
|
lgpl-2.1
| 3,295
|
//===-- Sparc.h - Top-level interface for Sparc representation --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the entry points for global functions defined in the LLVM
// Sparc back-end.
//
//===----------------------------------------------------------------------===//
#ifndef TARGET_SPARC_H
#define TARGET_SPARC_H
#include "MCTargetDesc/SparcMCTargetDesc.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Target/TargetMachine.h"
namespace llvm {
class FunctionPass;
class SparcTargetMachine;
class formatted_raw_ostream;
FunctionPass *createSparcISelDag(SparcTargetMachine &TM);
FunctionPass *createSparcDelaySlotFillerPass(TargetMachine &TM);
} // end namespace llvm;
namespace llvm {
// Enums corresponding to Sparc condition codes, both icc's and fcc's. These
// values must be kept in sync with the ones in the .td file.
namespace SPCC {
enum CondCodes {
//ICC_A = 8 , // Always
//ICC_N = 0 , // Never
ICC_NE = 9 , // Not Equal
ICC_E = 1 , // Equal
ICC_G = 10 , // Greater
ICC_LE = 2 , // Less or Equal
ICC_GE = 11 , // Greater or Equal
ICC_L = 3 , // Less
ICC_GU = 12 , // Greater Unsigned
ICC_LEU = 4 , // Less or Equal Unsigned
ICC_CC = 13 , // Carry Clear/Great or Equal Unsigned
ICC_CS = 5 , // Carry Set/Less Unsigned
ICC_POS = 14 , // Positive
ICC_NEG = 6 , // Negative
ICC_VC = 15 , // Overflow Clear
ICC_VS = 7 , // Overflow Set
//FCC_A = 8+16, // Always
//FCC_N = 0+16, // Never
FCC_U = 7+16, // Unordered
FCC_G = 6+16, // Greater
FCC_UG = 5+16, // Unordered or Greater
FCC_L = 4+16, // Less
FCC_UL = 3+16, // Unordered or Less
FCC_LG = 2+16, // Less or Greater
FCC_NE = 1+16, // Not Equal
FCC_E = 9+16, // Equal
FCC_UE = 10+16, // Unordered or Equal
FCC_GE = 11+16, // Greater or Equal
FCC_UGE = 12+16, // Unordered or Greater or Equal
FCC_LE = 13+16, // Less or Equal
FCC_ULE = 14+16, // Unordered or Less or Equal
FCC_O = 15+16 // Ordered
};
}
inline static const char *SPARCCondCodeToString(SPCC::CondCodes CC) {
switch (CC) {
case SPCC::ICC_NE: return "ne";
case SPCC::ICC_E: return "e";
case SPCC::ICC_G: return "g";
case SPCC::ICC_LE: return "le";
case SPCC::ICC_GE: return "ge";
case SPCC::ICC_L: return "l";
case SPCC::ICC_GU: return "gu";
case SPCC::ICC_LEU: return "leu";
case SPCC::ICC_CC: return "cc";
case SPCC::ICC_CS: return "cs";
case SPCC::ICC_POS: return "pos";
case SPCC::ICC_NEG: return "neg";
case SPCC::ICC_VC: return "vc";
case SPCC::ICC_VS: return "vs";
case SPCC::FCC_U: return "u";
case SPCC::FCC_G: return "g";
case SPCC::FCC_UG: return "ug";
case SPCC::FCC_L: return "l";
case SPCC::FCC_UL: return "ul";
case SPCC::FCC_LG: return "lg";
case SPCC::FCC_NE: return "ne";
case SPCC::FCC_E: return "e";
case SPCC::FCC_UE: return "ue";
case SPCC::FCC_GE: return "ge";
case SPCC::FCC_UGE: return "uge";
case SPCC::FCC_LE: return "le";
case SPCC::FCC_ULE: return "ule";
case SPCC::FCC_O: return "o";
}
llvm_unreachable("Invalid cond code");
}
} // end namespace llvm
#endif
|
cxx-hep/root-cern
|
interpreter/llvm/src/lib/Target/Sparc/Sparc.h
|
C
|
lgpl-2.1
| 3,687
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>CQRS.NET: Cqrs.Azure.DocumentDb.Factories.IAzureDocumentDbDataStoreConnectionStringFactory.UseSingleCollectionForAllDataStores</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">CQRS.NET
 <span id="projectnumber">2.4</span>
</div>
<div id="projectbrief">A lightweight enterprise Function as a Service (FaaS) framework to write function based serverless and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('interfaceCqrs_1_1Azure_1_1DocumentDb_1_1Factories_1_1IAzureDocumentDbDataStoreConnectionStringFactory_ae500b0191fee202806701e4f856c43dd.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="contents">
<a id="ae500b0191fee202806701e4f856c43dd"></a>
<h2 class="memtitle"><span class="permalink"><a href="#ae500b0191fee202806701e4f856c43dd">◆ </a></span>UseSingleCollectionForAllDataStores()</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">bool Cqrs.Azure.DocumentDb.Factories.IAzureDocumentDbDataStoreConnectionStringFactory.UseSingleCollectionForAllDataStores </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Indicates if a different collection should be used per IEntity/IDataStore<TData> or a single collection used for all instances of IDataStore<TData> and IDataStore<TData>. Setting this to true can become expensive as each IEntity will have it's own collection. Check the relevant SDK/pricing models. </p>
<p>Implemented in <a class="el" href="classCqrs_1_1Azure_1_1DocumentDb_1_1Factories_1_1AzureDocumentDbDataStoreConnectionStringFactory_aa7b4b3eca609a815358af227b0f53909.html#aa7b4b3eca609a815358af227b0f53909">Cqrs.Azure.DocumentDb.Factories.AzureDocumentDbDataStoreConnectionStringFactory</a>, and <a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1DocumentDb_1_1Factories_1_1TestAzureDocumentDbDataStoreConnectionStringFactory_aeac8ecfdbb2d1d7f18105f2e535c51fe.html#aeac8ecfdbb2d1d7f18105f2e535c51fe">Cqrs.Ninject.Azure.DocumentDb.Factories.TestAzureDocumentDbDataStoreConnectionStringFactory</a>.</p>
</div>
</div>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="namespaceCqrs.html">Cqrs</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Azure.html">Azure</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Azure_1_1DocumentDb.html">DocumentDb</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Azure_1_1DocumentDb_1_1Factories.html">Factories</a></li><li class="navelem"><a class="el" href="interfaceCqrs_1_1Azure_1_1DocumentDb_1_1Factories_1_1IAzureDocumentDbDataStoreConnectionStringFactory.html">IAzureDocumentDbDataStoreConnectionStringFactory</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li>
</ul>
</div>
</body>
</html>
|
cdmdotnet/CQRS
|
wiki/docs/2.4/html/interfaceCqrs_1_1Azure_1_1DocumentDb_1_1Factories_1_1IAzureDocumentDbDataStoreConnectionStringFactory_ae500b0191fee202806701e4f856c43dd.html
|
HTML
|
lgpl-2.1
| 6,232
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Mobility Components.
**
** $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 Digia Plc 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 CHATCLIENT_H
#define CHATCLIENT_H
#include <qbluetoothserviceinfo.h>
#include <qbluetoothsocket.h>
#include <QtCore/QObject>
#include <QtCore/QTime>
#include <QtCore/QTimer>
QTM_BEGIN_NAMESPACE
class QBluetoothSocket;
QTM_END_NAMESPACE
class QDataStream;
QTM_USE_NAMESPACE
//! [declaration]
class TennisClient : public QObject
{
Q_OBJECT
public:
explicit TennisClient(QObject *parent = 0);
~TennisClient();
void startClient(const QBluetoothServiceInfo &remoteService);
void stopClient();
public slots:
void moveRightPaddle(int y);
void error(QBluetoothSocket::SocketError);
signals:
void moveBall(int x, int y);
void score(int left, int right);
void moveLeftPaddle(int y);
void connected(const QString &name);
void disconnected();
void lag(int ms);
private slots:
void readSocket();
void connected();
void sendEcho();
void socketDisconnected();
private:
QBluetoothSocket *socket;
QDataStream *stream;
QBluetoothServiceInfo serviceInfo;
QTime *elapsed;
QTimer lagTimer;
int lagTimeout;
};
//! [declaration]
#endif // CHATCLIENT_H
|
qtproject/qt-mobility
|
demos/bttennis/tennisclient.h
|
C
|
lgpl-2.1
| 3,143
|
/*
Copyright (C) 2004, 2005, 2008, 2009 Nikolas Zimmermann <zimmermann@kde.org>
2004, 2005 Rob Buis <buis@kde.org>
This file is part of the KDE project
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef SVGURIReference_h
#define SVGURIReference_h
#if ENABLE(SVG)
#include "SVGElement.h"
#include "XLinkNames.h"
namespace WebCore {
extern char SVGURIReferenceIdentifier[];
class MappedAttribute;
class SVGURIReference {
public:
SVGURIReference();
virtual ~SVGURIReference();
bool parseMappedAttribute(MappedAttribute*);
bool isKnownAttribute(const QualifiedName&);
static String getTarget(const String& url);
protected:
virtual void setHrefBaseValue(SVGAnimatedTypeValue<String>::DecoratedType type) = 0;
};
} // namespace WebCore
#endif // ENABLE(SVG)
#endif // SVGURIReference_h
|
radekp/qt
|
src/3rdparty/webkit/WebCore/svg/SVGURIReference.h
|
C
|
lgpl-2.1
| 1,630
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.exist.external.org.apache.commons.io.output;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
/**
* This class implements an output stream in which the data is
* written into a byte array. The buffer automatically grows as data
* is written to it.
* <p>
* The data can be retrieved using <code>toByteArray()</code> and
* <code>toString()</code>.
* <p>
* Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in
* this class can be called after the stream has been closed without
* generating an <tt>IOException</tt>.
* <p>
* This is an alternative implementation of the java.io.ByteArrayOutputStream
* class. The original implementation only allocates 32 bytes at the beginning.
* As this class is designed for heavy duty it starts at 1024 bytes. In contrast
* to the original it doesn't reallocate the whole memory block but allocates
* additional buffers. This way no buffers need to be garbage collected and
* the contents don't have to be copied to the new buffer. This class is
* designed to behave exactly like the original. The only exception is the
* deprecated toString(int) method that has been ignored.
*
* @author <a href="mailto:jeremias@apache.org">Jeremias Maerki</a>
* @author Holger Hoffstatte
* @version $Id: ByteArrayOutputStream.java 610010 2008-01-08 14:50:59Z niallp $
*/
public class ByteArrayOutputStream extends OutputStream {
/** A singleton empty byte array. */
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
/** The list of buffers, which grows and never reduces. */
private List buffers = new ArrayList();
/** The index of the current buffer. */
private int currentBufferIndex;
/** The total count of bytes in all the filled buffers. */
private int filledBufferSum;
/** The current buffer. */
private byte[] currentBuffer;
/** The total count of bytes written. */
private int count;
/**
* Creates a new byte array output stream. The buffer capacity is
* initially 1024 bytes, though its size increases if necessary.
*/
public ByteArrayOutputStream() {
this(1024);
}
/**
* Creates a new byte array output stream, with a buffer capacity of
* the specified size, in bytes.
*
* @param size the initial size
* @throws IllegalArgumentException if size is negative
*/
public ByteArrayOutputStream(int size) {
if (size < 0) {
throw new IllegalArgumentException(
"Negative initial size: " + size);
}
needNewBuffer(size);
}
/**
* Return the appropriate <code>byte[]</code> buffer
* specified by index.
*
* @param index the index of the buffer required
* @return the buffer
*/
private byte[] getBuffer(int index) {
return (byte[]) buffers.get(index);
}
/**
* Makes a new buffer available either by allocating
* a new one or re-cycling an existing one.
*
* @param newcount the size of the buffer if one is created
*/
private void needNewBuffer(int newcount) {
if (currentBufferIndex < buffers.size() - 1) {
//Recycling old buffer
filledBufferSum += currentBuffer.length;
currentBufferIndex++;
currentBuffer = getBuffer(currentBufferIndex);
} else {
//Creating new buffer
int newBufferSize;
if (currentBuffer == null) {
newBufferSize = newcount;
filledBufferSum = 0;
} else {
newBufferSize = Math.max(
currentBuffer.length << 1,
newcount - filledBufferSum);
filledBufferSum += currentBuffer.length;
}
currentBufferIndex++;
currentBuffer = new byte[newBufferSize];
buffers.add(currentBuffer);
}
}
/**
* Write the bytes to byte array.
* @param b the bytes to write
* @param off The start offset
* @param len The number of bytes to write
*/
public void write(byte[] b, int off, int len) {
if ((off < 0)
|| (off > b.length)
|| (len < 0)
|| ((off + len) > b.length)
|| ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
synchronized (this) {
int newcount = count + len;
int remaining = len;
int inBufferPos = count - filledBufferSum;
while (remaining > 0) {
int part = Math.min(remaining, currentBuffer.length - inBufferPos);
System.arraycopy(b, off + len - remaining, currentBuffer, inBufferPos, part);
remaining -= part;
if (remaining > 0) {
needNewBuffer(newcount);
inBufferPos = 0;
}
}
count = newcount;
}
}
/**
* Write a byte to byte array.
* @param b the byte to write
*/
public synchronized void write(int b) {
int inBufferPos = count - filledBufferSum;
if (inBufferPos == currentBuffer.length) {
needNewBuffer(count + 1);
inBufferPos = 0;
}
currentBuffer[inBufferPos] = (byte) b;
count++;
}
/**
* Writes the entire contents of the specified input stream to this
* byte stream. Bytes from the input stream are read directly into the
* internal buffers of this streams.
*
* @param in the input stream to read from
* @return total number of bytes read from the input stream
* (and written to this stream)
* @throws IOException if an I/O error occurs while reading the input stream
* @since Commons IO 1.4
*/
public synchronized int write(InputStream in) throws IOException {
int readCount = 0;
int inBufferPos = count - filledBufferSum;
int n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos);
while (n != -1) {
readCount += n;
inBufferPos += n;
count += n;
if (inBufferPos == currentBuffer.length) {
needNewBuffer(currentBuffer.length);
inBufferPos = 0;
}
n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos);
}
return readCount;
}
/**
* Return the current size of the byte array.
* @return the current size of the byte array
*/
public synchronized int size() {
return count;
}
/**
* Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in
* this class can be called after the stream has been closed without
* generating an <tt>IOException</tt>.
*
* @throws IOException never (this method should not declare this exception
* but it has to now due to backwards compatability)
*/
public void close() throws IOException {
//nop
}
/**
* @see java.io.ByteArrayOutputStream#reset()
*/
public synchronized void reset() {
count = 0;
filledBufferSum = 0;
currentBufferIndex = 0;
currentBuffer = getBuffer(currentBufferIndex);
}
/**
* Writes the entire contents of this byte stream to the
* specified output stream.
*
* @param out the output stream to write to
* @throws IOException if an I/O error occurs, such as if the stream is closed
* @see java.io.ByteArrayOutputStream#writeTo(OutputStream)
*/
public synchronized void writeTo(OutputStream out) throws IOException {
int remaining = count;
for (int i = 0; i < buffers.size(); i++) {
byte[] buf = getBuffer(i);
int c = Math.min(buf.length, remaining);
out.write(buf, 0, c);
remaining -= c;
if (remaining == 0) {
break;
}
}
}
/**
* Gets the curent contents of this byte stream as a byte array.
* The result is independent of this stream.
*
* @return the current contents of this output stream, as a byte array
* @see java.io.ByteArrayOutputStream#toByteArray()
*/
public synchronized byte[] toByteArray() {
int remaining = count;
if (remaining == 0) {
return EMPTY_BYTE_ARRAY;
}
byte newbuf[] = new byte[remaining];
int pos = 0;
for (int i = 0; i < buffers.size(); i++) {
byte[] buf = getBuffer(i);
int c = Math.min(buf.length, remaining);
System.arraycopy(buf, 0, newbuf, pos, c);
pos += c;
remaining -= c;
if (remaining == 0) {
break;
}
}
return newbuf;
}
/**
* Gets the curent contents of this byte stream as a string.
* @return the contents of the byte array as a String
* @see java.io.ByteArrayOutputStream#toString()
*/
public String toString() {
return new String(toByteArray());
}
/**
* Gets the curent contents of this byte stream as a string
* using the specified encoding.
*
* @param enc the name of the character encoding
* @return the string converted from the byte array
* @throws UnsupportedEncodingException if the encoding is not supported
* @see java.io.ByteArrayOutputStream#toString(String)
*/
public String toString(String enc) throws UnsupportedEncodingException {
return new String(toByteArray(), enc);
}
}
|
kingargyle/exist-1.4.x
|
src/org/exist/external/org/apache/commons/io/output/ByteArrayOutputStream.java
|
Java
|
lgpl-2.1
| 10,646
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>CQRS.NET: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">CQRS.NET
 <span id="projectnumber">2.2</span>
</div>
<div id="projectbrief">A lightweight enterprise framework to write CQRS, event-sourced and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('classCqrs_1_1Ninject_1_1Azure_1_1DocumentDb_1_1Configuration_1_1TestAzureDocumentDbModule.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">Cqrs.Ninject.Azure.DocumentDb.Configuration.TestAzureDocumentDbModule Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1DocumentDb_1_1Configuration_1_1TestAzureDocumentDbModule.html">Cqrs.Ninject.Azure.DocumentDb.Configuration.TestAzureDocumentDbModule</a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1DocumentDb_1_1Configuration_1_1AzureDocumentDbModule_ad9536f1eb7820c9066f2ce5f711ee55e.html#ad9536f1eb7820c9066f2ce5f711ee55e">Load</a>()</td><td class="entry"><a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1DocumentDb_1_1Configuration_1_1AzureDocumentDbModule.html">Cqrs.Ninject.Azure.DocumentDb.Configuration.AzureDocumentDbModule</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1DocumentDb_1_1Configuration_1_1AzureDocumentDbModule_a6528ff9a0213bc0accd217080ff56653.html#a6528ff9a0213bc0accd217080ff56653">RegisterAzureHelpers</a>()</td><td class="entry"><a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1DocumentDb_1_1Configuration_1_1AzureDocumentDbModule.html">Cqrs.Ninject.Azure.DocumentDb.Configuration.AzureDocumentDbModule</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1DocumentDb_1_1Configuration_1_1AzureDocumentDbModule_ad541aab18b7ca5082dcabaaa5320a15c.html#ad541aab18b7ca5082dcabaaa5320a15c">RegisterCqrsRequirements</a>()</td><td class="entry"><a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1DocumentDb_1_1Configuration_1_1AzureDocumentDbModule.html">Cqrs.Ninject.Azure.DocumentDb.Configuration.AzureDocumentDbModule</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
<tr><td class="entry"><a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1DocumentDb_1_1Configuration_1_1TestAzureDocumentDbModule_a9bd41611cfee1edc8a88815c366fccae.html#a9bd41611cfee1edc8a88815c366fccae">RegisterFactories</a>()</td><td class="entry"><a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1DocumentDb_1_1Configuration_1_1TestAzureDocumentDbModule.html">Cqrs.Ninject.Azure.DocumentDb.Configuration.TestAzureDocumentDbModule</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1DocumentDb_1_1Configuration_1_1AzureDocumentDbModule_ae47d987c2f32d3167ebda105f5fc8743.html#ae47d987c2f32d3167ebda105f5fc8743">RegisterServices</a>()</td><td class="entry"><a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1DocumentDb_1_1Configuration_1_1AzureDocumentDbModule.html">Cqrs.Ninject.Azure.DocumentDb.Configuration.AzureDocumentDbModule</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
</table></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li>
</ul>
</div>
</body>
</html>
|
cdmdotnet/CQRS
|
wiki/docs/2.2/html/classCqrs_1_1Ninject_1_1Azure_1_1DocumentDb_1_1Configuration_1_1TestAzureDocumentDbModule-members.html
|
HTML
|
lgpl-2.1
| 6,924
|
/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "PorousFlowDensityConstBulk.h"
template <>
InputParameters
validParams<PorousFlowDensityConstBulk>()
{
InputParameters params = validParams<PorousFlowFluidPropertiesBase>();
params.addRequiredParam<Real>("density_P0", "The density of each phase at zero porepressure");
params.addRequiredParam<Real>("bulk_modulus", "The constant bulk modulus of each phase");
params.addClassDescription("This Material calculates a fluid density from its porepressure, "
"assuming constant bulk modulus for the fluid");
return params;
}
PorousFlowDensityConstBulk::PorousFlowDensityConstBulk(const InputParameters & parameters)
: PorousFlowFluidPropertiesBase(parameters),
_dens0(getParam<Real>("density_P0")),
_bulk(getParam<Real>("bulk_modulus")),
_density(_nodal_material
? declareProperty<Real>("PorousFlow_fluid_phase_density_nodal" + _phase)
: declareProperty<Real>("PorousFlow_fluid_phase_density_qp" + _phase)),
_ddensity_dp(_nodal_material
? declarePropertyDerivative<Real>(
"PorousFlow_fluid_phase_density_nodal" + _phase, _pressure_variable_name)
: declarePropertyDerivative<Real>("PorousFlow_fluid_phase_density_qp" + _phase,
_pressure_variable_name)),
_ddensity_dt(
_nodal_material
? declarePropertyDerivative<Real>("PorousFlow_fluid_phase_density_nodal" + _phase,
_temperature_variable_name)
: declarePropertyDerivative<Real>("PorousFlow_fluid_phase_density_qp" + _phase,
_temperature_variable_name))
{
mooseDeprecated("PorousFlowDensityConstBulk is deprecated. Please use the SimpleFluidPropterties "
"UserObject in the fluid_properties module. See "
"porous_flow/tests/fluids/simple_fluid.i for an example");
}
void
PorousFlowDensityConstBulk::initQpStatefulProperties()
{
_density[_qp] = density(_porepressure[_qp][_phase_num]);
}
void
PorousFlowDensityConstBulk::computeQpProperties()
{
_density[_qp] = density(_porepressure[_qp][_phase_num]);
_ddensity_dp[_qp] = dDensity_dP(_porepressure[_qp][_phase_num]);
_ddensity_dt[_qp] = 0.0;
}
Real
PorousFlowDensityConstBulk::density(Real pressure) const
{
return _dens0 * std::exp(pressure / _bulk);
}
Real
PorousFlowDensityConstBulk::dDensity_dP(Real pressure) const
{
return density(pressure) / _bulk;
}
|
liuwenf/moose
|
modules/porous_flow/src/materials/PorousFlowDensityConstBulk.C
|
C++
|
lgpl-2.1
| 2,962
|
/* example-start progressbar progressbar.c */
#include <gtk/gtk.h>
typedef struct _ProgressData {
GtkWidget *window;
GtkWidget *pbar;
int timer;
} ProgressData;
/* Update the value of the progress bar so that we get
* some movement */
gint progress_timeout( gpointer data )
{
gfloat new_val;
GtkAdjustment *adj;
/* Calculate the value of the progress bar using the
* value range set in the adjustment object */
new_val = gtk_progress_get_value( GTK_PROGRESS(data) ) + 1;
adj = GTK_PROGRESS (data)->adjustment;
if (new_val > adj->upper)
new_val = adj->lower;
/* Set the new value */
gtk_progress_set_value (GTK_PROGRESS (data), new_val);
/* As this is a timeout function, return TRUE so that it
* continues to get called */
return(TRUE);
}
/* Callback that toggles the text display within the progress
* bar trough */
void toggle_show_text( GtkWidget *widget,
ProgressData *pdata )
{
gtk_progress_set_show_text (GTK_PROGRESS (pdata->pbar),
GTK_TOGGLE_BUTTON (widget)->active);
}
/* Callback that toggles the activity mode of the progress
* bar */
void toggle_activity_mode( GtkWidget *widget,
ProgressData *pdata )
{
gtk_progress_set_activity_mode (GTK_PROGRESS (pdata->pbar),
GTK_TOGGLE_BUTTON (widget)->active);
}
/* Callback that toggles the continuous mode of the progress
* bar */
void set_continuous_mode( GtkWidget *widget,
ProgressData *pdata )
{
gtk_progress_bar_set_bar_style (GTK_PROGRESS_BAR (pdata->pbar),
GTK_PROGRESS_CONTINUOUS);
}
/* Callback that toggles the discrete mode of the progress
* bar */
void set_discrete_mode( GtkWidget *widget,
ProgressData *pdata )
{
gtk_progress_bar_set_bar_style (GTK_PROGRESS_BAR (pdata->pbar),
GTK_PROGRESS_DISCRETE);
}
/* Clean up allocated memory and remove the timer */
void destroy_progress( GtkWidget *widget,
ProgressData *pdata)
{
gtk_timeout_remove (pdata->timer);
pdata->timer = 0;
pdata->window = NULL;
g_free(pdata);
gtk_main_quit();
}
int main( int argc,
char *argv[])
{
ProgressData *pdata;
GtkWidget *align;
GtkWidget *separator;
GtkWidget *table;
GtkAdjustment *adj;
GtkWidget *button;
GtkWidget *check;
GtkWidget *vbox;
gtk_init (&argc, &argv);
/* Allocate memory for the data that is passwd to the callbacks */
pdata = g_malloc( sizeof(ProgressData) );
pdata->window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_policy (GTK_WINDOW (pdata->window), FALSE, FALSE, TRUE);
gtk_signal_connect (GTK_OBJECT (pdata->window), "destroy",
GTK_SIGNAL_FUNC (destroy_progress),
pdata);
gtk_window_set_title (GTK_WINDOW (pdata->window), "GtkProgressBar");
gtk_container_set_border_width (GTK_CONTAINER (pdata->window), 0);
vbox = gtk_vbox_new (FALSE, 5);
gtk_container_set_border_width (GTK_CONTAINER (vbox), 10);
gtk_container_add (GTK_CONTAINER (pdata->window), vbox);
gtk_widget_show(vbox);
/* Create a centering alignment object */
align = gtk_alignment_new (0.5, 0.5, 0, 0);
gtk_box_pack_start (GTK_BOX (vbox), align, FALSE, FALSE, 5);
gtk_widget_show(align);
/* Create a Adjusment object to hold the range of the
* progress bar */
adj = (GtkAdjustment *) gtk_adjustment_new (0, 1, 150, 0, 0, 0);
/* Create the GtkProgressBar using the adjustment */
pdata->pbar = gtk_progress_bar_new_with_adjustment (adj);
/* Set the format of the string that can be displayed in the
* trough of the progress bar:
* %p - percentage
* %v - value
* %l - lower range value
* %u - upper range value */
gtk_progress_set_format_string (GTK_PROGRESS (pdata->pbar),
"%v from [%l-%u] (=%p%%)");
gtk_container_add (GTK_CONTAINER (align), pdata->pbar);
gtk_widget_show(pdata->pbar);
/* Add a timer callback to update the value of the progress bar */
pdata->timer = gtk_timeout_add (100, progress_timeout, pdata->pbar);
separator = gtk_hseparator_new ();
gtk_box_pack_start (GTK_BOX (vbox), separator, FALSE, FALSE, 0);
gtk_widget_show(separator);
/* rows, columns, homogeneous */
table = gtk_table_new (2, 3, FALSE);
gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, TRUE, 0);
gtk_widget_show(table);
/* Add a check button to select displaying of the trough text */
check = gtk_check_button_new_with_label ("Show text");
gtk_table_attach (GTK_TABLE (table), check, 0, 1, 0, 1,
GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL,
5, 5);
gtk_signal_connect (GTK_OBJECT (check), "clicked",
GTK_SIGNAL_FUNC (toggle_show_text),
pdata);
gtk_widget_show(check);
/* Add a check button to toggle activity mode */
check = gtk_check_button_new_with_label ("Activity mode");
gtk_table_attach (GTK_TABLE (table), check, 0, 1, 1, 2,
GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL,
5, 5);
gtk_signal_connect (GTK_OBJECT (check), "clicked",
GTK_SIGNAL_FUNC (toggle_activity_mode),
pdata);
gtk_widget_show(check);
separator = gtk_vseparator_new ();
gtk_table_attach (GTK_TABLE (table), separator, 1, 2, 0, 2,
GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL,
5, 5);
gtk_widget_show(separator);
/* Add a radio button to select continuous display mode */
button = gtk_radio_button_new_with_label (NULL, "Continuous");
gtk_table_attach (GTK_TABLE (table), button, 2, 3, 0, 1,
GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL,
5, 5);
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (set_continuous_mode),
pdata);
gtk_widget_show (button);
/* Add a radio button to select discrete display mode */
button = gtk_radio_button_new_with_label(
gtk_radio_button_group (GTK_RADIO_BUTTON (button)),
"Discrete");
gtk_table_attach (GTK_TABLE (table), button, 2, 3, 1, 2,
GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL,
5, 5);
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (set_discrete_mode),
pdata);
gtk_widget_show (button);
separator = gtk_hseparator_new ();
gtk_box_pack_start (GTK_BOX (vbox), separator, FALSE, FALSE, 0);
gtk_widget_show(separator);
/* Add a button to exit the program */
button = gtk_button_new_with_label ("close");
gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
(GtkSignalFunc) gtk_widget_destroy,
GTK_OBJECT (pdata->window));
gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0);
/* This makes it so the button is the default. */
GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
/* This grabs this button to be the default button. Simply hitting
* the "Enter" key will cause this button to activate. */
gtk_widget_grab_default (button);
gtk_widget_show(button);
gtk_widget_show (pdata->window);
gtk_main ();
return(0);
}
/* example-end */
|
dimkr/gtk
|
examples/progressbar/progressbar.c
|
C
|
lgpl-2.1
| 7,600
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//
// 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 "qapplicationargumentparser_p.h"
#include "qapplicationargument_p.h"
#include <QtTest/QtTest>
Q_DECLARE_METATYPE(QList<QApplicationArgument>);
Q_DECLARE_METATYPE(QApplicationArgumentParser::ExitCode);
/*!
\class tst_QApplicationArgumentParser
\brief The class tst_QApplicationArgumentParser tests class QApplicationArgumentParser.
\internal
\since 4.5
*/
class tst_QApplicationArgumentParser : public QObject
{
Q_OBJECT
private slots:
void negativeTest() const;
void negativeTest_data() const;
void mandatoryArguments() const;
void mandatoryArguments_data() const;
};
/*
Comments from notes.txt:
Different arg types:
* -name <mandatory value>
* -name <no value, it's a switch>
Both of these types in addition have a cardinality. For instance:
-name -name -name
-name value1 -name value2 -name value3
Possible Tests
-------------------
./foo -ab -cd -
./foo -ab -cd - - -
./foo -ab -cd - input1 input
./foo -help -
./foo - -help
// -switch has upper limit of 2
./foo -switch -switch -switch
// -switch has upper limit of 1
./foo -switch -switch
// -switch has lower limit of 1
./foo
./foo -switch cruft -switch
./foo -option value1 cruft -option value2
./foo -option value1 cruft cruft -option value2
./foo -option value1 cruft cruft cruft -option value2
./foo -option -option -option2 -option2
./foo -option
./foo -option -option -option2
./foo -option -
./foo -option - -
*/
void tst_QApplicationArgumentParser::negativeTest() const
{
}
void tst_QApplicationArgumentParser::negativeTest_data() const
{
QTest::addColumn<QStringList>("inputArgs");
QTest::addColumn<QApplicationArgumentParser::ExitCode>("expectedExitCode");
QTest::addColumn<QString>("expectedStderr");
QTest::addColumn<QList<QApplicationArgument> >("declarations");
}
void tst_QApplicationArgumentParser::mandatoryArguments() const
{
QFETCH(QStringList, inputArgs);
QFETCH(QList<QApplicationArgument>, inputDecls);
QApplicationArgumentParser parser(inputArgs);
parser.setDeclaredArguments(inputDecls);
QVERIFY(!parser.parse());
QCOMPARE(parser.exitCode(), QApplicationArgumentParser::ParseError);
}
void tst_QApplicationArgumentParser::mandatoryArguments_data() const
{
QTest::addColumn<QStringList>("inputArgs");
QTest::addColumn<QList<QApplicationArgument> >("inputDecls");
{
QStringList in;
in << "./appName";
QList<QApplicationArgument> decls;
QApplicationArgument arg1("name", QString(), QVariant::String);
arg1.setMinimumOccurrence(1);
decls.append(arg1);
QTest::newRow("A single, named, argument") << in << decls;
}
}
QTEST_APPLESS_MAIN(tst_QApplicationArgumentParser)
#include "tst_qapplicationargumentparser.moc"
|
CodeDJ/qt5-hidpi
|
qt/qtxmlpatterns/tests/auto/qapplicationargumentparser/tst_qapplicationargumentparser.cpp
|
C++
|
lgpl-2.1
| 5,043
|
using System;
using NHibernate.Engine;
using NHibernate.Type;
using NHibernate.Util;
namespace NHibernate.SqlCommand
{
/// <summary>
/// Builds a <c>SELECT</c> SQL statement.
/// </summary>
public class SqlSelectBuilder : SqlBaseBuilder, ISqlStringBuilder
{
private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(SqlSelectBuilder));
private SqlString selectClause;
private string fromClause;
private SqlString outerJoinsAfterFrom;
private SqlString whereClause;
private SqlString outerJoinsAfterWhere;
private SqlString orderByClause;
private SqlString groupByClause;
private SqlString havingClause;
private LockMode lockMode;
private string mainTableAlias;
private string comment;
public SqlSelectBuilder(ISessionFactoryImplementor factory)
: base(factory.Dialect, factory) {}
public SqlSelectBuilder SetComment(string comment)
{
this.comment = comment;
return this;
}
/// <summary>
/// Sets the text that should appear after the FROM
/// </summary>
/// <param name="fromClause">The fromClause to set</param>
/// <returns>The SqlSelectBuilder</returns>
public SqlSelectBuilder SetFromClause(string fromClause)
{
this.fromClause = fromClause;
return this;
}
/// <summary>
/// Sets the text that should appear after the FROM
/// </summary>
/// <param name="tableName">The name of the Table to get the data from</param>
/// <param name="alias">The Alias to use for the table name.</param>
/// <returns>The SqlSelectBuilder</returns>
public SqlSelectBuilder SetFromClause(string tableName, string alias)
{
fromClause = tableName + " " + alias;
return this;
}
/// <summary>
/// Sets the text that should appear after the FROM
/// </summary>
/// <param name="fromClause">The fromClause in a SqlString</param>
/// <returns>The SqlSelectBuilder</returns>
public SqlSelectBuilder SetFromClause(SqlString fromClause)
{
// it is safe to do this because a fromClause will have no parameters
return SetFromClause(fromClause.ToString());
}
/// <summary>
/// Sets the text that should appear after the ORDER BY.
/// </summary>
/// <param name="orderByClause">The orderByClause to set</param>
/// <returns>The SqlSelectBuilder</returns>
public SqlSelectBuilder SetOrderByClause(SqlString orderByClause)
{
this.orderByClause = orderByClause;
return this;
}
/// <summary>
/// Sets the text that should appear after the GROUP BY.
/// </summary>
/// <param name="groupByClause">The groupByClause to set</param>
/// <returns>The SqlSelectBuilder</returns>
public SqlSelectBuilder SetGroupByClause(SqlString groupByClause)
{
this.groupByClause = groupByClause;
return this;
}
/// <summary>
/// Sets the SqlString for the OUTER JOINs.
/// </summary>
/// <remarks>
/// All of the Sql needs to be included in the SELECT. No OUTER JOINS will automatically be
/// added.
/// </remarks>
/// <param name="outerJoinsAfterFrom">The outerJoinsAfterFrom to set</param>
/// <param name="outerJoinsAfterWhere">The outerJoinsAfterWhere to set</param>
/// <returns>The SqlSelectBuilder</returns>
public SqlSelectBuilder SetOuterJoins(SqlString outerJoinsAfterFrom, SqlString outerJoinsAfterWhere)
{
this.outerJoinsAfterFrom = outerJoinsAfterFrom;
SqlString tmpOuterJoinsAfterWhere = outerJoinsAfterWhere.Trim();
if (tmpOuterJoinsAfterWhere.StartsWithCaseInsensitive("and"))
{
tmpOuterJoinsAfterWhere = tmpOuterJoinsAfterWhere.Substring(4);
}
this.outerJoinsAfterWhere = tmpOuterJoinsAfterWhere;
return this;
}
/// <summary>
/// Sets the text for the SELECT
/// </summary>
/// <param name="selectClause">The selectClause to set</param>
/// <returns>The SqlSelectBuilder</returns>
public SqlSelectBuilder SetSelectClause(SqlString selectClause)
{
this.selectClause = selectClause;
return this;
}
/// <summary>
/// Sets the text for the SELECT
/// </summary>
/// <param name="selectClause">The selectClause to set</param>
/// <returns>The SqlSelectBuilder</returns>
public SqlSelectBuilder SetSelectClause(string selectClause)
{
this.selectClause = new SqlString(selectClause);
return this;
}
/// <summary>
/// Sets the criteria to use for the WHERE. It joins all of the columnNames together with an AND.
/// </summary>
/// <param name="tableAlias"></param>
/// <param name="columnNames">The names of the columns</param>
/// <param name="whereType">The Hibernate Type</param>
/// <returns>The SqlSelectBuilder</returns>
public SqlSelectBuilder SetWhereClause(string tableAlias, string[] columnNames, IType whereType)
{
return SetWhereClause(ToWhereString(tableAlias, columnNames));
}
/// <summary>
/// Sets the prebuilt SqlString to the Where clause
/// </summary>
/// <param name="whereSqlString">The SqlString that contains the sql and parameters to add to the WHERE</param>
/// <returns>This SqlSelectBuilder</returns>
public SqlSelectBuilder SetWhereClause(SqlString whereSqlString)
{
whereClause = whereSqlString;
return this;
}
/// <summary>
/// Sets the criteria to use for the WHERE. It joins all of the columnNames together with an AND.
/// </summary>
/// <param name="tableAlias"></param>
/// <param name="columnNames">The names of the columns</param>
/// <param name="whereType">The Hibernate Type</param>
/// <returns>The SqlSelectBuilder</returns>
public SqlSelectBuilder SetHavingClause(string tableAlias, string[] columnNames, IType whereType)
{
return SetHavingClause(ToWhereString(tableAlias, columnNames));
}
/// <summary>
/// Sets the prebuilt SqlString to the Having clause
/// </summary>
/// <param name="havingSqlString">The SqlString that contains the sql and parameters to add to the HAVING</param>
/// <returns>This SqlSelectBuilder</returns>
public SqlSelectBuilder SetHavingClause(SqlString havingSqlString)
{
havingClause = havingSqlString;
return this;
}
[Obsolete("For some DBMS's such as PostgreSQL, a lock on query with OUTER JOIN is not possible without specifying the not-null side. " +
"Use the new method SetLockMode(LockMode, mainTableAlias) instead.")]
public SqlSelectBuilder SetLockMode(LockMode lockMode)
{
this.lockMode = lockMode;
return this;
}
public SqlSelectBuilder SetLockMode(LockMode lockMode, string mainTableAlias)
{
this.lockMode = lockMode;
this.mainTableAlias = mainTableAlias;
return this;
}
#region ISqlStringBuilder Members
/// <summary>
/// ToSqlString() is named ToStatementString() in H3
/// </summary>
/// <returns></returns>
public SqlString ToStatementString()
{
return ToSqlString();
}
/// <summary></summary>
public SqlString ToSqlString()
{
// 4 = the "SELECT", selectClause, "FROM", fromClause are straight strings
// plus the number of parts in outerJoinsAfterFrom SqlString.
// 1 = the "WHERE"
// plus the number of parts in outerJoinsAfterWhere SqlString.
// 1 = the whereClause
// 2 = the "ORDER BY" and orderByClause
var joinAfterFrom = outerJoinsAfterFrom != null ? outerJoinsAfterFrom.Count : 0;
var joinAfterWhere = outerJoinsAfterWhere != null ? outerJoinsAfterWhere.Count : 0;
int initialCapacity = 4 + joinAfterFrom + 1 + joinAfterWhere + 1 + 2;
if (!string.IsNullOrEmpty(comment))
initialCapacity++;
SqlStringBuilder sqlBuilder = new SqlStringBuilder(initialCapacity + 2);
if (!string.IsNullOrEmpty(comment))
sqlBuilder.Add("/* " + comment + " */ ");
sqlBuilder.Add("SELECT ")
.Add(selectClause)
.Add(" FROM ")
.Add(fromClause);
if (SqlStringHelper.IsNotEmpty(outerJoinsAfterFrom))
{
sqlBuilder.Add(outerJoinsAfterFrom);
}
if (SqlStringHelper.IsNotEmpty(whereClause) || SqlStringHelper.IsNotEmpty(outerJoinsAfterWhere))
{
sqlBuilder.Add(" WHERE ");
// the outerJoinsAfterWhere needs to come before where clause to properly
// handle dynamic filters
if (SqlStringHelper.IsNotEmpty(outerJoinsAfterWhere))
{
sqlBuilder.Add(outerJoinsAfterWhere);
if (SqlStringHelper.IsNotEmpty(whereClause))
{
sqlBuilder.Add(" AND ");
}
}
if (SqlStringHelper.IsNotEmpty(whereClause))
{
sqlBuilder.Add(whereClause);
}
}
if (SqlStringHelper.IsNotEmpty(groupByClause))
{
sqlBuilder.Add(" GROUP BY ")
.Add(groupByClause);
}
if(SqlStringHelper.IsNotEmpty(havingClause))
{
sqlBuilder.Add(" HAVING ")
.Add(havingClause);
}
if (SqlStringHelper.IsNotEmpty(orderByClause))
{
sqlBuilder.Add(" ORDER BY ")
.Add(orderByClause);
}
if (lockMode != null)
{
sqlBuilder.Add(GetForUpdateString());
}
if (log.IsDebugEnabled())
{
if (initialCapacity < sqlBuilder.Count)
{
log.Debug("The initial capacity was set too low at: {0} for the SelectSqlBuilder that needed a capacity of: {1} for the table {2}",
initialCapacity,
sqlBuilder.Count,
fromClause);
}
else if (initialCapacity > 16 && ((float) initialCapacity / sqlBuilder.Count) > 1.2)
{
log.Debug("The initial capacity was set too high at: {0} for the SelectSqlBuilder that needed a capacity of: {1} for the table {2}",
initialCapacity,
sqlBuilder.Count,
fromClause);
}
}
return sqlBuilder.ToSqlString();
}
private string GetForUpdateString()
{
if (!Dialect.SupportsOuterJoinForUpdate && HasOuterJoin())
{
var isUpgrade = Equals(lockMode, LockMode.Upgrade);
var isUpgradeNoWait = !isUpgrade && (
Equals(lockMode, LockMode.UpgradeNoWait) || Equals(lockMode, LockMode.Force));
if (!isUpgrade && !isUpgradeNoWait)
return string.Empty;
if (!Dialect.SupportsForUpdateOf)
{
log.Warn(
"Unsupported 'for update' case: 'for update' query with an outer join using a dialect not" +
"supporting it and not supporting 'for update of' clause. Discarding 'for" +
"update' clause.");
return string.Empty;
}
if (Dialect.UsesColumnsWithForUpdateOf)
{
log.Warn(
"Unimplemented 'for update' case: 'for update' query with an outer join using a dialect not" +
"supporting it and requiring columns for its 'for update of' syntax. Discarding 'for" +
"update' clause.");
return string.Empty;
}
return isUpgrade ? Dialect.GetForUpdateString(mainTableAlias) : Dialect.GetForUpdateNowaitString(mainTableAlias);
}
return Dialect.GetForUpdateString(lockMode);
bool HasOuterJoin() =>
outerJoinsAfterFrom?.IsEmptyOrWhitespace() == false ||
StringHelper.ContainsCaseInsensitive(fromClause, "outer join");
}
#endregion
}
}
|
lnu/nhibernate-core
|
src/NHibernate/SqlCommand/SqlSelectBuilder.cs
|
C#
|
lgpl-2.1
| 10,807
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.16"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>CQRS.NET: Cqrs.Domain.Saga.Id</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(initResizable);
/* @license-end */</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script><script type="text/javascript" async="async" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">CQRS.NET
 <span id="projectnumber">4.2</span>
</div>
<div id="projectbrief">A lightweight enterprise Function as a Service (FaaS) framework to write function based serverless and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.16 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(function(){initNavTree('classCqrs_1_1Domain_1_1Saga_af6b9552a90fcbe5c101c413126256565.html','');});
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="contents">
<a id="af6b9552a90fcbe5c101c413126256565"></a>
<h2 class="memtitle"><span class="permalink"><a href="#af6b9552a90fcbe5c101c413126256565">◆ </a></span>Id</h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">Guid <a class="el" href="classCqrs_1_1Domain_1_1Saga.html">Cqrs.Domain.Saga</a>< TAuthenticationToken >.Id</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">get</span><span class="mlabel">protected set</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>The identifier of this ISaga<TAuthenticationToken>. </p>
</div>
</div>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="namespaceCqrs.html">Cqrs</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Domain.html">Domain</a></li><li class="navelem"><a class="el" href="classCqrs_1_1Domain_1_1Saga.html">Saga</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.16 </li>
</ul>
</div>
</body>
</html>
|
Chinchilla-Software-Com/CQRS
|
wiki/docs/4.2/html/classCqrs_1_1Domain_1_1Saga_af6b9552a90fcbe5c101c413126256565.html
|
HTML
|
lgpl-2.1
| 5,449
|
/*
* src/nl-class-delete.c Delete Traffic Classes
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* Copyright (c) 2010 Thomas Graf <tgraf@suug.ch>
*/
#include <netlink/cli/utils.h>
#include <netlink/cli/class.h>
#include <netlink/cli/link.h>
#include <linux/netlink.h>
static int quiet = 0, default_yes = 0, deleted = 0, interactive = 0;
static struct nl_sock *sock;
static void print_usage(void)
{
printf(
"Usage: nl-class-delete [OPTION]... [class]\n"
"\n"
"OPTIONS\n"
" --interactive Run interactively.\n"
" --yes Set default answer to yes.\n"
" -q, --quiet Do not print informal notifications.\n"
" -h, --help Show this help text and exit.\n"
" -v, --version Show versioning information and exit.\n"
"\n"
" -d, --dev=DEV Device the class is attached to.\n"
" -p, --parent=ID Identifier of parent qdisc/class.\n"
" -i, --id=ID Identifier\n"
" -k, --kind=NAME Kind of class (e.g. pfifo_fast)\n"
"\n"
"EXAMPLE\n"
" # Delete all classes on eth0 attached to parent 1:\n"
" $ nl-class-delete --dev eth0 --parent 1:\n"
"\n"
);
exit(0);
}
static void delete_cb(struct nl_object *obj, void *arg)
{
struct rtnl_class *class = nl_object_priv(obj);
struct nl_dump_params params = {
.dp_type = NL_DUMP_LINE,
.dp_fd = stdout,
};
int err;
if (interactive && !nl_cli_confirm(obj, ¶ms, default_yes))
return;
if ((err = rtnl_class_delete(sock, class)) < 0)
nl_cli_fatal(err, "Unable to delete class: %s\n", nl_geterror(err));
if (!quiet) {
printf("Deleted ");
nl_object_dump(obj, ¶ms);
}
deleted++;
}
int main(int argc, char *argv[])
{
struct rtnl_class *class;
struct rtnl_tc *tc;
struct nl_cache *link_cache, *class_cache;
sock = nl_cli_alloc_socket();
nl_cli_connect(sock, NETLINK_ROUTE);
link_cache = nl_cli_link_alloc_cache(sock);
class = nl_cli_class_alloc();
tc = (struct rtnl_tc *) class;
for (;;) {
int c, optidx = 0;
enum {
ARG_YES = 257,
ARG_INTERACTIVE = 258,
};
static struct option long_opts[] = {
{ "interactive", 0, 0, ARG_INTERACTIVE },
{ "yes", 0, 0, ARG_YES },
{ "quiet", 0, 0, 'q' },
{ "help", 0, 0, 'h' },
{ "version", 0, 0, 'v' },
{ "dev", 1, 0, 'd' },
{ "parent", 1, 0, 'p' },
{ "id", 1, 0, 'i' },
{ "kind", 1, 0, 'k' },
{ 0, 0, 0, 0 }
};
c = getopt_long(argc, argv, "qhvd:p:i:k:", long_opts, &optidx);
if (c == -1)
break;
switch (c) {
case '?': nl_cli_fatal(EINVAL, "Invalid options");
case ARG_INTERACTIVE: interactive = 1; break;
case ARG_YES: default_yes = 1; break;
case 'q': quiet = 1; break;
case 'h': print_usage(); break;
case 'v': nl_cli_print_version(); break;
case 'd': nl_cli_tc_parse_dev(tc, link_cache, optarg); break;
case 'p': nl_cli_tc_parse_parent(tc, optarg); break;
case 'i': nl_cli_tc_parse_handle(tc, optarg, 0); break;
case 'k': nl_cli_tc_parse_kind(tc, optarg); break;
}
}
if (!rtnl_tc_get_ifindex(tc))
nl_cli_fatal(EINVAL, "You must specify a network device (--dev=XXX)");
class_cache = nl_cli_class_alloc_cache(sock, rtnl_tc_get_ifindex(tc));
nl_cache_foreach_filter(class_cache, OBJ_CAST(class), delete_cb, NULL);
if (!quiet)
printf("Deleted %d classs\n", deleted);
return 0;
}
|
dsahern/libnl
|
src/nl-class-delete.c
|
C
|
lgpl-2.1
| 3,449
|
//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org>
//
#include "MarbleDeclarativeWidget.h"
#include "Coordinate.h"
#include "ZoomButtonInterceptor.h"
#include "GeoDataCoordinates.h"
#include "MarbleWidget.h"
#include "MarbleModel.h"
#include "MarbleWidgetInputHandler.h"
#include "MarbleMath.h"
#include "MapThemeManager.h"
#include "AbstractFloatItem.h"
#include "AbstractDataPlugin.h"
#include "RenderPlugin.h"
#include "MarbleMap.h"
#include "MarbleDirs.h"
#include "ViewParams.h"
#include "ViewportParams.h"
#include "DownloadRegion.h"
#include "BookmarkManager.h"
#include "routing/RoutingManager.h"
#include "routing/RoutingProfilesModel.h"
#include "DeclarativeDataPlugin.h"
#include "PluginManager.h"
MarbleWidget::MarbleWidget( QGraphicsItem *parent , Qt::WindowFlags flags ) :
QGraphicsProxyWidget( parent, flags ),
m_marbleWidget( new Marble::MarbleWidget ),
m_inputEnabled( true ),
m_interceptor( new ZoomButtonInterceptor( this, this ) )
{
m_marbleWidget->setMapThemeId( "earth/openstreetmap/openstreetmap.dgml" );
QSettings settings;
m_marbleWidget->readPluginSettings( settings );
m_marbleWidget->model()->routingManager()->profilesModel()->loadDefaultProfiles();
m_marbleWidget->model()->routingManager()->readSettings();
m_marbleWidget->model()->bookmarkManager()->loadFile( "bookmarks/bookmarks.kml" );
setWidget( m_marbleWidget );
connect( m_marbleWidget, SIGNAL(visibleLatLonAltBoxChanged(GeoDataLatLonAltBox)),
this, SIGNAL(visibleLatLonAltBoxChanged()) );
connect( m_marbleWidget->model(), SIGNAL(workOfflineChanged()),
this, SIGNAL(workOfflineChanged()) );
connect( m_marbleWidget, SIGNAL(zoomChanged(int)),
this, SIGNAL(radiusChanged()) );
connect( m_marbleWidget, SIGNAL(themeChanged(QString)),
this, SIGNAL(mapThemeChanged()) );
connect( m_marbleWidget, SIGNAL(projectionChanged(Projection)),
this, SIGNAL(projectionChanged()) );
connect( m_marbleWidget, SIGNAL(mouseClickGeoPosition(qreal,qreal,GeoDataCoordinates::Unit)),
this, SLOT(forwardMouseClick(qreal,qreal,GeoDataCoordinates::Unit)) );
connect( &m_center, SIGNAL(latitudeChanged()), this, SLOT(updateCenterPosition()));
connect( &m_center, SIGNAL(longitudeChanged()), this, SLOT(updateCenterPosition()));
m_marbleWidget->inputHandler()->setMouseButtonPopupEnabled( Qt::LeftButton, false );
m_marbleWidget->inputHandler()->setPanViaArrowsEnabled( false );
grabGesture( Qt::PinchGesture, Qt::ReceivePartialGestures | Qt::IgnoredGesturesPropagateToParent );
setAcceptTouchEvents(true);
}
MarbleWidget::~MarbleWidget()
{
QSettings settings;
m_marbleWidget->writePluginSettings( settings );
m_marbleWidget->model()->routingManager()->writeSettings();
}
Marble::MarbleModel *MarbleWidget::model()
{
return m_marbleWidget->model();
}
const Marble::ViewportParams *MarbleWidget::viewport() const
{
return m_marbleWidget->viewport();
}
QList<QObject*> MarbleWidget::renderPlugins() const
{
QList<QObject*> result;
foreach ( Marble::RenderPlugin* plugin, m_marbleWidget->renderPlugins() ) {
result << plugin;
}
return result;
}
QStringList MarbleWidget::activeFloatItems() const
{
QStringList result;
foreach( Marble::AbstractFloatItem * floatItem, m_marbleWidget->floatItems() ) {
if ( floatItem->enabled() && floatItem->visible() ) {
result << floatItem->nameId();
}
}
return result;
}
void MarbleWidget::setActiveFloatItems( const QStringList &items )
{
foreach( Marble::AbstractFloatItem * floatItem, m_marbleWidget->floatItems() ) {
floatItem->setEnabled( items.contains( floatItem->nameId() ) );
floatItem->setVisible( items.contains( floatItem->nameId() ) );
}
}
QStringList MarbleWidget::activeRenderPlugins() const
{
QStringList result;
foreach( Marble::RenderPlugin * plugin, m_marbleWidget->renderPlugins() ) {
if ( plugin->enabled() && plugin->visible() ) {
result << plugin->nameId();
}
}
return result;
}
QDeclarativeListProperty<QObject> MarbleWidget::childList()
{
return QDeclarativeListProperty<QObject>( this, m_children );
}
QDeclarativeListProperty<DeclarativeDataPlugin> MarbleWidget::dataLayers()
{
return QDeclarativeListProperty<DeclarativeDataPlugin>( this, 0, &MarbleWidget::addLayer );
}
void MarbleWidget::setActiveRenderPlugins( const QStringList &items )
{
foreach( Marble::RenderPlugin * plugin, m_marbleWidget->renderPlugins() ) {
plugin->setEnabled( items.contains( plugin->nameId() ) );
plugin->setVisible( items.contains( plugin->nameId() ) );
}
}
bool MarbleWidget::inputEnabled() const
{
return m_inputEnabled;
}
void MarbleWidget::setInputEnabled( bool enabled )
{
m_inputEnabled = enabled;
m_marbleWidget->setInputEnabled( enabled );
}
QString MarbleWidget::mapThemeId() const
{
return m_marbleWidget->mapThemeId();
}
void MarbleWidget::setMapThemeId( const QString &mapThemeId )
{
m_marbleWidget->setMapThemeId( mapThemeId );
}
QString MarbleWidget::projection( ) const
{
switch ( m_marbleWidget->projection() ) {
case Marble::Equirectangular:
return "Equirectangular";
case Marble::Mercator:
return "Mercator";
case Marble::Spherical:
return "Spherical";
}
Q_ASSERT( false && "Marble got a new projection which we do not know about yet" );
return "Spherical";
}
void MarbleWidget::setProjection( const QString &projection )
{
if ( projection.compare( "Equirectangular", Qt::CaseInsensitive ) == 0 ) {
m_marbleWidget->setProjection( Marble::Equirectangular );
} else if ( projection.compare( "Mercator", Qt::CaseInsensitive ) == 0 ) {
m_marbleWidget->setProjection( Marble::Mercator );
} else {
m_marbleWidget->setProjection( Marble::Spherical );
}
}
void MarbleWidget::zoomIn()
{
m_marbleWidget->zoomIn();
}
void MarbleWidget::zoomOut()
{
m_marbleWidget->zoomOut();
}
QPoint MarbleWidget::pixel( qreal lon, qreal lat ) const
{
Marble::GeoDataCoordinates position( lon, lat, 0, Marble::GeoDataCoordinates::Degree );
qreal x( 0.0 );
qreal y( 0.0 );
Marble::ViewportParams *viewport = m_marbleWidget->viewport();
viewport->screenCoordinates( position, x, y );
return QPoint( x, y );
}
Coordinate *MarbleWidget::coordinate( int x, int y )
{
qreal lat( 0.0 ), lon( 0.0 );
m_marbleWidget->geoCoordinates( x, y, lon, lat );
return new Coordinate( lon, lat, 0.0, this );
}
Coordinate* MarbleWidget::center()
{
m_center.blockSignals( true );
m_center.setLongitude( m_marbleWidget->centerLongitude() );
m_center.setLatitude( m_marbleWidget->centerLatitude() );
m_center.blockSignals( false );
return &m_center;
}
void MarbleWidget::setCenter( Coordinate* center )
{
if ( center ) {
m_center.blockSignals( true );
m_center.setLongitude( center->longitude() );
m_center.setLatitude( center->latitude() );
m_center.setAltitude( center->altitude() );
m_center.blockSignals( false );
updateCenterPosition();
}
}
void MarbleWidget::centerOn( const Marble::GeoDataLatLonBox &bbox )
{
m_marbleWidget->centerOn( bbox );
}
void MarbleWidget::centerOn( const Marble::GeoDataCoordinates &coordinates )
{
m_marbleWidget->centerOn( coordinates );
}
void MarbleWidget::updateCenterPosition()
{
m_marbleWidget->centerOn( m_center.longitude(), m_center.latitude() );
}
void MarbleWidget::forwardMouseClick(qreal lon, qreal lat, Marble::GeoDataCoordinates::Unit unit )
{
Marble::GeoDataCoordinates position( lon, lat, unit );
Marble::GeoDataCoordinates::Unit degree = Marble::GeoDataCoordinates::Degree;
QPoint const point = pixel( position.longitude( degree ), position.latitude( degree ) );
QVector<const Marble::GeoDataPlacemark*> const placemarks = m_marbleWidget->whichFeatureAt( point );
if ( !placemarks.isEmpty() ) {
if ( placemarks.size() == 1 ) {
Placemark* placemark = new Placemark;
placemark->setGeoDataPlacemark( *placemarks.first() );
emit placemarkSelected( placemark );
}
} else {
emit mouseClickGeoPosition( position.longitude( degree ),
position.latitude( degree ) );
}
}
void MarbleWidget::addLayer( QDeclarativeListProperty<DeclarativeDataPlugin> *list, DeclarativeDataPlugin *layer )
{
MarbleWidget *object = qobject_cast<MarbleWidget *>( list->object );
if ( object ) {
object->m_marbleWidget->model()->pluginManager()->addRenderPlugin( layer );
object->setDataPluginDelegate( layer->nameId(), layer->delegate() );
object->m_dataLayers << layer;
}
}
QObject *MarbleWidget::mapThemeModel()
{
return m_marbleWidget->model()->mapThemeManager()->mapThemeModel();
}
void MarbleWidget::setGeoSceneProperty(const QString &key, bool value)
{
m_marbleWidget->setPropertyValue( key, value );
}
void MarbleWidget::downloadRoute( qreal offset, int topTileLevel, int bottomTileLevel )
{
Marble::DownloadRegion region;
region.setMarbleModel( m_marbleWidget->model() );
region.setVisibleTileLevel( m_marbleWidget->tileZoomLevel() );
region.setTileLevelRange( topTileLevel, bottomTileLevel );
QVector<Marble::TileCoordsPyramid> const pyramid = region.routeRegion( m_marbleWidget->textureLayer(), offset );
if ( !pyramid.isEmpty() ) {
m_marbleWidget->downloadRegion( pyramid );
}
}
void MarbleWidget::downloadArea(int topTileLevel, int bottomTileLevel)
{
Marble::DownloadRegion region;
region.setMarbleModel( m_marbleWidget->model() );
region.setVisibleTileLevel( m_marbleWidget->tileZoomLevel() );
region.setTileLevelRange( topTileLevel, bottomTileLevel );
QVector<Marble::TileCoordsPyramid> const pyramid = region.region( m_marbleWidget->textureLayer(), m_marbleWidget->viewport()->viewLatLonAltBox() );
if ( !pyramid.isEmpty() ) {
m_marbleWidget->downloadRegion( pyramid );
}
}
void MarbleWidget::setDataPluginDelegate( const QString &plugin, QDeclarativeComponent *delegate )
{
QList<Marble::RenderPlugin*> renderPlugins = m_marbleWidget->renderPlugins();
foreach( Marble::RenderPlugin* renderPlugin, renderPlugins ) {
Marble::AbstractDataPlugin* dataPlugin = qobject_cast<Marble::AbstractDataPlugin*>( renderPlugin );
if ( dataPlugin && dataPlugin->nameId() == plugin ) {
dataPlugin->setDelegate( delegate, this );
}
}
}
bool MarbleWidget::workOffline() const
{
return m_marbleWidget->model()->workOffline();
}
void MarbleWidget::setWorkOffline( bool workOffline )
{
m_marbleWidget->model()->setWorkOffline( workOffline );
}
int MarbleWidget::radius() const
{
return m_marbleWidget->radius();
}
void MarbleWidget::setRadius( int radius )
{
m_marbleWidget->setRadius( radius );
}
bool MarbleWidget::event ( QEvent * event )
{
if ( m_marbleWidget && event && event->type() == QEvent::Gesture ) {
return QApplication::sendEvent( m_marbleWidget, event );
}
return QGraphicsProxyWidget::event( event );
}
bool MarbleWidget::sceneEvent( QEvent *event )
{
if ( event->type() == QEvent::TouchBegin ) {
event->accept();
return true;
}
return QGraphicsProxyWidget::sceneEvent( event );
}
Marble::RenderPlugin *MarbleWidget::renderPlugin( const QString & name )
{
foreach( Marble::RenderPlugin * plugin, m_marbleWidget->renderPlugins() )
{
if( plugin->nameId() == name ) {
return plugin;
}
}
return 0;
}
bool MarbleWidget::containsRenderPlugin( const QString & name )
{
foreach( Marble::RenderPlugin * plugin, m_marbleWidget->renderPlugins() )
{
if( plugin->nameId() == name ) {
return true;
}
}
return false;
}
QList<QObject*> MarbleWidget::floatItems() const
{
QList<QObject*> result;
foreach ( Marble::AbstractFloatItem* plugin, m_marbleWidget->floatItems() ) {
result << plugin;
}
return result;
}
Marble::AbstractFloatItem* MarbleWidget::floatItem( const QString & name )
{
foreach( Marble::AbstractFloatItem * plugin, m_marbleWidget->floatItems() )
{
if( plugin->nameId() == name ) {
return plugin ;
}
}
return 0;
}
bool MarbleWidget::containsFloatItem( const QString & name )
{
foreach( Marble::AbstractFloatItem * plugin, m_marbleWidget->floatItems() )
{
if( plugin->nameId() == name ) {
return true;
}
}
return false;
}
#include "MarbleDeclarativeWidget.moc"
|
oberluz/marble
|
src/plugins/declarative/MarbleDeclarativeWidget.cpp
|
C++
|
lgpl-2.1
| 12,999
|
/****************************************************************************
**
** 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 test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//TESTED_COMPONENT=src/serviceframework
#include <qmobilityglobal.h>
#include <QtTest/QtTest>
#include <QtCore/qlocale.h>
#include <qmetaobjectbuilder_p.h>
QTM_USE_NAMESPACE
class tst_QMetaObjectBuilder : public QObject
{
Q_OBJECT
public:
tst_QMetaObjectBuilder() {}
~tst_QMetaObjectBuilder() {}
private slots:
void mocVersionCheck();
void create();
void className();
void superClass();
void flags();
void method();
void slot();
void signal();
void constructor();
void property();
void notifySignal();
void enumerator();
void classInfo();
void relatedMetaObject();
void staticMetacall();
void copyMetaObject();
void serialize();
void removeNotifySignal();
private:
static bool checkForSideEffects
(const QMetaObjectBuilder& builder,
QMetaObjectBuilder::AddMembers members);
static bool sameMetaObject
(const QMetaObject *meta1, const QMetaObject *meta2);
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject *meta;
#endif
// Dummy class that has something of every type of thing moc can generate.
class SomethingOfEverything : public QObject
{
Q_OBJECT
Q_CLASSINFO("ci_foo", "ABC")
Q_CLASSINFO("ci_bar", "DEF")
Q_PROPERTY(QString prop READ prop WRITE setProp NOTIFY propChanged)
Q_PROPERTY(QString prop2 READ prop WRITE setProp)
Q_PROPERTY(SomethingEnum eprop READ eprop)
Q_PROPERTY(SomethingFlagEnum fprop READ fprop)
Q_PROPERTY(QLocale::Language language READ language)
Q_ENUMS(SomethingEnum)
Q_FLAGS(SomethingFlagEnum)
public:
Q_INVOKABLE SomethingOfEverything() {}
~SomethingOfEverything() {}
enum SomethingEnum
{
GHI,
JKL = 10
};
enum SomethingFlagEnum
{
XYZ = 1,
UVW = 8
};
Q_INVOKABLE Q_SCRIPTABLE void method1() {}
QString prop() const { return QString(); }
void setProp(const QString& v) { Q_UNUSED(v); }
SomethingOfEverything::SomethingEnum eprop() const { return GHI; }
SomethingOfEverything::SomethingFlagEnum fprop() const { return XYZ; }
QLocale::Language language() const { return QLocale::English; }
public slots:
void slot1(const QString&) {}
void slot2(int, const QString&) {}
private slots:
void slot3() {}
protected slots:
Q_SCRIPTABLE void slot4(int) {}
void slot5(int a, const QString& b) { Q_UNUSED(a); Q_UNUSED(b); }
signals:
void sig1();
void sig2(int x, const QString& y);
void propChanged(const QString&);
};
void tst_QMetaObjectBuilder::mocVersionCheck()
{
// This test will fail when the moc version number is changed.
// It is intended as a reminder to also update QMetaObjectBuilder
// whenenver moc changes. Once QMetaObjectBuilder has been
// updated, this test can be changed to check for the next version.
int version = int(QObject::staticMetaObject.d.data[0]);
QVERIFY(version == 4 || version == 5 || version == 6);
version = int(staticMetaObject.d.data[0]);
QVERIFY(version == 4 || version == 5 || version == 6);
}
void tst_QMetaObjectBuilder::create()
{
QMetaObjectBuilder builder;
QVERIFY(builder.className().isEmpty());
QVERIFY(builder.superClass() == &QObject::staticMetaObject);
QCOMPARE(builder.methodCount(), 0);
QCOMPARE(builder.constructorCount(), 0);
QCOMPARE(builder.propertyCount(), 0);
QCOMPARE(builder.enumeratorCount(), 0);
QCOMPARE(builder.classInfoCount(), 0);
QCOMPARE(builder.relatedMetaObjectCount(), 0);
QVERIFY(builder.staticMetacallFunction() == 0);
}
void tst_QMetaObjectBuilder::className()
{
QMetaObjectBuilder builder;
// Change the class name.
builder.setClassName("Foo");
QCOMPARE(builder.className(), QByteArray("Foo"));
// Change it again.
builder.setClassName("Bar");
QCOMPARE(builder.className(), QByteArray("Bar"));
// Clone the class name off a static QMetaObject.
builder.addMetaObject(&QObject::staticMetaObject, QMetaObjectBuilder::ClassName);
QCOMPARE(builder.className(), QByteArray("QObject"));
// Check that nothing else changed.
QVERIFY(checkForSideEffects(builder, QMetaObjectBuilder::ClassName));
}
void tst_QMetaObjectBuilder::superClass()
{
QMetaObjectBuilder builder;
// Change the super class.
builder.setSuperClass(&QObject::staticMetaObject);
QVERIFY(builder.superClass() == &QObject::staticMetaObject);
// Change it again.
builder.setSuperClass(&staticMetaObject);
QVERIFY(builder.superClass() == &staticMetaObject);
// Clone the super class off a static QMetaObject.
builder.addMetaObject(&QObject::staticMetaObject, QMetaObjectBuilder::SuperClass);
QVERIFY(builder.superClass() == 0);
builder.addMetaObject(&staticMetaObject, QMetaObjectBuilder::SuperClass);
QVERIFY(builder.superClass() == staticMetaObject.superClass());
// Check that nothing else changed.
QVERIFY(checkForSideEffects(builder, QMetaObjectBuilder::SuperClass));
}
void tst_QMetaObjectBuilder::flags()
{
QMetaObjectBuilder builder;
// Check default
QVERIFY(builder.flags() == 0);
// Set flags
builder.setFlags(QMetaObjectBuilder::DynamicMetaObject);
QVERIFY(builder.flags() == QMetaObjectBuilder::DynamicMetaObject);
}
void tst_QMetaObjectBuilder::method()
{
QMetaObjectBuilder builder;
// Check null method
QMetaMethodBuilder nullMethod;
QCOMPARE(nullMethod.signature(), QByteArray());
QVERIFY(nullMethod.methodType() == QMetaMethod::Method);
QVERIFY(nullMethod.returnType().isEmpty());
QVERIFY(nullMethod.parameterNames().isEmpty());
QVERIFY(nullMethod.tag().isEmpty());
QVERIFY(nullMethod.access() == QMetaMethod::Public);
QCOMPARE(nullMethod.attributes(), 0);
QCOMPARE(nullMethod.index(), 0);
// Add a method and check its attributes.
QMetaMethodBuilder method1 = builder.addMethod("foo(const QString&, int)");
QCOMPARE(method1.signature(), QByteArray("foo(QString,int)"));
QVERIFY(method1.methodType() == QMetaMethod::Method);
QVERIFY(method1.returnType().isEmpty());
QVERIFY(method1.parameterNames().isEmpty());
QVERIFY(method1.tag().isEmpty());
QVERIFY(method1.access() == QMetaMethod::Public);
QCOMPARE(method1.attributes(), 0);
QCOMPARE(method1.index(), 0);
QCOMPARE(builder.methodCount(), 1);
// Add another method and check again.
QMetaMethodBuilder method2 = builder.addMethod("bar(QString)", "int");
QCOMPARE(method2.signature(), QByteArray("bar(QString)"));
QVERIFY(method2.methodType() == QMetaMethod::Method);
QCOMPARE(method2.returnType(), QByteArray("int"));
QVERIFY(method2.parameterNames().isEmpty());
QVERIFY(method2.tag().isEmpty());
QVERIFY(method2.access() == QMetaMethod::Public);
QCOMPARE(method2.attributes(), 0);
QCOMPARE(method2.index(), 1);
QCOMPARE(builder.methodCount(), 2);
// Perform index-based lookup.
QCOMPARE(builder.indexOfMethod("foo(const QString&, int)"), 0);
QCOMPARE(builder.indexOfMethod("bar(QString)"), 1);
QCOMPARE(builder.indexOfMethod("baz()"), -1);
// Modify the attributes on method1.
method1.setReturnType("int");
method1.setParameterNames(QList<QByteArray>() << "a" << "b");
method1.setTag("tag");
method1.setAccess(QMetaMethod::Private);
method1.setAttributes(42);
// Check that method1 is changed, but method2 is not.
QCOMPARE(method1.signature(), QByteArray("foo(QString,int)"));
QVERIFY(method1.methodType() == QMetaMethod::Method);
QCOMPARE(method1.returnType(), QByteArray("int"));
QCOMPARE(method1.parameterNames(), QList<QByteArray>() << "a" << "b");
QCOMPARE(method1.tag(), QByteArray("tag"));
QVERIFY(method1.access() == QMetaMethod::Private);
QCOMPARE(method1.attributes(), 42);
QCOMPARE(method1.index(), 0);
QCOMPARE(method2.signature(), QByteArray("bar(QString)"));
QVERIFY(method2.methodType() == QMetaMethod::Method);
QCOMPARE(method2.returnType(), QByteArray("int"));
QVERIFY(method2.parameterNames().isEmpty());
QVERIFY(method2.tag().isEmpty());
QVERIFY(method2.access() == QMetaMethod::Public);
QCOMPARE(method2.attributes(), 0);
QCOMPARE(method2.index(), 1);
QCOMPARE(builder.methodCount(), 2);
// Modify the attributes on method2.
method2.setReturnType("QString");
method2.setParameterNames(QList<QByteArray>() << "c");
method2.setTag("Q_FOO");
method2.setAccess(QMetaMethod::Protected);
method2.setAttributes(24);
// This time check that only method2 changed.
QCOMPARE(method1.signature(), QByteArray("foo(QString,int)"));
QVERIFY(method1.methodType() == QMetaMethod::Method);
QCOMPARE(method1.returnType(), QByteArray("int"));
QCOMPARE(method1.parameterNames(), QList<QByteArray>() << "a" << "b");
QCOMPARE(method1.tag(), QByteArray("tag"));
QVERIFY(method1.access() == QMetaMethod::Private);
QCOMPARE(method1.attributes(), 42);
QCOMPARE(method1.index(), 0);
QCOMPARE(method2.signature(), QByteArray("bar(QString)"));
QVERIFY(method2.methodType() == QMetaMethod::Method);
QCOMPARE(method2.returnType(), QByteArray("QString"));
QCOMPARE(method2.parameterNames(), QList<QByteArray>() << "c");
QCOMPARE(method2.tag(), QByteArray("Q_FOO"));
QVERIFY(method2.access() == QMetaMethod::Protected);
QCOMPARE(method2.attributes(), 24);
QCOMPARE(method2.index(), 1);
QCOMPARE(builder.methodCount(), 2);
// Remove method1 and check that method2 becomes index 0.
builder.removeMethod(0);
QCOMPARE(builder.methodCount(), 1);
method2 = builder.method(0);
QCOMPARE(method2.signature(), QByteArray("bar(QString)"));
QVERIFY(method2.methodType() == QMetaMethod::Method);
QCOMPARE(method2.returnType(), QByteArray("QString"));
QCOMPARE(method2.parameterNames(), QList<QByteArray>() << "c");
QCOMPARE(method2.tag(), QByteArray("Q_FOO"));
QVERIFY(method2.access() == QMetaMethod::Protected);
QCOMPARE(method2.attributes(), 24);
QCOMPARE(method2.index(), 0);
// Perform index-based lookup again.
QCOMPARE(builder.indexOfMethod("foo(const QString&, int)"), -1);
QCOMPARE(builder.indexOfMethod("bar(QString)"), 0);
QCOMPARE(builder.indexOfMethod("baz()"), -1);
QCOMPARE(builder.method(0).signature(), QByteArray("bar(QString)"));
QCOMPARE(builder.method(9).signature(), QByteArray());
// Check that nothing else changed.
QVERIFY(checkForSideEffects(builder, QMetaObjectBuilder::Methods));
}
void tst_QMetaObjectBuilder::slot()
{
QMetaObjectBuilder builder;
// Add a slot and check its attributes.
QMetaMethodBuilder method1 = builder.addSlot("foo(const QString&, int)");
QCOMPARE(method1.signature(), QByteArray("foo(QString,int)"));
QVERIFY(method1.methodType() == QMetaMethod::Slot);
QVERIFY(method1.returnType().isEmpty());
QVERIFY(method1.parameterNames().isEmpty());
QVERIFY(method1.tag().isEmpty());
QVERIFY(method1.access() == QMetaMethod::Public);
QCOMPARE(method1.attributes(), 0);
QCOMPARE(method1.index(), 0);
QCOMPARE(builder.methodCount(), 1);
// Add another slot and check again.
QMetaMethodBuilder method2 = builder.addSlot("bar(QString)");
QCOMPARE(method2.signature(), QByteArray("bar(QString)"));
QVERIFY(method2.methodType() == QMetaMethod::Slot);
QVERIFY(method2.returnType().isEmpty());
QVERIFY(method2.parameterNames().isEmpty());
QVERIFY(method2.tag().isEmpty());
QVERIFY(method2.access() == QMetaMethod::Public);
QCOMPARE(method2.attributes(), 0);
QCOMPARE(method2.index(), 1);
QCOMPARE(builder.methodCount(), 2);
// Perform index-based lookup
QCOMPARE(builder.indexOfSlot("foo(const QString &, int)"), 0);
QCOMPARE(builder.indexOfSlot("bar(QString)"), 1);
QCOMPARE(builder.indexOfSlot("baz()"), -1);
// Check that nothing else changed.
QVERIFY(checkForSideEffects(builder, QMetaObjectBuilder::Methods));
}
void tst_QMetaObjectBuilder::signal()
{
QMetaObjectBuilder builder;
// Add a signal and check its attributes.
QMetaMethodBuilder method1 = builder.addSignal("foo(const QString&, int)");
QCOMPARE(method1.signature(), QByteArray("foo(QString,int)"));
QVERIFY(method1.methodType() == QMetaMethod::Signal);
QVERIFY(method1.returnType().isEmpty());
QVERIFY(method1.parameterNames().isEmpty());
QVERIFY(method1.tag().isEmpty());
QVERIFY(method1.access() == QMetaMethod::Protected);
QCOMPARE(method1.attributes(), 0);
QCOMPARE(method1.index(), 0);
QCOMPARE(builder.methodCount(), 1);
// Add another signal and check again.
QMetaMethodBuilder method2 = builder.addSignal("bar(QString)");
QCOMPARE(method2.signature(), QByteArray("bar(QString)"));
QVERIFY(method2.methodType() == QMetaMethod::Signal);
QVERIFY(method2.returnType().isEmpty());
QVERIFY(method2.parameterNames().isEmpty());
QVERIFY(method2.tag().isEmpty());
QVERIFY(method2.access() == QMetaMethod::Protected);
QCOMPARE(method2.attributes(), 0);
QCOMPARE(method2.index(), 1);
QCOMPARE(builder.methodCount(), 2);
// Perform index-based lookup
QCOMPARE(builder.indexOfSignal("foo(const QString &, int)"), 0);
QCOMPARE(builder.indexOfSignal("bar(QString)"), 1);
QCOMPARE(builder.indexOfSignal("baz()"), -1);
// Check that nothing else changed.
QVERIFY(checkForSideEffects(builder, QMetaObjectBuilder::Methods));
}
void tst_QMetaObjectBuilder::constructor()
{
QMetaObjectBuilder builder;
// Add a constructor and check its attributes.
QMetaMethodBuilder ctor1 = builder.addConstructor("foo(const QString&, int)");
QCOMPARE(ctor1.signature(), QByteArray("foo(QString,int)"));
QVERIFY(ctor1.methodType() == QMetaMethod::Constructor);
QVERIFY(ctor1.returnType().isEmpty());
QVERIFY(ctor1.parameterNames().isEmpty());
QVERIFY(ctor1.tag().isEmpty());
QVERIFY(ctor1.access() == QMetaMethod::Public);
QCOMPARE(ctor1.attributes(), 0);
QCOMPARE(ctor1.index(), 0);
QCOMPARE(builder.constructorCount(), 1);
// Add another constructor and check again.
QMetaMethodBuilder ctor2 = builder.addConstructor("bar(QString)");
QCOMPARE(ctor2.signature(), QByteArray("bar(QString)"));
QVERIFY(ctor2.methodType() == QMetaMethod::Constructor);
QVERIFY(ctor2.returnType().isEmpty());
QVERIFY(ctor2.parameterNames().isEmpty());
QVERIFY(ctor2.tag().isEmpty());
QVERIFY(ctor2.access() == QMetaMethod::Public);
QCOMPARE(ctor2.attributes(), 0);
QCOMPARE(ctor2.index(), 1);
QCOMPARE(builder.constructorCount(), 2);
// Perform index-based lookup.
QCOMPARE(builder.indexOfConstructor("foo(const QString&, int)"), 0);
QCOMPARE(builder.indexOfConstructor("bar(QString)"), 1);
QCOMPARE(builder.indexOfConstructor("baz()"), -1);
QCOMPARE(builder.constructor(1).signature(), QByteArray("bar(QString)"));
QCOMPARE(builder.constructor(9).signature(), QByteArray());
// Modify the attributes on ctor1.
ctor1.setReturnType("int");
ctor1.setParameterNames(QList<QByteArray>() << "a" << "b");
ctor1.setTag("tag");
ctor1.setAccess(QMetaMethod::Private);
ctor1.setAttributes(42);
// Check that ctor1 is changed, but ctor2 is not.
QCOMPARE(ctor1.signature(), QByteArray("foo(QString,int)"));
QVERIFY(ctor1.methodType() == QMetaMethod::Constructor);
QCOMPARE(ctor1.returnType(), QByteArray("int"));
QCOMPARE(ctor1.parameterNames(), QList<QByteArray>() << "a" << "b");
QCOMPARE(ctor1.tag(), QByteArray("tag"));
QVERIFY(ctor1.access() == QMetaMethod::Private);
QCOMPARE(ctor1.attributes(), 42);
QCOMPARE(ctor1.index(), 0);
QCOMPARE(ctor2.signature(), QByteArray("bar(QString)"));
QVERIFY(ctor2.methodType() == QMetaMethod::Constructor);
QVERIFY(ctor2.returnType().isEmpty());
QVERIFY(ctor2.parameterNames().isEmpty());
QVERIFY(ctor2.tag().isEmpty());
QVERIFY(ctor2.access() == QMetaMethod::Public);
QCOMPARE(ctor2.attributes(), 0);
QCOMPARE(ctor2.index(), 1);
QCOMPARE(builder.constructorCount(), 2);
// Modify the attributes on ctor2.
ctor2.setReturnType("QString");
ctor2.setParameterNames(QList<QByteArray>() << "c");
ctor2.setTag("Q_FOO");
ctor2.setAccess(QMetaMethod::Protected);
ctor2.setAttributes(24);
// This time check that only ctor2 changed.
QCOMPARE(ctor1.signature(), QByteArray("foo(QString,int)"));
QVERIFY(ctor1.methodType() == QMetaMethod::Constructor);
QCOMPARE(ctor1.returnType(), QByteArray("int"));
QCOMPARE(ctor1.parameterNames(), QList<QByteArray>() << "a" << "b");
QCOMPARE(ctor1.tag(), QByteArray("tag"));
QVERIFY(ctor1.access() == QMetaMethod::Private);
QCOMPARE(ctor1.attributes(), 42);
QCOMPARE(ctor1.index(), 0);
QCOMPARE(ctor2.signature(), QByteArray("bar(QString)"));
QVERIFY(ctor2.methodType() == QMetaMethod::Constructor);
QCOMPARE(ctor2.returnType(), QByteArray("QString"));
QCOMPARE(ctor2.parameterNames(), QList<QByteArray>() << "c");
QCOMPARE(ctor2.tag(), QByteArray("Q_FOO"));
QVERIFY(ctor2.access() == QMetaMethod::Protected);
QCOMPARE(ctor2.attributes(), 24);
QCOMPARE(ctor2.index(), 1);
QCOMPARE(builder.constructorCount(), 2);
// Remove ctor1 and check that ctor2 becomes index 0.
builder.removeConstructor(0);
QCOMPARE(builder.constructorCount(), 1);
ctor2 = builder.constructor(0);
QCOMPARE(ctor2.signature(), QByteArray("bar(QString)"));
QVERIFY(ctor2.methodType() == QMetaMethod::Constructor);
QCOMPARE(ctor2.returnType(), QByteArray("QString"));
QCOMPARE(ctor2.parameterNames(), QList<QByteArray>() << "c");
QCOMPARE(ctor2.tag(), QByteArray("Q_FOO"));
QVERIFY(ctor2.access() == QMetaMethod::Protected);
QCOMPARE(ctor2.attributes(), 24);
QCOMPARE(ctor2.index(), 0);
// Perform index-based lookup again.
QCOMPARE(builder.indexOfConstructor("foo(const QString&, int)"), -1);
QCOMPARE(builder.indexOfConstructor("bar(QString)"), 0);
QCOMPARE(builder.indexOfConstructor("baz()"), -1);
// Add constructor from prototype
QMetaMethod prototype = SomethingOfEverything::staticMetaObject.constructor(0);
QMetaMethodBuilder prototypeConstructor = builder.addMethod(prototype);
QCOMPARE(builder.constructorCount(), 2);
QCOMPARE(prototypeConstructor.signature(), QByteArray("SomethingOfEverything()"));
QVERIFY(prototypeConstructor.methodType() == QMetaMethod::Constructor);
QCOMPARE(prototypeConstructor.returnType(), QByteArray());
QVERIFY(prototypeConstructor.access() == QMetaMethod::Public);
QCOMPARE(prototypeConstructor.index(), 1);
// Check that nothing else changed.
QVERIFY(checkForSideEffects(builder, QMetaObjectBuilder::Constructors));
}
void tst_QMetaObjectBuilder::property()
{
QMetaObjectBuilder builder;
// Null property builder
QMetaPropertyBuilder nullProp;
QCOMPARE(nullProp.name(), QByteArray());
QCOMPARE(nullProp.type(), QByteArray());
QVERIFY(!nullProp.hasNotifySignal());
QVERIFY(!nullProp.isReadable());
QVERIFY(!nullProp.isWritable());
QVERIFY(!nullProp.isResettable());
QVERIFY(!nullProp.isDesignable());
QVERIFY(!nullProp.isScriptable());
QVERIFY(!nullProp.isStored());
QVERIFY(!nullProp.isEditable());
QVERIFY(!nullProp.isUser());
QVERIFY(!nullProp.hasStdCppSet());
QVERIFY(!nullProp.isEnumOrFlag());
QVERIFY(!nullProp.isConstant());
QVERIFY(!nullProp.isFinal());
QCOMPARE(nullProp.index(), 0);
// Add a property and check its attributes.
QMetaPropertyBuilder prop1 = builder.addProperty("foo", "const QString &");
QCOMPARE(prop1.name(), QByteArray("foo"));
QCOMPARE(prop1.type(), QByteArray("QString"));
QVERIFY(!prop1.hasNotifySignal());
QVERIFY(prop1.isReadable());
QVERIFY(prop1.isWritable());
QVERIFY(!prop1.isResettable());
QVERIFY(!prop1.isDesignable());
QVERIFY(prop1.isScriptable());
QVERIFY(!prop1.isStored());
QVERIFY(!prop1.isEditable());
QVERIFY(!prop1.isUser());
QVERIFY(!prop1.hasStdCppSet());
QVERIFY(!prop1.isEnumOrFlag());
QVERIFY(!prop1.isConstant());
QVERIFY(!prop1.isFinal());
QCOMPARE(prop1.index(), 0);
QCOMPARE(builder.propertyCount(), 1);
// Add another property and check again.
QMetaPropertyBuilder prop2 = builder.addProperty("bar", "int");
QCOMPARE(prop2.name(), QByteArray("bar"));
QCOMPARE(prop2.type(), QByteArray("int"));
QVERIFY(!prop2.hasNotifySignal());
QVERIFY(prop2.isReadable());
QVERIFY(prop2.isWritable());
QVERIFY(!prop2.isResettable());
QVERIFY(!prop2.isDesignable());
QVERIFY(prop2.isScriptable());
QVERIFY(!prop2.isStored());
QVERIFY(!prop2.isEditable());
QVERIFY(!prop2.isUser());
QVERIFY(!prop2.hasStdCppSet());
QVERIFY(!prop2.isEnumOrFlag());
QVERIFY(!prop2.isConstant());
QVERIFY(!prop2.isFinal());
QCOMPARE(prop2.index(), 1);
QCOMPARE(builder.propertyCount(), 2);
// Perform index-based lookup.
QCOMPARE(builder.indexOfProperty("foo"), 0);
QCOMPARE(builder.indexOfProperty("bar"), 1);
QCOMPARE(builder.indexOfProperty("baz"), -1);
QCOMPARE(builder.property(1).name(), QByteArray("bar"));
QCOMPARE(builder.property(9).name(), QByteArray());
// Modify the attributes on prop1.
prop1.setReadable(false);
prop1.setWritable(false);
prop1.setResettable(true);
prop1.setDesignable(true);
prop1.setScriptable(false);
prop1.setStored(true);
prop1.setEditable(true);
prop1.setUser(true);
prop1.setStdCppSet(true);
prop1.setEnumOrFlag(true);
prop1.setConstant(true);
prop1.setFinal(true);
// Check that prop1 is changed, but prop2 is not.
QCOMPARE(prop1.name(), QByteArray("foo"));
QCOMPARE(prop1.type(), QByteArray("QString"));
QVERIFY(!prop1.isReadable());
QVERIFY(!prop1.isWritable());
QVERIFY(prop1.isResettable());
QVERIFY(prop1.isDesignable());
QVERIFY(!prop1.isScriptable());
QVERIFY(prop1.isStored());
QVERIFY(prop1.isEditable());
QVERIFY(prop1.isUser());
QVERIFY(prop1.hasStdCppSet());
QVERIFY(prop1.isEnumOrFlag());
QVERIFY(prop1.isConstant());
QVERIFY(prop1.isFinal());
QVERIFY(prop2.isReadable());
QVERIFY(prop2.isWritable());
QCOMPARE(prop2.name(), QByteArray("bar"));
QCOMPARE(prop2.type(), QByteArray("int"));
QVERIFY(!prop2.isResettable());
QVERIFY(!prop2.isDesignable());
QVERIFY(prop2.isScriptable());
QVERIFY(!prop2.isStored());
QVERIFY(!prop2.isEditable());
QVERIFY(!prop2.isUser());
QVERIFY(!prop2.hasStdCppSet());
QVERIFY(!prop2.isEnumOrFlag());
QVERIFY(!prop2.isConstant());
QVERIFY(!prop2.isFinal());
// Remove prop1 and check that prop2 becomes index 0.
builder.removeProperty(0);
QCOMPARE(builder.propertyCount(), 1);
prop2 = builder.property(0);
QCOMPARE(prop2.name(), QByteArray("bar"));
QCOMPARE(prop2.type(), QByteArray("int"));
QVERIFY(!prop2.isResettable());
QVERIFY(!prop2.isDesignable());
QVERIFY(prop2.isScriptable());
QVERIFY(!prop2.isStored());
QVERIFY(!prop2.isEditable());
QVERIFY(!prop2.isUser());
QVERIFY(!prop2.hasStdCppSet());
QVERIFY(!prop2.isEnumOrFlag());
QVERIFY(!prop2.isConstant());
QVERIFY(!prop2.isFinal());
QCOMPARE(prop2.index(), 0);
// Perform index-based lookup again.
QCOMPARE(builder.indexOfProperty("foo"), -1);
QCOMPARE(builder.indexOfProperty("bar"), 0);
QCOMPARE(builder.indexOfProperty("baz"), -1);
// Check for side-effects between the flags on prop2.
// Setting a flag to true shouldn't set any of the others to true.
// This checks for cut-and-paste bugs in the implementation where
// the flag code was pasted but the flag name was not changed.
#define CLEAR_FLAGS() \
do { \
prop2.setReadable(false); \
prop2.setWritable(false); \
prop2.setResettable(false); \
prop2.setDesignable(false); \
prop2.setScriptable(false); \
prop2.setStored(false); \
prop2.setEditable(false); \
prop2.setUser(false); \
prop2.setStdCppSet(false); \
prop2.setEnumOrFlag(false); \
prop2.setConstant(false); \
prop2.setFinal(false); \
} while (0)
#define COUNT_FLAGS() \
((prop2.isReadable() ? 1 : 0) + \
(prop2.isWritable() ? 1 : 0) + \
(prop2.isResettable() ? 1 : 0) + \
(prop2.isDesignable() ? 1 : 0) + \
(prop2.isScriptable() ? 1 : 0) + \
(prop2.isStored() ? 1 : 0) + \
(prop2.isEditable() ? 1 : 0) + \
(prop2.isUser() ? 1 : 0) + \
(prop2.hasStdCppSet() ? 1 : 0) + \
(prop2.isEnumOrFlag() ? 1 : 0) + \
(prop2.isConstant() ? 1 : 0) + \
(prop2.isFinal() ? 1 : 0))
#define CHECK_FLAG(setFunc,isFunc) \
do { \
CLEAR_FLAGS(); \
QCOMPARE(COUNT_FLAGS(), 0); \
prop2.setFunc(true); \
QVERIFY(prop2.isFunc()); \
QCOMPARE(COUNT_FLAGS(), 1); \
} while (0)
CHECK_FLAG(setReadable, isReadable);
CHECK_FLAG(setWritable, isWritable);
CHECK_FLAG(setResettable, isResettable);
CHECK_FLAG(setDesignable, isDesignable);
CHECK_FLAG(setScriptable, isScriptable);
CHECK_FLAG(setStored, isStored);
CHECK_FLAG(setEditable, isEditable);
CHECK_FLAG(setUser, isUser);
CHECK_FLAG(setStdCppSet, hasStdCppSet);
CHECK_FLAG(setEnumOrFlag, isEnumOrFlag);
CHECK_FLAG(setConstant, isConstant);
CHECK_FLAG(setFinal, isFinal);
// Check that nothing else changed.
QVERIFY(checkForSideEffects(builder, QMetaObjectBuilder::Properties));
// Add property from prototype
QMetaProperty prototype = SomethingOfEverything::staticMetaObject.property(1);
QVERIFY(prototype.name() == QByteArray("prop"));
QMetaPropertyBuilder prototypeProp = builder.addProperty(prototype);
QCOMPARE(prototypeProp.name(), QByteArray("prop"));
QVERIFY(prototypeProp.hasNotifySignal());
QCOMPARE(prototypeProp.notifySignal().signature(), QByteArray("propChanged(QString)"));
QCOMPARE(builder.methodCount(), 1);
QCOMPARE(builder.method(0).signature(), QByteArray("propChanged(QString)"));
}
void tst_QMetaObjectBuilder::notifySignal()
{
QMetaObjectBuilder builder;
QMetaPropertyBuilder prop = builder.addProperty("foo", "const QString &");
builder.addSlot("setFoo(QString)");
QMetaMethodBuilder notify = builder.addSignal("fooChanged(QString)");
QVERIFY(!prop.hasNotifySignal());
QCOMPARE(prop.notifySignal().index(), 0);
prop.setNotifySignal(notify);
QVERIFY(prop.hasNotifySignal());
QCOMPARE(prop.notifySignal().index(), 1);
prop.setNotifySignal(QMetaMethodBuilder());
QVERIFY(!prop.hasNotifySignal());
QCOMPARE(prop.notifySignal().index(), 0);
prop.setNotifySignal(notify);
prop.removeNotifySignal();
QVERIFY(!prop.hasNotifySignal());
QCOMPARE(prop.notifySignal().index(), 0);
QCOMPARE(builder.methodCount(), 2);
QCOMPARE(builder.propertyCount(), 1);
// Check that nothing else changed except methods and properties.
QVERIFY(checkForSideEffects
(builder, QMetaObjectBuilder::Methods | QMetaObjectBuilder::Properties));
}
void tst_QMetaObjectBuilder::enumerator()
{
QMetaObjectBuilder builder;
// Add an enumerator and check its attributes.
QMetaEnumBuilder enum1 = builder.addEnumerator("foo");
QCOMPARE(enum1.name(), QByteArray("foo"));
QVERIFY(!enum1.isFlag());
QCOMPARE(enum1.keyCount(), 0);
QCOMPARE(enum1.index(), 0);
QCOMPARE(builder.enumeratorCount(), 1);
// Add another enumerator and check again.
QMetaEnumBuilder enum2 = builder.addEnumerator("bar");
QCOMPARE(enum2.name(), QByteArray("bar"));
QVERIFY(!enum2.isFlag());
QCOMPARE(enum2.keyCount(), 0);
QCOMPARE(enum2.index(), 1);
QCOMPARE(builder.enumeratorCount(), 2);
// Perform index-based lookup.
QCOMPARE(builder.indexOfEnumerator("foo"), 0);
QCOMPARE(builder.indexOfEnumerator("bar"), 1);
QCOMPARE(builder.indexOfEnumerator("baz"), -1);
QCOMPARE(builder.enumerator(1).name(), QByteArray("bar"));
QCOMPARE(builder.enumerator(9).name(), QByteArray());
// Modify the attributes on enum1.
enum1.setIsFlag(true);
QCOMPARE(enum1.addKey("ABC", 0), 0);
QCOMPARE(enum1.addKey("DEF", 1), 1);
QCOMPARE(enum1.addKey("GHI", -1), 2);
// Check that enum1 is changed, but enum2 is not.
QCOMPARE(enum1.name(), QByteArray("foo"));
QVERIFY(enum1.isFlag());
QCOMPARE(enum1.keyCount(), 3);
QCOMPARE(enum1.index(), 0);
QCOMPARE(enum1.key(0), QByteArray("ABC"));
QCOMPARE(enum1.key(1), QByteArray("DEF"));
QCOMPARE(enum1.key(2), QByteArray("GHI"));
QCOMPARE(enum1.key(3), QByteArray());
QCOMPARE(enum1.value(0), 0);
QCOMPARE(enum1.value(1), 1);
QCOMPARE(enum1.value(2), -1);
QCOMPARE(enum2.name(), QByteArray("bar"));
QVERIFY(!enum2.isFlag());
QCOMPARE(enum2.keyCount(), 0);
QCOMPARE(enum2.index(), 1);
// Modify the attributes on enum2.
enum2.setIsFlag(true);
QCOMPARE(enum2.addKey("XYZ", 10), 0);
QCOMPARE(enum2.addKey("UVW", 19), 1);
// This time check that only method2 changed.
QCOMPARE(enum1.name(), QByteArray("foo"));
QVERIFY(enum1.isFlag());
QCOMPARE(enum1.keyCount(), 3);
QCOMPARE(enum1.index(), 0);
QCOMPARE(enum1.key(0), QByteArray("ABC"));
QCOMPARE(enum1.key(1), QByteArray("DEF"));
QCOMPARE(enum1.key(2), QByteArray("GHI"));
QCOMPARE(enum1.key(3), QByteArray());
QCOMPARE(enum1.value(0), 0);
QCOMPARE(enum1.value(1), 1);
QCOMPARE(enum1.value(2), -1);
QCOMPARE(enum2.name(), QByteArray("bar"));
QVERIFY(enum2.isFlag());
QCOMPARE(enum2.keyCount(), 2);
QCOMPARE(enum2.index(), 1);
QCOMPARE(enum2.key(0), QByteArray("XYZ"));
QCOMPARE(enum2.key(1), QByteArray("UVW"));
QCOMPARE(enum2.key(2), QByteArray());
QCOMPARE(enum2.value(0), 10);
QCOMPARE(enum2.value(1), 19);
// Remove enum1 key
enum1.removeKey(2);
QCOMPARE(enum1.name(), QByteArray("foo"));
QVERIFY(enum1.isFlag());
QCOMPARE(enum1.keyCount(), 2);
QCOMPARE(enum1.index(), 0);
QCOMPARE(enum1.key(0), QByteArray("ABC"));
QCOMPARE(enum1.key(1), QByteArray("DEF"));
QCOMPARE(enum1.key(2), QByteArray());
QCOMPARE(enum1.value(0), 0);
QCOMPARE(enum1.value(1), 1);
QCOMPARE(enum1.value(2), -1);
QCOMPARE(enum2.name(), QByteArray("bar"));
QVERIFY(enum2.isFlag());
QCOMPARE(enum2.keyCount(), 2);
QCOMPARE(enum2.index(), 1);
QCOMPARE(enum2.key(0), QByteArray("XYZ"));
QCOMPARE(enum2.key(1), QByteArray("UVW"));
QCOMPARE(enum2.key(2), QByteArray());
QCOMPARE(enum2.value(0), 10);
QCOMPARE(enum2.value(1), 19);
// Remove enum1 and check that enum2 becomes index 0.
builder.removeEnumerator(0);
QCOMPARE(builder.enumeratorCount(), 1);
enum2 = builder.enumerator(0);
QCOMPARE(enum2.name(), QByteArray("bar"));
QVERIFY(enum2.isFlag());
QCOMPARE(enum2.keyCount(), 2);
QCOMPARE(enum2.index(), 0);
QCOMPARE(enum2.key(0), QByteArray("XYZ"));
QCOMPARE(enum2.key(1), QByteArray("UVW"));
QCOMPARE(enum2.key(2), QByteArray());
QCOMPARE(enum2.value(0), 10);
QCOMPARE(enum2.value(1), 19);
// Perform index-based lookup again.
QCOMPARE(builder.indexOfEnumerator("foo"), -1);
QCOMPARE(builder.indexOfEnumerator("bar"), 0);
QCOMPARE(builder.indexOfEnumerator("baz"), -1);
// Check that nothing else changed.
QVERIFY(checkForSideEffects(builder, QMetaObjectBuilder::Enumerators));
}
void tst_QMetaObjectBuilder::classInfo()
{
QMetaObjectBuilder builder;
// Add two items of class information and check their attributes.
QCOMPARE(builder.addClassInfo("foo", "value1"), 0);
QCOMPARE(builder.addClassInfo("bar", "value2"), 1);
QCOMPARE(builder.classInfoName(0), QByteArray("foo"));
QCOMPARE(builder.classInfoValue(0), QByteArray("value1"));
QCOMPARE(builder.classInfoName(1), QByteArray("bar"));
QCOMPARE(builder.classInfoValue(1), QByteArray("value2"));
QCOMPARE(builder.classInfoName(9), QByteArray());
QCOMPARE(builder.classInfoValue(9), QByteArray());
QCOMPARE(builder.classInfoCount(), 2);
// Perform index-based lookup.
QCOMPARE(builder.indexOfClassInfo("foo"), 0);
QCOMPARE(builder.indexOfClassInfo("bar"), 1);
QCOMPARE(builder.indexOfClassInfo("baz"), -1);
// Remove the first one and check again.
builder.removeClassInfo(0);
QCOMPARE(builder.classInfoName(0), QByteArray("bar"));
QCOMPARE(builder.classInfoValue(0), QByteArray("value2"));
QCOMPARE(builder.classInfoCount(), 1);
// Perform index-based lookup again.
QCOMPARE(builder.indexOfClassInfo("foo"), -1);
QCOMPARE(builder.indexOfClassInfo("bar"), 0);
QCOMPARE(builder.indexOfClassInfo("baz"), -1);
// Check that nothing else changed.
QVERIFY(checkForSideEffects(builder, QMetaObjectBuilder::ClassInfos));
}
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject& staticMetaObjectGlobal()
{
return QObject::staticMetaObject;
}
const QMetaObject& staticMetaObjectLocal()
{
return *meta;
}
#endif
void tst_QMetaObjectBuilder::relatedMetaObject()
{
QMetaObjectBuilder builder;
// Add two related meta objects and check their attributes.
#ifdef Q_NO_DATA_RELOCATION
meta = &staticMetaObject;
QCOMPARE(builder.addRelatedMetaObject(&staticMetaObjectGlobal), 0);
QCOMPARE(builder.addRelatedMetaObject(&staticMetaObjectLocal), 1);
#else
QCOMPARE(builder.addRelatedMetaObject(&QObject::staticMetaObject), 0);
QCOMPARE(builder.addRelatedMetaObject(&staticMetaObject), 1);
#endif
QVERIFY(builder.relatedMetaObject(0) == &QObject::staticMetaObject);
QVERIFY(builder.relatedMetaObject(1) == &staticMetaObject);
QCOMPARE(builder.relatedMetaObjectCount(), 2);
// Remove the first one and check again.
builder.removeRelatedMetaObject(0);
QVERIFY(builder.relatedMetaObject(0) == &staticMetaObject);
QCOMPARE(builder.relatedMetaObjectCount(), 1);
// Check that nothing else changed.
QVERIFY(checkForSideEffects(builder, QMetaObjectBuilder::RelatedMetaObjects));
}
static void smetacall(QObject *, QMetaObject::Call, int, void **)
{
return;
}
void tst_QMetaObjectBuilder::staticMetacall()
{
QMetaObjectBuilder builder;
QVERIFY(!builder.staticMetacallFunction());
builder.setStaticMetacallFunction(smetacall);
QVERIFY(builder.staticMetacallFunction() == smetacall);
QVERIFY(checkForSideEffects(builder, QMetaObjectBuilder::StaticMetacall));
}
// Copy the entire contents of a static QMetaObject and then check
// that QMetaObjectBuilder will produce an exact copy as output.
void tst_QMetaObjectBuilder::copyMetaObject()
{
QMetaObjectBuilder builder(&QObject::staticMetaObject);
QMetaObject *meta = builder.toMetaObject();
QVERIFY(sameMetaObject(meta, &QObject::staticMetaObject));
qFree(meta);
QMetaObjectBuilder builder2(&staticMetaObject);
meta = builder2.toMetaObject();
QVERIFY(sameMetaObject(meta, &staticMetaObject));
qFree(meta);
QMetaObjectBuilder builder3(&SomethingOfEverything::staticMetaObject);
meta = builder3.toMetaObject();
QVERIFY(sameMetaObject(meta, &SomethingOfEverything::staticMetaObject));
qFree(meta);
}
// Serialize and deserialize a meta object and check that
// it round-trips to the exact same value.
void tst_QMetaObjectBuilder::serialize()
{
// Full QMetaObjectBuilder
{
QMetaObjectBuilder builder(&SomethingOfEverything::staticMetaObject);
QMetaObject *meta = builder.toMetaObject();
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly | QIODevice::Append);
builder.serialize(stream);
QMetaObjectBuilder builder2;
QDataStream stream2(data);
QMap<QByteArray, const QMetaObject *> references;
references.insert(QByteArray("QLocale"), &QLocale::staticMetaObject);
builder2.deserialize(stream2, references);
#ifdef Q_NO_DATA_RELOCATION
//the related meta objects will be function pointers
//which you have to add to the builder manually.
builder2.addRelatedMetaObject(QLocale::getStaticMetaObject);
#endif
builder2.setStaticMetacallFunction(builder.staticMetacallFunction());
QMetaObject *meta2 = builder2.toMetaObject();
QVERIFY(sameMetaObject(meta, meta2));
qFree(meta);
qFree(meta2);
}
// Partial QMetaObjectBuilder
{
QMetaObjectBuilder builder;
builder.setClassName("Test");
builder.addProperty("foo", "int");
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly | QIODevice::Append);
builder.serialize(stream);
QMetaObjectBuilder builder2;
QDataStream stream2(data);
builder2.deserialize(stream2, QMap<QByteArray, const QMetaObject *>());
QCOMPARE(builder.superClass(), builder2.superClass());
QCOMPARE(builder.className(), builder2.className());
QCOMPARE(builder.propertyCount(), builder2.propertyCount());
QCOMPARE(builder.property(0).name(), builder2.property(0).name());
QCOMPARE(builder.property(0).type(), builder2.property(0).type());
}
}
// Check that removing a method updates notify signals appropriately
void tst_QMetaObjectBuilder::removeNotifySignal()
{
QMetaObjectBuilder builder;
QMetaMethodBuilder method1 = builder.addSignal("foo(const QString&, int)");
QMetaMethodBuilder method2 = builder.addSignal("bar(QString)");
// Setup property
QMetaPropertyBuilder prop = builder.addProperty("prop", "const QString &");
prop.setNotifySignal(method2);
QVERIFY(prop.hasNotifySignal());
QCOMPARE(prop.notifySignal().index(), 1);
// Remove non-notify signal
builder.removeMethod(0);
QVERIFY(prop.hasNotifySignal());
QCOMPARE(prop.notifySignal().index(), 0);
// Remove notify signal
builder.removeMethod(0);
QVERIFY(!prop.hasNotifySignal());
}
// Check that the only changes to a "builder" relative to the default
// state is specified by "members".
bool tst_QMetaObjectBuilder::checkForSideEffects
(const QMetaObjectBuilder& builder,
QMetaObjectBuilder::AddMembers members)
{
if ((members & QMetaObjectBuilder::ClassName) == 0) {
if (!builder.className().isEmpty())
return false;
}
if ((members & QMetaObjectBuilder::SuperClass) == 0) {
if (builder.superClass() != &QObject::staticMetaObject)
return false;
}
if ((members & QMetaObjectBuilder::Methods) == 0) {
if (builder.methodCount() != 0)
return false;
}
if ((members & QMetaObjectBuilder::Constructors) == 0) {
if (builder.constructorCount() != 0)
return false;
}
if ((members & QMetaObjectBuilder::Properties) == 0) {
if (builder.propertyCount() != 0)
return false;
}
if ((members & QMetaObjectBuilder::Enumerators) == 0) {
if (builder.enumeratorCount() != 0)
return false;
}
if ((members & QMetaObjectBuilder::ClassInfos) == 0) {
if (builder.classInfoCount() != 0)
return false;
}
if ((members & QMetaObjectBuilder::RelatedMetaObjects) == 0) {
if (builder.relatedMetaObjectCount() != 0)
return false;
}
if ((members & QMetaObjectBuilder::StaticMetacall) == 0) {
if (builder.staticMetacallFunction() != 0)
return false;
}
return true;
}
static bool sameMethod(const QMetaMethod& method1, const QMetaMethod& method2)
{
if (QByteArray(method1.signature()) != QByteArray(method2.signature()))
return false;
if (QByteArray(method1.typeName()) != QByteArray(method2.typeName()))
return false;
if (method1.parameterNames() != method2.parameterNames())
return false;
if (QByteArray(method1.tag()) != QByteArray(method2.tag()))
return false;
if (method1.access() != method2.access())
return false;
if (method1.methodType() != method2.methodType())
return false;
if (method1.attributes() != method2.attributes())
return false;
return true;
}
static bool sameProperty(const QMetaProperty& prop1, const QMetaProperty& prop2)
{
if (QByteArray(prop1.name()) != QByteArray(prop2.name()))
return false;
if (QByteArray(prop1.typeName()) != QByteArray(prop2.typeName()))
return false;
if (prop1.isReadable() != prop2.isReadable() ||
prop1.isWritable() != prop2.isWritable() ||
prop1.isResettable() != prop2.isResettable() ||
prop1.isDesignable() != prop2.isDesignable() ||
prop1.isScriptable() != prop2.isScriptable() ||
prop1.isStored() != prop2.isStored() ||
prop1.isEditable() != prop2.isEditable() ||
prop1.isUser() != prop2.isUser() ||
prop1.isFlagType() != prop2.isFlagType() ||
prop1.isEnumType() != prop2.isEnumType() ||
prop1.hasNotifySignal() != prop2.hasNotifySignal() ||
prop1.hasStdCppSet() != prop2.hasStdCppSet())
return false;
if (prop1.hasNotifySignal()) {
if (prop1.notifySignalIndex() != prop2.notifySignalIndex())
return false;
}
return true;
}
static bool sameEnumerator(const QMetaEnum& enum1, const QMetaEnum& enum2)
{
if (QByteArray(enum1.name()) != QByteArray(enum2.name()))
return false;
if (enum1.isFlag() != enum2.isFlag())
return false;
if (enum1.keyCount() != enum2.keyCount())
return false;
for (int index = 0; index < enum1.keyCount(); ++index) {
if (QByteArray(enum1.key(index)) != QByteArray(enum2.key(index)))
return false;
if (enum1.value(index) != enum2.value(index))
return false;
}
if (QByteArray(enum1.scope()) != QByteArray(enum2.scope()))
return false;
return true;
}
// Determine if two meta objects are identical.
bool tst_QMetaObjectBuilder::sameMetaObject
(const QMetaObject *meta1, const QMetaObject *meta2)
{
int index;
if (strcmp(meta1->className(), meta2->className()) != 0)
return false;
if (meta1->superClass() != meta2->superClass())
return false;
if (meta1->constructorCount() != meta2->constructorCount() ||
meta1->methodCount() != meta2->methodCount() ||
meta1->enumeratorCount() != meta2->enumeratorCount() ||
meta1->propertyCount() != meta2->propertyCount() ||
meta1->classInfoCount() != meta2->classInfoCount())
return false;
for (index = 0; index < meta1->constructorCount(); ++index) {
if (!sameMethod(meta1->constructor(index), meta2->constructor(index)))
return false;
}
for (index = 0; index < meta1->methodCount(); ++index) {
if (!sameMethod(meta1->method(index), meta2->method(index)))
return false;
}
for (index = 0; index < meta1->propertyCount(); ++index) {
if (!sameProperty(meta1->property(index), meta2->property(index)))
return false;
}
for (index = 0; index < meta1->enumeratorCount(); ++index) {
if (!sameEnumerator(meta1->enumerator(index), meta2->enumerator(index)))
return false;
}
for (index = 0; index < meta1->classInfoCount(); ++index) {
if (QByteArray(meta1->classInfo(index).name()) !=
QByteArray(meta2->classInfo(index).name()))
return false;
if (QByteArray(meta1->classInfo(index).value()) !=
QByteArray(meta2->classInfo(index).value()))
return false;
}
const QMetaObject **objects1 = 0;
const QMetaObject **objects2 = 0;
if (meta1->d.data[0] == meta2->d.data[0] && meta1->d.data[0] >= 2) {
QMetaObjectExtraData *extra1 = (QMetaObjectExtraData *)(meta1->d.extradata);
QMetaObjectExtraData *extra2 = (QMetaObjectExtraData *)(meta2->d.extradata);
if (extra1 && !extra2)
return false;
if (extra2 && !extra1)
return false;
if (extra1 && extra2) {
if (extra1->static_metacall != extra2->static_metacall)
return false;
objects1 = extra1->objects;
objects2 = extra1->objects;
}
} else if (meta1->d.data[0] == meta2->d.data[0] && meta1->d.data[0] == 1) {
objects1 = (const QMetaObject **)(meta1->d.extradata);
objects2 = (const QMetaObject **)(meta2->d.extradata);
}
if (objects1 && !objects2)
return false;
if (objects2 && !objects1)
return false;
if (objects1 && objects2) {
while (*objects1 != 0 && *objects2 != 0) {
if (*objects1 != *objects2)
return false;
++objects1;
++objects2;
}
}
return true;
}
QTEST_MAIN(tst_QMetaObjectBuilder)
#include "tst_qmetaobjectbuilder.moc"
|
kaltsi/qt-mobility
|
tests/auto/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp
|
C++
|
lgpl-2.1
| 46,806
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qgeomapitemgeometry_p.h"
#include "qdeclarativegeomap_p.h"
#include "qlocationutils_p.h"
#include <QtQuick/QSGGeometry>
QT_BEGIN_NAMESPACE
QGeoMapItemGeometry::QGeoMapItemGeometry(QObject *parent) :
QObject(parent),
sourceDirty_(true),
screenDirty_(true),
clipToViewport_(true),
preserveGeometry_(false)
{
}
/*!
\internal
*/
void QGeoMapItemGeometry::translate(const QPointF &offset)
{
for (int i = 0; i < screenVertices_.size(); ++i) {
screenVertices_[i].x += offset.x();
screenVertices_[i].y += offset.y();
}
firstPointOffset_ += offset;
screenOutline_.translate(offset);
screenBounds_.translate(offset);
}
/*!
\internal
*/
void QGeoMapItemGeometry::allocateAndFill(QSGGeometry *geom) const
{
const QVector<QGeoMapItemGeometry::Point> &vx = screenVertices_;
const QVector<quint32> &ix = screenIndices_;
if (isIndexed()) {
geom->allocate(vx.size(), ix.size());
if (geom->indexType() == GL_UNSIGNED_SHORT) {
quint16 *its = geom->indexDataAsUShort();
for (int i = 0; i < ix.size(); ++i)
its[i] = ix[i];
} else if (geom->indexType() == GL_UNSIGNED_INT) {
quint32 *its = geom->indexDataAsUInt();
for (int i = 0; i < ix.size(); ++i)
its[i] = ix[i];
}
} else {
geom->allocate(vx.size());
}
QSGGeometry::Point2D *pts = geom->vertexDataAsPoint2D();
for (int i = 0; i < vx.size(); ++i)
pts[i].set(vx[i].x, vx[i].y);
}
/*!
\internal
*/
QRectF QGeoMapItemGeometry::translateToCommonOrigin(const QList<QGeoMapItemGeometry *> &geoms)
{
QGeoCoordinate origin = geoms.at(0)->origin();
QPainterPath brects;
// first get max offset
QPointF maxOffset = geoms.at(0)->firstPointOffset();
foreach (QGeoMapItemGeometry *g, geoms) {
Q_ASSERT(g->origin() == origin);
QPointF o = g->firstPointOffset();
maxOffset.setX(qMax(o.x(), maxOffset.x()));
maxOffset.setY(qMax(o.y(), maxOffset.y()));
}
// then translate everything
foreach (QGeoMapItemGeometry *g, geoms) {
g->translate(maxOffset - g->firstPointOffset());
brects.addRect(g->sourceBoundingBox());
}
return brects.boundingRect();
}
/*!
\internal
*/
double QGeoMapItemGeometry::geoDistanceToScreenWidth(const QGeoMap &map,
const QGeoCoordinate &fromCoord,
const QGeoCoordinate &toCoord)
{
QGeoCoordinate mapMid = map.screenPositionToCoordinate(QPointF(map.width()/2.0, 0));
double halfGeoDist = toCoord.longitude() - fromCoord.longitude();
if (toCoord.longitude() < fromCoord.longitude())
halfGeoDist += 360;
halfGeoDist /= 2.0;
QGeoCoordinate geoDelta = QGeoCoordinate(0,
QLocationUtils::wrapLong(mapMid.longitude() + halfGeoDist));
QPointF halfScreenDist = map.coordinateToScreenPosition(geoDelta, false)
- QPointF(map.width()/2.0, 0);
return halfScreenDist.x() * 2.0;
}
QT_END_NAMESPACE
|
kobolabs/qtlocation
|
src/imports/location/qgeomapitemgeometry.cpp
|
C++
|
lgpl-2.1
| 5,127
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>Content-Centric Networking in Java: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<!-- Generated by Doxygen 1.6.3 -->
<div class="navigation" id="top">
<div class="tabs">
<ul>
<li><a href="main.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="namespaces.html"><span>Packages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div>
<div class="contents">
<h1>org.ccnx.ccn.test.BenchmarkTest.Operation< T extends Object, U extends Object > Member List</h1>This is the complete list of members for <a class="el" href="classorg_1_1ccnx_1_1ccn_1_1test_1_1_benchmark_test_1_1_operation_3_01_t_01extends_01_object_00_01_u_01extends_01_object_01_4.html">org.ccnx.ccn.test.BenchmarkTest.Operation< T extends Object, U extends Object ></a>, including all inherited members.<table>
<tr bgcolor="#f0f0f0"><td><b>execute</b>(T input, U parameter) (defined in <a class="el" href="classorg_1_1ccnx_1_1ccn_1_1test_1_1_benchmark_test_1_1_operation_3_01_t_01extends_01_object_00_01_u_01extends_01_object_01_4.html">org.ccnx.ccn.test.BenchmarkTest.Operation< T extends Object, U extends Object ></a>)</td><td><a class="el" href="classorg_1_1ccnx_1_1ccn_1_1test_1_1_benchmark_test_1_1_operation_3_01_t_01extends_01_object_00_01_u_01extends_01_object_01_4.html">org.ccnx.ccn.test.BenchmarkTest.Operation< T extends Object, U extends Object ></a></td><td><code> [package, pure virtual]</code></td></tr>
<tr bgcolor="#f0f0f0"><td><b>runBenchmark</b>(String desc, T input, U parameter) (defined in <a class="el" href="classorg_1_1ccnx_1_1ccn_1_1test_1_1_benchmark_test_1_1_operation_3_01_t_01extends_01_object_00_01_u_01extends_01_object_01_4.html">org.ccnx.ccn.test.BenchmarkTest.Operation< T extends Object, U extends Object ></a>)</td><td><a class="el" href="classorg_1_1ccnx_1_1ccn_1_1test_1_1_benchmark_test_1_1_operation_3_01_t_01extends_01_object_00_01_u_01extends_01_object_01_4.html">org.ccnx.ccn.test.BenchmarkTest.Operation< T extends Object, U extends Object ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>runBenchmark</b>(int count, String desc, T input, U parameter) (defined in <a class="el" href="classorg_1_1ccnx_1_1ccn_1_1test_1_1_benchmark_test_1_1_operation_3_01_t_01extends_01_object_00_01_u_01extends_01_object_01_4.html">org.ccnx.ccn.test.BenchmarkTest.Operation< T extends Object, U extends Object ></a>)</td><td><a class="el" href="classorg_1_1ccnx_1_1ccn_1_1test_1_1_benchmark_test_1_1_operation_3_01_t_01extends_01_object_00_01_u_01extends_01_object_01_4.html">org.ccnx.ccn.test.BenchmarkTest.Operation< T extends Object, U extends Object ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>size</b>(T input) (defined in <a class="el" href="classorg_1_1ccnx_1_1ccn_1_1test_1_1_benchmark_test_1_1_operation_3_01_t_01extends_01_object_00_01_u_01extends_01_object_01_4.html">org.ccnx.ccn.test.BenchmarkTest.Operation< T extends Object, U extends Object ></a>)</td><td><a class="el" href="classorg_1_1ccnx_1_1ccn_1_1test_1_1_benchmark_test_1_1_operation_3_01_t_01extends_01_object_00_01_u_01extends_01_object_01_4.html">org.ccnx.ccn.test.BenchmarkTest.Operation< T extends Object, U extends Object ></a></td><td><code> [package]</code></td></tr>
</table></div>
<hr class="footer"/><address style="text-align: right;"><small>Generated on Mon Feb 4 11:59:04 2013 for Content-Centric Networking in Java by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.6.3 </small></address>
</body>
</html>
|
StefanoSalsano/alien-ofelia-conet-ccnx
|
doc/javacode/html/classorg_1_1ccnx_1_1ccn_1_1test_1_1_benchmark_test_1_1_operation_3_01_t_01extends_01_object_00_0700ec2693528f00cde31da0bc2e26cdc.html
|
HTML
|
lgpl-2.1
| 4,324
|
/*
* This program source code file is part of KiCad, a free EDA CAD application.
*
* Copyright (C) 1992-2010 <Jean-Pierre Charras>
* Copyright (C) 1992-2010 KiCad Developers, see change_log.txt for contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
/**
* @file gerbview/controle.cpp
*/
#include <fctsys.h>
#include <common.h>
#include <class_drawpanel.h>
#include <gerbview.h>
void GERBVIEW_FRAME::GeneralControl( wxDC* aDC, const wxPoint& aPosition, int aHotKey )
{
wxRealPoint gridSize;
wxPoint oldpos;
wxPoint pos = aPosition;
pos = GetScreen()->GetNearestGridPosition( pos );
oldpos = GetScreen()->GetCrossHairPosition();
gridSize = GetScreen()->GetGridSize();
switch( aHotKey )
{
case WXK_NUMPAD8:
case WXK_UP:
pos.y -= KiROUND( gridSize.y );
m_canvas->MoveCursor( pos );
break;
case WXK_NUMPAD2:
case WXK_DOWN:
pos.y += KiROUND( gridSize.y );
m_canvas->MoveCursor( pos );
break;
case WXK_NUMPAD4:
case WXK_LEFT:
pos.x -= KiROUND( gridSize.x );
m_canvas->MoveCursor( pos );
break;
case WXK_NUMPAD6:
case WXK_RIGHT:
pos.x += KiROUND( gridSize.x );
m_canvas->MoveCursor( pos );
break;
default:
break;
}
GetScreen()->SetCrossHairPosition( pos );
if( oldpos != GetScreen()->GetCrossHairPosition() )
{
pos = GetScreen()->GetCrossHairPosition();
GetScreen()->SetCrossHairPosition( oldpos );
m_canvas->CrossHairOff( aDC );
GetScreen()->SetCrossHairPosition( pos );
m_canvas->CrossHairOn( aDC );
if( m_canvas->IsMouseCaptured() )
{
#ifdef USE_WX_OVERLAY
wxDCOverlay oDC( m_overlay, (wxWindowDC*)aDC );
oDC.Clear();
m_canvas->CallMouseCapture( aDC, aPosition, false );
#else
m_canvas->CallMouseCapture( aDC, aPosition, true );
#endif
}
#ifdef USE_WX_OVERLAY
else
{
m_overlay.Reset();
}
#endif
}
if( aHotKey )
{
OnHotKey( aDC, aHotKey, aPosition );
}
UpdateStatusBar();
}
|
peabody124/kicad
|
gerbview/controle.cpp
|
C++
|
lgpl-2.1
| 3,023
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>CQRS.NET: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">CQRS.NET
 <span id="projectnumber">2.0</span>
</div>
<div id="projectbrief">A lightweight enterprise framework to write CQRS, event-sourced and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('classCqrs_1_1Ninject_1_1Azure_1_1ServiceBus_1_1EventBus_1_1Configuration_1_1AzureEventPublisherModule.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">Cqrs.Ninject.Azure.ServiceBus.EventBus.Configuration.AzureEventPublisherModule< TAuthenticationToken > Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1ServiceBus_1_1EventBus_1_1Configuration_1_1AzureEventPublisherModule.html">Cqrs.Ninject.Azure.ServiceBus.EventBus.Configuration.AzureEventPublisherModule< TAuthenticationToken ></a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1ServiceBus_1_1EventBus_1_1Configuration_1_1AzureEventPublisherModule_ab9adf56ae8b2812f77fce9cb35fb5bd3.html#ab9adf56ae8b2812f77fce9cb35fb5bd3">Load</a>()</td><td class="entry"><a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1ServiceBus_1_1EventBus_1_1Configuration_1_1AzureEventPublisherModule.html">Cqrs.Ninject.Azure.ServiceBus.EventBus.Configuration.AzureEventPublisherModule< TAuthenticationToken ></a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1ServiceBus_1_1EventBus_1_1Configuration_1_1AzureEventPublisherModule_a083d0a67e9aff92b84b710f1ad3f1e9b.html#a083d0a67e9aff92b84b710f1ad3f1e9b">RegisterEventMessageSerialiser</a>()</td><td class="entry"><a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1ServiceBus_1_1EventBus_1_1Configuration_1_1AzureEventPublisherModule.html">Cqrs.Ninject.Azure.ServiceBus.EventBus.Configuration.AzureEventPublisherModule< TAuthenticationToken ></a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1ServiceBus_1_1EventBus_1_1Configuration_1_1AzureEventPublisherModule_af48f3202822bbfe9cf654d7acedf5024.html#af48f3202822bbfe9cf654d7acedf5024">RegisterEventPublisher</a>()</td><td class="entry"><a class="el" href="classCqrs_1_1Ninject_1_1Azure_1_1ServiceBus_1_1EventBus_1_1Configuration_1_1AzureEventPublisherModule.html">Cqrs.Ninject.Azure.ServiceBus.EventBus.Configuration.AzureEventPublisherModule< TAuthenticationToken ></a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
</table></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li>
</ul>
</div>
</body>
</html>
|
cdmdotnet/CQRS
|
wiki/docs/2.0/html/classCqrs_1_1Ninject_1_1Azure_1_1ServiceBus_1_1EventBus_1_1Configuration_1_1AzureEventPublisherModule-members.html
|
HTML
|
lgpl-2.1
| 6,235
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki.plugin.charts.exceptions;
public class InvalidArgumentException extends ParamException
{
public InvalidArgumentException()
{
super();
}
public InvalidArgumentException(String arg0)
{
super(arg0);
}
public InvalidArgumentException(String arg0, Throwable arg1)
{
super(arg0, arg1);
}
public InvalidArgumentException(Throwable arg0)
{
super(arg0);
}
}
|
xwiki/xwiki-platform
|
xwiki-platform-core/xwiki-platform-chart/xwiki-platform-chart-plugin/src/main/java/com/xpn/xwiki/plugin/charts/exceptions/InvalidArgumentException.java
|
Java
|
lgpl-2.1
| 1,349
|
/*
* JBoss, Home of Professional Open Source.
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
package org.jboss.bqt.core.util;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.jboss.bqt.core.exception.FrameworkException;
import org.junit.Test;
import org.junit.BeforeClass;
import org.junit.AfterClass;
/**
* @since 4.0
*/
public final class TestFileUtils {
private static final String FILE_NAME = UnitTestUtil.getTestDataPath() + File.separator + "fakeScript.txt"; //$NON-NLS-1$
private static final String TEMP_FILE_PREFFIX = "mmtmp"; //$NON-NLS-1$
private final static String TEMP_DIR_NAME = "tempdir"; //$NON-NLS-1$
private final static String TEMP_FILE_NAME = "tempfile.txt"; //$NON-NLS-1$
private final static String TEMP_FILE_NAME2 = "tempfile2.txt"; //$NON-NLS-1$
private static File tempDir;
// =========================================================================
// F R A M E W O R K
// =========================================================================
/**
* Constructor for TestJDBCRepositoryWriter.
*/
public TestFileUtils() {
}
// =========================================================================
// S E T U P A N D T E A R D O W N
// =========================================================================
@BeforeClass
public static void setUp() throws Exception {
//create a temp directory
tempDir = new File(TEMP_DIR_NAME);
tempDir.mkdir();
}
@AfterClass
public static void tearDown() throws Exception {
try {
tempDir.delete();
} catch (Exception e) {
}
try {
new File(TEMP_FILE_NAME).delete();
} catch (Exception e) {
e.printStackTrace();
}
try {
new File(TEMP_FILE_NAME2).delete();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testWrite() throws Exception{
File tmp = null;
try {
tmp = File.createTempFile(TEMP_FILE_PREFFIX, null);
final FileInputStream is = new FileInputStream(FILE_NAME);
FileUtils.write(is, tmp);
if(tmp == null || tmp.length() == 0){
fail("Content not written to new file"); //$NON-NLS-1$
}
}finally {
if(tmp != null) {
tmp.delete();
}
}
}
@Test
public void testWriteEmptyFile() throws Exception{
File tmp = null;
File emptyFile = null;
try {
tmp = File.createTempFile(TEMP_FILE_PREFFIX, null);
emptyFile = File.createTempFile("EMPTY", null); //$NON-NLS-1$
final FileInputStream is = new FileInputStream(emptyFile);
FileUtils.write(is, tmp);
if(tmp == null || tmp.length() > 0){
fail("content available; must be empty"); //$NON-NLS-1$
}
}finally {
if(tmp != null) {
tmp.delete();
}
if (emptyFile != null) {
emptyFile.delete();
}
}
}
/**
* Tests FileUtils.testDirectoryPermissions()
* @throws Exception
*/
@Test
public void testTestDirectoryPermissions() throws Exception {
//positive case
FileUtils.testDirectoryPermissions(TEMP_DIR_NAME);
//negative case: dir doesn't exist
try {
FileUtils.testDirectoryPermissions("fakeDir"); //$NON-NLS-1$
fail("Expected a BQTException"); //$NON-NLS-1$
} catch (FrameworkException e) {
}
}
/**
* Tests FileUtils.testDirectoryPermissions()
* @throws Exception
*/
@Test
public void testGetBaseNameWithoutExt() throws Exception {
String n =FileUtils.getBaseFileNameWithoutExtension(TEMP_DIR_NAME + File.separator + TEMP_FILE_NAME);
assertEquals("tempfile", n);
n =FileUtils.getBaseFileNameWithoutExtension("mysql50_vqt.properties");
assertEquals("mysql50_vqt", n);
}
/**
* Tests FileUtils.copy()
* @throws Exception
*/
@Test
public void testCopy() throws Exception {
String contents1 = ObjectConverterUtil.convertFileToString(new File(FILE_NAME));
//positive case
FileUtils.copy(FILE_NAME, TEMP_FILE_NAME, false);
String contents2 = ObjectConverterUtil.convertFileToString(new File(TEMP_FILE_NAME));
assertEquals("Expected file contents to be the same", contents1, contents2); //$NON-NLS-1$
assertTrue("Expected original file to still exist", new File(FILE_NAME).exists()); //$NON-NLS-1$
//negative case: should fail because file already exists
try {
FileUtils.copy(FILE_NAME, TEMP_FILE_NAME, false);
fail("Expected BQTException"); //$NON-NLS-1$
} catch (IOException e) {
}
//positive case: should succeed because we've specified to overwrite
FileUtils.copy(FILE_NAME, TEMP_FILE_NAME, true);
contents2 = ObjectConverterUtil.convertFileToString(new File(TEMP_FILE_NAME));
assertEquals("Expected file contents to be the same", contents1, contents2); //$NON-NLS-1$
assertTrue("Expected original file to still exist", new File(FILE_NAME).exists()); //$NON-NLS-1$
}
/**
* Tests FileUtils.rename()
* @throws Exception
*/
@Test
public void testRename() throws Exception {
String contents1 = ObjectConverterUtil.convertFileToString(new File(FILE_NAME));
//positive case
FileUtils.copy(FILE_NAME, TEMP_FILE_NAME, true);
FileUtils.rename(TEMP_FILE_NAME, TEMP_FILE_NAME2, false);
String contents2 = ObjectConverterUtil.convertFileToString(new File(TEMP_FILE_NAME2));
assertEquals("Expected file contents to be the same", contents1, contents2); //$NON-NLS-1$
assertFalse("Expected original file to not exist", new File(TEMP_FILE_NAME).exists()); //$NON-NLS-1$
//negative case: should fail because file already exists
FileUtils.copy(FILE_NAME, TEMP_FILE_NAME, true);
FileUtils.copy(FILE_NAME, TEMP_FILE_NAME2, true);
try {
FileUtils.rename(FILE_NAME, TEMP_FILE_NAME2, false);
fail("Expected BQTException"); //$NON-NLS-1$
} catch (IOException e) {
}
//positive case: should succeed because we've specified to overwrite
FileUtils.copy(FILE_NAME, TEMP_FILE_NAME, true);
FileUtils.copy(FILE_NAME, TEMP_FILE_NAME2, true);
FileUtils.rename(TEMP_FILE_NAME, TEMP_FILE_NAME2, true);
contents2 = ObjectConverterUtil.convertFileToString(new File(TEMP_FILE_NAME2));
assertEquals("Expected file contents to be the same", contents1, contents2); //$NON-NLS-1$
assertFalse("Expected original file to not exist", new File(TEMP_FILE_NAME).exists()); //$NON-NLS-1$
}
/**
* Tests FileUtils.remove()
* @throws Exception
*/
@Test
public void testRemove() throws Exception {
FileUtils.copy(FILE_NAME, TEMP_FILE_NAME, true);
//positive case
FileUtils.remove(TEMP_FILE_NAME);
assertFalse("Expected File to not exist", new File(TEMP_FILE_NAME).exists()); //$NON-NLS-1$
//call again - this should not throw an exception
FileUtils.remove(TEMP_FILE_NAME);
}
/**
* Tests FileUtils.copyRecursively()
* Should fail because a file is given for source dir
* @throws Exception
*/
@Test
public void testCopyRecursivelyNull() throws Exception {
File fileSource = new File(TEMP_FILE_NAME);
fileSource.delete();
fileSource.createNewFile();
try {
FileUtils.copyDirectoriesRecursively(fileSource, fileSource);
fail("File arg should have been illegal."); //$NON-NLS-1$
} catch (final Exception err) {
// source was a file instead of dir - exception
// err.printStackTrace();
} finally {
fileSource.delete();
}
}
}
|
SQLBulkQueryTool/SQLBulkQueryTool
|
core/src/test/java/org/jboss/bqt/core/util/TestFileUtils.java
|
Java
|
lgpl-2.1
| 9,464
|
/*
* Clutter.
*
* An OpenGL based 'interactive canvas' library.
*
* Authored By Matthew Allum <mallum@openedhand.com>
*
* Copyright (C) 2006 OpenedHand
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(__CLUTTER_H_INSIDE__) && !defined(CLUTTER_COMPILATION)
#error "Only <clutter/clutter.h> can be included directly."
#endif
#ifndef __CLUTTER_EVENT_H__
#define __CLUTTER_EVENT_H__
#include <clutter/clutter-types.h>
#include <clutter/clutter-input-device.h>
G_BEGIN_DECLS
#define CLUTTER_TYPE_EVENT (clutter_event_get_type ())
/**
* CLUTTER_PRIORITY_EVENTS:
*
* Priority for event handling.
*
*
*/
#define CLUTTER_PRIORITY_EVENTS (G_PRIORITY_DEFAULT)
/**
* CLUTTER_CURRENT_TIME:
*
* Default value for "now".
*
*
*/
#define CLUTTER_CURRENT_TIME (0L)
/**
* CLUTTER_EVENT_PROPAGATE:
*
* Continues the propagation of an event; this macro should be
* used in event-related signals.
*
*
*/
#define CLUTTER_EVENT_PROPAGATE (FALSE)
/**
* CLUTTER_EVENT_STOP:
*
* Stops the propagation of an event; this macro should be used
* in event-related signals.
*
*
*/
#define CLUTTER_EVENT_STOP (TRUE)
/**
* CLUTTER_BUTTON_PRIMARY:
*
* The primary button of a pointer device.
*
* This is typically the left mouse button in a right-handed
* mouse configuration.
*
*
*/
#define CLUTTER_BUTTON_PRIMARY (1)
/**
* CLUTTER_BUTTON_MIDDLE:
*
* The middle button of a pointer device.
*
*
*/
#define CLUTTER_BUTTON_MIDDLE (2)
/**
* CLUTTER_BUTTON_SECONDARY:
*
* The secondary button of a pointer device.
*
* This is typically the right mouse button in a right-handed
* mouse configuration.
*
*
*/
#define CLUTTER_BUTTON_SECONDARY (3)
typedef struct _ClutterAnyEvent ClutterAnyEvent;
typedef struct _ClutterButtonEvent ClutterButtonEvent;
typedef struct _ClutterKeyEvent ClutterKeyEvent;
typedef struct _ClutterMotionEvent ClutterMotionEvent;
typedef struct _ClutterScrollEvent ClutterScrollEvent;
typedef struct _ClutterStageStateEvent ClutterStageStateEvent;
typedef struct _ClutterCrossingEvent ClutterCrossingEvent;
typedef struct _ClutterTouchEvent ClutterTouchEvent;
/**
* ClutterAnyEvent:
* @type: event type
* @time: event time
* @flags: event flags
* @source: event source actor
*
* Common members for a #ClutterEvent
*
*
*/
struct _ClutterAnyEvent
{
ClutterEventType type;
guint32 time;
ClutterEventFlags flags;
ClutterStage *stage;
ClutterActor *source;
};
/**
* ClutterKeyEvent:
* @type: event type
* @time: event time
* @flags: event flags
* @stage: event source stage
* @source: event source actor
* @modifier_state: key modifiers
* @keyval: raw key value
* @hardware_keycode: raw hardware key value
* @unicode_value: Unicode representation
* @device: the device that originated the event. If you want the physical
* device the event originated from, use clutter_event_get_source_device()
*
* Key event
*
*
*/
struct _ClutterKeyEvent
{
ClutterEventType type;
guint32 time;
ClutterEventFlags flags;
ClutterStage *stage;
ClutterActor *source;
ClutterModifierType modifier_state;
guint keyval;
guint16 hardware_keycode;
gunichar unicode_value;
ClutterInputDevice *device;
};
/**
* ClutterButtonEvent:
* @type: event type
* @time: event time
* @flags: event flags
* @stage: event source stage
* @source: event source actor
* @x: event X coordinate, relative to the stage
* @y: event Y coordinate, relative to the stage
* @modifier_state: button modifiers
* @button: event button
* @click_count: number of button presses within the default time
* and radius
* @axes: reserved for future use
* @device: the device that originated the event. If you want the physical
* device the event originated from, use clutter_event_get_source_device()
*
* Button event.
*
* The event coordinates are relative to the stage that received the
* event, and can be transformed into actor-relative coordinates by
* using clutter_actor_transform_stage_point().
*
*
*/
struct _ClutterButtonEvent
{
ClutterEventType type;
guint32 time;
ClutterEventFlags flags;
ClutterStage *stage;
ClutterActor *source;
gfloat x;
gfloat y;
ClutterModifierType modifier_state;
guint32 button;
guint click_count;
gdouble *axes; /* Future use */
ClutterInputDevice *device;
};
/**
* ClutterCrossingEvent:
* @type: event type
* @time: event time
* @flags: event flags
* @stage: event source stage
* @source: event source actor
* @x: event X coordinate
* @y: event Y coordinate
* @related: actor related to the crossing
* @device: the device that originated the event. If you want the physical
* device the event originated from, use clutter_event_get_source_device()
*
* Event for the movement of the pointer across different actors
*
*
*/
struct _ClutterCrossingEvent
{
ClutterEventType type;
guint32 time;
ClutterEventFlags flags;
ClutterStage *stage;
ClutterActor *source;
gfloat x;
gfloat y;
ClutterInputDevice *device;
ClutterActor *related;
};
/**
* ClutterMotionEvent:
* @type: event type
* @time: event time
* @flags: event flags
* @stage: event source stage
* @source: event source actor
* @x: event X coordinate
* @y: event Y coordinate
* @modifier_state: button modifiers
* @axes: reserved for future use
* @device: the device that originated the event. If you want the physical
* device the event originated from, use clutter_event_get_source_device()
*
* Event for the pointer motion
*
*
*/
struct _ClutterMotionEvent
{
ClutterEventType type;
guint32 time;
ClutterEventFlags flags;
ClutterStage *stage;
ClutterActor *source;
gfloat x;
gfloat y;
ClutterModifierType modifier_state;
gdouble *axes; /* Future use */
ClutterInputDevice *device;
};
/**
* ClutterScrollEvent:
* @type: event type
* @time: event time
* @flags: event flags
* @stage: event source stage
* @source: event source actor
* @x: event X coordinate
* @y: event Y coordinate
* @direction: direction of the scrolling
* @modifier_state: button modifiers
* @axes: reserved for future use
* @device: the device that originated the event. If you want the physical
* device the event originated from, use clutter_event_get_source_device()
*
* Scroll wheel (or similar device) event
*
*
*/
struct _ClutterScrollEvent
{
ClutterEventType type;
guint32 time;
ClutterEventFlags flags;
ClutterStage *stage;
ClutterActor *source;
gfloat x;
gfloat y;
ClutterScrollDirection direction;
ClutterModifierType modifier_state;
gdouble *axes; /* future use */
ClutterInputDevice *device;
};
/**
* ClutterStageStateEvent:
* @type: event type
* @time: event time
* @flags: event flags
* @stage: event source stage
* @source: event source actor (unused)
* @changed_mask: bitwise OR of the changed flags
* @new_state: bitwise OR of the current state flags
*
* Event signalling a change in the #ClutterStage state.
*
*
*/
struct _ClutterStageStateEvent
{
ClutterEventType type;
guint32 time;
ClutterEventFlags flags;
ClutterStage *stage;
ClutterActor *source; /* XXX: should probably be the stage itself */
ClutterStageState changed_mask;
ClutterStageState new_state;
};
/**
* ClutterTouchEvent:
* @type: event type
* @time: event time
* @flags: event flags
* @stage: event source stage
* @source: event source actor (unused)
* @x: the X coordinate of the pointer, relative to the stage
* @y: the Y coordinate of the pointer, relative to the stage
* @sequence: the event sequence that this event belongs to
* @modifier_state: (type ClutterModifierType): a bit-mask representing the state
* of modifier keys (e.g. Control, Shift, and Alt) and the pointer
* buttons. See #ClutterModifierType
* @axes: reserved
* @device: the device that originated the event. If you want the physical
* device the event originated from, use clutter_event_get_source_device()
*
* Used for touch events.
*
* The @type field will be one of %CLUTTER_TOUCH_BEGIN, %CLUTTER_TOUCH_END,
* %CLUTTER_TOUCH_UPDATE, or %CLUTTER_TOUCH_CANCEL.
*
* Touch events are grouped into sequences; each touch sequence will begin
* with a %CLUTTER_TOUCH_BEGIN event, progress with %CLUTTER_TOUCH_UPDATE
* events, and end either with a %CLUTTER_TOUCH_END event or with a
* %CLUTTER_TOUCH_CANCEL event.
*
* With multi-touch capable devices there can be multiple event sequence
* running at the same time.
*
*
*/
struct _ClutterTouchEvent
{
ClutterEventType type;
guint32 time;
ClutterEventFlags flags;
ClutterStage *stage;
ClutterActor *source;
gfloat x;
gfloat y;
ClutterEventSequence *sequence;
ClutterModifierType modifier_state;
gdouble *axes; /* reserved */
ClutterInputDevice *device;
};
/**
* ClutterEvent:
*
* Generic event wrapper.
*
*
*/
union _ClutterEvent
{
/*< private >*/
ClutterEventType type;
ClutterAnyEvent any;
ClutterButtonEvent button;
ClutterKeyEvent key;
ClutterMotionEvent motion;
ClutterScrollEvent scroll;
ClutterStageStateEvent stage_state;
ClutterCrossingEvent crossing;
ClutterTouchEvent touch;
};
GType clutter_event_get_type (void) G_GNUC_CONST;
gboolean clutter_events_pending (void);
ClutterEvent * clutter_event_get (void);
ClutterEvent * clutter_event_peek (void);
void clutter_event_put (const ClutterEvent *event);
ClutterEvent * clutter_event_new (ClutterEventType type);
ClutterEvent * clutter_event_copy (const ClutterEvent *event);
void clutter_event_free (ClutterEvent *event);
ClutterEventType clutter_event_type (const ClutterEvent *event);
void clutter_event_set_flags (ClutterEvent *event,
ClutterEventFlags flags);
ClutterEventFlags clutter_event_get_flags (const ClutterEvent *event);
void clutter_event_set_time (ClutterEvent *event,
guint32 time_);
guint32 clutter_event_get_time (const ClutterEvent *event);
void clutter_event_set_state (ClutterEvent *event,
ClutterModifierType state);
ClutterModifierType clutter_event_get_state (const ClutterEvent *event);
void clutter_event_set_device (ClutterEvent *event,
ClutterInputDevice *device);
ClutterInputDevice * clutter_event_get_device (const ClutterEvent *event);
void clutter_event_set_source_device (ClutterEvent *event,
ClutterInputDevice *device);
ClutterInputDevice * clutter_event_get_source_device (const ClutterEvent *event);
void clutter_event_set_source (ClutterEvent *event,
ClutterActor *actor);
ClutterActor * clutter_event_get_source (const ClutterEvent *event);
void clutter_event_set_stage (ClutterEvent *event,
ClutterStage *stage);
ClutterStage * clutter_event_get_stage (const ClutterEvent *event);
gint clutter_event_get_device_id (const ClutterEvent *event);
ClutterInputDeviceType clutter_event_get_device_type (const ClutterEvent *event);
void clutter_event_set_coords (ClutterEvent *event,
gfloat x,
gfloat y);
void clutter_event_get_coords (const ClutterEvent *event,
gfloat *x,
gfloat *y);
void clutter_event_get_position (const ClutterEvent *event,
ClutterPoint *position);
float clutter_event_get_distance (const ClutterEvent *source,
const ClutterEvent *target);
double clutter_event_get_angle (const ClutterEvent *source,
const ClutterEvent *target);
gdouble * clutter_event_get_axes (const ClutterEvent *event,
guint *n_axes);
gboolean clutter_event_has_shift_modifier (const ClutterEvent *event);
gboolean clutter_event_has_control_modifier (const ClutterEvent *event);
gboolean clutter_event_is_pointer_emulated (const ClutterEvent *event);
void clutter_event_set_key_symbol (ClutterEvent *event,
guint key_sym);
guint clutter_event_get_key_symbol (const ClutterEvent *event);
void clutter_event_set_key_code (ClutterEvent *event,
guint16 key_code);
guint16 clutter_event_get_key_code (const ClutterEvent *event);
void clutter_event_set_key_unicode (ClutterEvent *event,
gunichar key_unicode);
gunichar clutter_event_get_key_unicode (const ClutterEvent *event);
void clutter_event_set_button (ClutterEvent *event,
guint32 button);
guint32 clutter_event_get_button (const ClutterEvent *event);
guint clutter_event_get_click_count (const ClutterEvent *event);
void clutter_event_set_related (ClutterEvent *event,
ClutterActor *actor);
ClutterActor * clutter_event_get_related (const ClutterEvent *event);
void clutter_event_set_scroll_direction (ClutterEvent *event,
ClutterScrollDirection direction);
ClutterScrollDirection clutter_event_get_scroll_direction (const ClutterEvent *event);
void clutter_event_set_scroll_delta (ClutterEvent *event,
gdouble dx,
gdouble dy);
void clutter_event_get_scroll_delta (const ClutterEvent *event,
gdouble *dx,
gdouble *dy);
ClutterEventSequence * clutter_event_get_event_sequence (const ClutterEvent *event);
guint32 clutter_keysym_to_unicode (guint keyval);
guint clutter_unicode_to_keysym (guint32 wc);
guint32 clutter_get_current_event_time (void);
const ClutterEvent * clutter_get_current_event (void);
G_END_DECLS
#endif /* __CLUTTER_EVENT_H__ */
|
collects/clutter
|
clutter/clutter-event.h
|
C
|
lgpl-2.1
| 17,374
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QMLBACKENDMONITORINFO_H_
#define QMLBACKENDMONITORINFO_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 "qmlbackendmonitorao_s60_p.h"
QTM_BEGIN_NAMESPACE
//linked list information structure
struct CMonitorTriggerInfo {
QGeoAreaMonitorS60* iParent;
TLbtTriggerId iTriggerID;
enum enTriggerType iType;
CMonitorTriggerInfo* next;
};
class CBackendMonitorInfo : public CBase
{
public :
static CBackendMonitorInfo *NewL();
//return CMonitorTriggerInfo from TriggerID
CMonitorTriggerInfo* getMonitorTriggerInfo(TLbtTriggerId aTrigID);
//return CMonitorTriggerInfo from the QGeoAreaMonitorS60
CMonitorTriggerInfo* getMonitorTriggerInfo(QGeoAreaMonitorS60* aParent, enTriggerType aType);
//return the header of the linked list
inline CMonitorTriggerInfo* getMonitorTriggerInfo() {
return iMonitorInfo;
}
//add the entry and exit trigger info to the list
bool addMonitorTriggerInfo(QGeoAreaMonitorS60* aParent, TLbtTriggerId aTriggerID, enTriggerType aType);
//remove the CMonitorTriggerInfo corresponding to the TriggerID
void removeMonitorTriggerInfo(TLbtTriggerId aTrigID);
~CBackendMonitorInfo();
private :
CBackendMonitorInfo() : iMonitorInfo(NULL) { }
CMonitorTriggerInfo* iMonitorInfo;
static CBackendMonitorInfo* iBackendMonitorInfo;
};
QTM_END_NAMESPACE
#endif /* QMLBACKENDMONITORINFO_H_ */
|
enthought/qt-mobility
|
src/location/qmlbackendmonitorinfo_s60_p.h
|
C
|
lgpl-2.1
| 3,584
|
/*
Copyright (C) 2011 Sebastian Pancratz
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
#include "flint.h"
#include "fmpq.h"
#include "fmpq_mat.h"
int
main(void)
{
int i, result;
FLINT_TEST_INIT(state);
flint_printf("neg....");
fflush(stdout);
/* Aliasing */
for (i = 0; i < 100 * flint_test_multiplier(); i++)
{
fmpq_mat_t A, B;
slong m, n, bits;
m = n_randint(state, 10);
n = n_randint(state, 10);
bits = 1 + n_randint(state, 100);
fmpq_mat_init(A, m, n);
fmpq_mat_init(B, m, n);
fmpq_mat_randtest(B, state, bits);
fmpq_mat_neg(A, B);
fmpq_mat_neg(B, B);
result = fmpq_mat_equal(A, B);
if (!result)
{
flint_printf("FAIL:\n");
flint_printf("A:\n");
fmpq_mat_print(A);
flint_printf("B:\n");
fmpq_mat_print(B);
fflush(stdout);
flint_abort();
}
fmpq_mat_clear(A);
fmpq_mat_clear(B);
}
/* --A == A */
for (i = 0; i < 100 * flint_test_multiplier(); i++)
{
fmpq_mat_t A, B;
slong m, n, bits;
m = n_randint(state, 10);
n = n_randint(state, 10);
bits = 1 + n_randint(state, 100);
fmpq_mat_init(A, m, n);
fmpq_mat_init(B, m, n);
fmpq_mat_randtest(B, state, bits);
fmpq_mat_neg(A, B);
fmpq_mat_neg(A, A);
result = fmpq_mat_equal(A, B);
if (!result)
{
flint_printf("FAIL:\n");
flint_printf("A:\n");
fmpq_mat_print(A);
flint_printf("B:\n");
fmpq_mat_print(B);
fflush(stdout);
flint_abort();
}
fmpq_mat_clear(A);
fmpq_mat_clear(B);
}
FLINT_TEST_CLEANUP(state);
flint_printf("PASS\n");
return EXIT_SUCCESS;
}
|
fredrik-johansson/flint2
|
fmpq_mat/test/t-neg.c
|
C
|
lgpl-2.1
| 2,266
|
/*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (C) Alkacon Software (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.ade.contenteditor;
import com.alkacon.acacia.shared.AttributeConfiguration;
import com.alkacon.acacia.shared.TabInfo;
import com.alkacon.acacia.shared.Type;
import com.alkacon.vie.shared.I_Type;
import org.opencms.ade.contenteditor.shared.CmsComplexWidgetData;
import org.opencms.ade.contenteditor.shared.CmsExternalWidgetConfiguration;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.i18n.CmsMessages;
import org.opencms.i18n.CmsMultiMessages;
import org.opencms.main.OpenCms;
import org.opencms.widgets.A_CmsWidget;
import org.opencms.widgets.I_CmsADEWidget;
import org.opencms.widgets.I_CmsComplexWidget;
import org.opencms.widgets.I_CmsWidget;
import org.opencms.xml.CmsXmlContentDefinition;
import org.opencms.xml.CmsXmlException;
import org.opencms.xml.content.CmsXmlContentTab;
import org.opencms.xml.content.I_CmsXmlContentHandler;
import org.opencms.xml.content.I_CmsXmlContentHandler.DisplayType;
import org.opencms.xml.types.A_CmsXmlContentValue;
import org.opencms.xml.types.CmsXmlNestedContentDefinition;
import org.opencms.xml.types.I_CmsXmlSchemaType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Visitor to read all types and attribute configurations within a content definition.<p>
*/
public class CmsContentTypeVisitor {
/**
* Helper class to evaluate the widget display type.<p>
*/
protected class DisplayTypeEvaluator {
/** The attribute name. */
private String m_attributeName;
/** The attribute type configuration. */
private AttributeConfiguration m_config;
/** The configured display type. */
private DisplayType m_configuredType;
/** The default display type. */
private DisplayType m_default;
/** The applied rule. */
private EvaluationRule m_rule;
/**
* Constructor.<p>
*
* @param config the attribute type configuration
* @param configuredType the configured display type
* @param defaultType the default display type
* @param rule the applied rule
*/
protected DisplayTypeEvaluator(
AttributeConfiguration config,
DisplayType configuredType,
DisplayType defaultType,
EvaluationRule rule) {
m_config = config;
m_configuredType = configuredType;
m_default = defaultType;
m_rule = rule;
}
/**
* Returns the attribute name.<p>
*
* @return the attribute name
*/
protected String getAttributeName() {
return m_attributeName;
}
/**
* Returns the attribute configuration with the evaluated display type.<p>
*
* @param predecessor the proposed predecessor display type
* @param successor the proposed successor display type
*
* @return the attribute configuration
*/
protected AttributeConfiguration getEvaluatedConfiguration(DisplayType predecessor, DisplayType successor) {
DisplayType resultingType = m_configuredType;
if (resultingType.equals(DisplayType.none)) {
if (m_rule.equals(EvaluationRule.rootLevel)) {
resultingType = DisplayType.wide;
} else {
resultingType = getProposedType();
if ((predecessor != null) && predecessor.equals(DisplayType.none)) {
predecessor = null;
}
if ((successor != null) && successor.equals(DisplayType.none)) {
successor = null;
}
if ((predecessor != null) && predecessor.equals(DisplayType.column)) {
predecessor = DisplayType.singleline;
}
if ((successor != null) && successor.equals(DisplayType.column)) {
successor = DisplayType.singleline;
}
boolean strong = (m_rule.equals(EvaluationRule.none) || (m_rule.equals(EvaluationRule.optional) && m_default.equals(DisplayType.singleline)))
|| (m_rule.equals(EvaluationRule.optional) && m_default.equals(DisplayType.singleline));
if (((predecessor == null) || (successor == null)) && strong) {
resultingType = m_default;
} else if ((predecessor != null) || (successor != null)) {
// check if the proposed type matches neither the type of the predecessor nor the type of the successor
if (!(((predecessor != null) && resultingType.equals(predecessor)) || ((successor != null) && resultingType.equals(successor)))) {
DisplayType match = (predecessor != null)
&& (predecessor.equals(DisplayType.wide) || predecessor.equals(DisplayType.singleline))
? predecessor
: ((successor != null)
&& (successor.equals(DisplayType.wide) || successor.equals(DisplayType.singleline))
? successor
: null);
resultingType = match != null ? match : resultingType;
}
}
}
}
m_config.setDisplayType(resultingType.name());
return m_config;
}
/**
* Returns the proposed display type.<p>
*
* @return the proposed display type
*/
protected DisplayType getProposedType() {
DisplayType resultingType = m_configuredType;
if (resultingType.equals(DisplayType.none)) {
switch (m_rule) {
case rootLevel:
case labelLength:
resultingType = DisplayType.wide;
break;
case optional:
resultingType = DisplayType.singleline;
break;
default:
resultingType = m_default;
}
}
return resultingType;
}
/**
* Sets the attribute name.<p>
*
* @param attributeName the attribute name
*/
protected void setAttributeName(String attributeName) {
m_attributeName = attributeName;
}
}
/** Widget display type evaluation rules. */
protected enum EvaluationRule {
/** Label length rule. */
labelLength,
/** No rule applied. */
none,
/** Optional field rule. */
optional,
/** Root level rule. */
rootLevel
}
/** The attribute configurations. */
private Map<String, AttributeConfiguration> m_attributeConfigurations;
/** The CMS context used for this visitor. */
private CmsObject m_cms;
/** Map from attribute names to complex widget configurations. */
private Map<String, CmsComplexWidgetData> m_complexWidgets = new HashMap<String, CmsComplexWidgetData>();
/** The content handler. */
private I_CmsXmlContentHandler m_contentHandler;
/** The content resource. */
private CmsFile m_file;
/** The content locale. */
private Locale m_locale;
/** The messages. */
private CmsMultiMessages m_messages;
/** The registered types. */
private Map<String, I_Type> m_registeredTypes;
/** The tab informations. */
private List<TabInfo> m_tabInfos;
/** The widget configurations. */
private Map<String, CmsExternalWidgetConfiguration> m_widgetConfigurations;
/** The widgets encountered by this visitor. */
private List<I_CmsWidget> m_widgets = new ArrayList<I_CmsWidget>();
/**
* Constructor.<p>
*
* @param cms the CMS context
* @param file the content file
* @param locale the content locale
*/
public CmsContentTypeVisitor(CmsObject cms, CmsFile file, Locale locale) {
m_file = file;
m_cms = cms;
m_locale = locale;
}
/**
* Gets the CMS context.<p>
*
* @return the CMS context
*/
public CmsObject getCmsObject() {
return m_cms;
}
/**
* Gets the list of widgets which have been processed by this visitor.<p>
*
* @return the list of widget
*/
public List<I_CmsWidget> getCollectedWidgets() {
return Collections.unmodifiableList(m_widgets);
}
/**
* Gets the map of complex widget configurations.<p>
*
* @return a map from attribute names to complex widget configurations
*/
public Map<String, CmsComplexWidgetData> getComplexWidgetData() {
return m_complexWidgets;
}
/**
* Returns the tabInfos.<p>
*
* @return the tabInfos
*/
public List<TabInfo> getTabInfos() {
return m_tabInfos;
}
/**
* Checks if the content type widgets are compatible with the new content editor.<p>
*
* @param xmlContentDefinition the content definition
*
* @return <code>true</code> if the content type widgets are compatible with the new content editor
*
* @throws CmsXmlException if something goes wrong reading the type widget
*/
public boolean isEditorCompatible(CmsXmlContentDefinition xmlContentDefinition) throws CmsXmlException {
boolean result = true;
for (I_CmsXmlSchemaType subType : xmlContentDefinition.getTypeSequence()) {
if (subType.isSimpleType()) {
result = isEditorCompatible((A_CmsXmlContentValue)subType);
} else {
CmsXmlContentDefinition subTypeDefinition = ((CmsXmlNestedContentDefinition)subType).getNestedContentDefinition();
result = isEditorCompatible(subTypeDefinition);
}
if (!result) {
break;
}
}
return result;
}
/**
* Visits all types within the XML content definition.<p>
*
* @param xmlContentDefinition the content definition
* @param messageLocale the locale
*/
/**
* Visits all types within the XML content definition.<p>
*
* @param xmlContentDefinition the content definition
* @param messageLocale the locale
*/
public void visitTypes(CmsXmlContentDefinition xmlContentDefinition, Locale messageLocale) {
m_contentHandler = xmlContentDefinition.getContentHandler();
CmsMessages messages = null;
m_messages = new CmsMultiMessages(messageLocale);
try {
messages = OpenCms.getWorkplaceManager().getMessages(messageLocale);
if (messages != null) {
m_messages.addMessages(messages);
}
messages = m_contentHandler.getMessages(messageLocale);
if (messages != null) {
m_messages.addMessages(messages);
}
} catch (Exception e) {
//ignore
}
// generate a new multi messages object and add the messages from the workplace
m_attributeConfigurations = new HashMap<String, AttributeConfiguration>();
m_widgetConfigurations = new HashMap<String, CmsExternalWidgetConfiguration>();
m_registeredTypes = new HashMap<String, I_Type>();
m_tabInfos = collectTabInfos(xmlContentDefinition);
readTypes(xmlContentDefinition, "");
}
/**
* Returns the attribute configurations.<p>
*
* @return the attribute configurations
*/
protected Map<String, AttributeConfiguration> getAttributeConfigurations() {
return m_attributeConfigurations;
}
/**
* Returns the types of the visited content definition.<p>
*
* @return the types
*/
protected Map<String, I_Type> getTypes() {
return m_registeredTypes;
}
/**
* Returns the external widget configurations.<p>
*
* @return the external widget configurations
*/
protected Collection<CmsExternalWidgetConfiguration> getWidgetConfigurations() {
return m_widgetConfigurations.values();
}
/**
* Returns the tab informations for the given content definition.<p>
*
* @param definition the content definition
*
* @return the tab informations
*/
private List<TabInfo> collectTabInfos(CmsXmlContentDefinition definition) {
List<TabInfo> result = new ArrayList<TabInfo>();
if (definition.getContentHandler().getTabs() != null) {
for (CmsXmlContentTab xmlTab : definition.getContentHandler().getTabs()) {
String tabName = m_messages.keyDefault(A_CmsWidget.LABEL_PREFIX
+ definition.getInnerName()
+ "."
+ xmlTab.getTabName(), xmlTab.getTabName());
result.add(new TabInfo(tabName, xmlTab.getIdName(), xmlTab.getStartName(), xmlTab.isCollapsed()));
}
}
return result;
}
/**
* Returns the help information for this value.<p>
*
* @param value the value
*
* @return the help information
*/
private String getHelp(I_CmsXmlSchemaType value) {
StringBuffer result = new StringBuffer(64);
result.append(A_CmsWidget.LABEL_PREFIX);
result.append(getTypeKey(value));
result.append(A_CmsWidget.HELP_POSTFIX);
return m_messages.keyDefault(result.toString(), null);
}
/**
* Returns the label for this value.<p>
*
* @param value the value
*
* @return the label
*/
private String getLabel(I_CmsXmlSchemaType value) {
StringBuffer result = new StringBuffer(64);
result.append(A_CmsWidget.LABEL_PREFIX);
result.append(getTypeKey(value));
return m_messages.keyDefault(result.toString(), value.getName());
}
/**
* Returns the schema type message key.<p>
*
* @param value the schema type
*
* @return the schema type message key
*/
private String getTypeKey(I_CmsXmlSchemaType value) {
StringBuffer result = new StringBuffer(64);
result.append(value.getContentDefinition().getInnerName());
result.append('.');
result.append(value.getName());
return result.toString();
}
/**
* Checks if the content value widget is compatible with the new content editor.<p>
*
* @param schemaType the content value type
*
* @return <code>true</code> if the content value widget is compatible with the new content editor
*
* @throws CmsXmlException if something goes wrong reading the type widget
*/
private boolean isEditorCompatible(A_CmsXmlContentValue schemaType) throws CmsXmlException {
boolean result = false;
I_CmsXmlContentHandler contentHandler = schemaType.getContentDefinition().getContentHandler();
I_CmsWidget widget = contentHandler.getWidget(schemaType);
result = (widget == null) || (widget instanceof I_CmsADEWidget);
return result;
}
/**
* Returns if an element with the given path will be displayed at root level of a content editor tab.<p>
*
* @param path the element path
*
* @return <code>true</code> if an element with the given path will be displayed at root level of a content editor tab
*/
private boolean isTabRootLevel(String path) {
path = path.substring(1);
if (!path.contains("/")) {
return true;
}
if (m_tabInfos != null) {
for (TabInfo info : m_tabInfos) {
if (info.isCollapsed()
&& path.startsWith(info.getStartName())
&& !path.substring(info.getStartName().length() + 1).contains("/")) {
return true;
}
}
}
return false;
}
/**
* Reads the attribute configuration for the given schema type. May return <code>null</code> if no special configuration was set.<p>
*
* @param schemaType the schema type
* @param path the attribute path
*
* @return the attribute configuration
*/
private DisplayTypeEvaluator readConfiguration(A_CmsXmlContentValue schemaType, String path) {
String widgetName = null;
String widgetConfig = null;
CmsObject cms = getCmsObject();
String label = getLabel(schemaType);
// set the default display type
DisplayType configuredType = DisplayType.none;
DisplayType defaultType = DisplayType.none;
EvaluationRule rule = EvaluationRule.none;
try {
I_CmsXmlContentHandler contentHandler = schemaType.getContentDefinition().getContentHandler();
I_CmsWidget widget = contentHandler.getWidget(schemaType);
configuredType = contentHandler.getDisplayType(schemaType);
if (configuredType.equals(DisplayType.none) && schemaType.isSimpleType()) {
// check the type is on the root level of the document, those will be displayed 'wide'
// the path will always have a leading '/'
// also in case the label has more than 15 characters, we display 'wide'
if (isTabRootLevel(path)) {
rule = EvaluationRule.rootLevel;
} else if (label.length() > 15) {
rule = EvaluationRule.labelLength;
} else if ((schemaType.getMinOccurs() == 0)) {
rule = EvaluationRule.optional;
}
}
if (widget != null) {
widgetName = widget.getClass().getName();
if ((configuredType == DisplayType.column)
&& !(schemaType.isSimpleType() && (schemaType.getMaxOccurs() == 1) && widget.isCompactViewEnabled())) {
// column view is not allowed for this widget
configuredType = DisplayType.singleline;
}
long timer = 0;
if (widget instanceof I_CmsADEWidget) {
if (CmsContentService.LOG.isDebugEnabled()) {
timer = System.currentTimeMillis();
}
I_CmsADEWidget adeWidget = (I_CmsADEWidget)widget;
defaultType = adeWidget.getDefaultDisplayType();
widgetName = adeWidget.getWidgetName();
widgetConfig = adeWidget.getConfiguration(cms, schemaType, m_messages, m_file, m_locale);
if (!adeWidget.isInternal() && !m_widgetConfigurations.containsKey(widgetName)) {
CmsExternalWidgetConfiguration externalConfiguration = new CmsExternalWidgetConfiguration(
widgetName,
adeWidget.getInitCall(),
adeWidget.getJavaScriptResourceLinks(cms),
adeWidget.getCssResourceLinks(cms));
m_widgetConfigurations.put(widgetName, externalConfiguration);
}
if (CmsContentService.LOG.isDebugEnabled()) {
CmsContentService.LOG.debug(Messages.get().getBundle().key(
Messages.LOG_TAKE_READING_WIDGET_CONFIGURATION_TIME_2,
widgetName,
"" + (System.currentTimeMillis() - timer)));
}
}
m_widgets.add(widget);
} else if (contentHandler.getComplexWidget(schemaType) != null) {
I_CmsComplexWidget complexWidget = contentHandler.getComplexWidget(schemaType);
CmsComplexWidgetData widgetData = complexWidget.getWidgetData(m_cms);
CmsExternalWidgetConfiguration externalConfig = widgetData.getExternalWidgetConfiguration();
if (externalConfig != null) {
m_widgetConfigurations.put(complexWidget.getName(), externalConfig);
}
m_complexWidgets.put(CmsContentService.getAttributeName(schemaType), widgetData);
}
} catch (Exception e) {
// may happen if no widget was set for the value
CmsContentService.LOG.debug(e.getMessage(), e);
}
AttributeConfiguration result = new AttributeConfiguration(
label,
getHelp(schemaType),
widgetName,
widgetConfig,
readDefaultValue(schemaType, path),
configuredType.name());
return new DisplayTypeEvaluator(result, configuredType, defaultType, rule);
}
/**
* Reads the default value for the given type.<p>
*
* @param schemaType the schema type
* @param path the element path
*
* @return the default value
*/
private String readDefaultValue(I_CmsXmlSchemaType schemaType, String path) {
return m_contentHandler.getDefault(getCmsObject(), m_file, schemaType, path, m_locale);
}
/**
* Reads the types from the given content definition and adds the to the map of already registered
* types if necessary.<p>
*
* @param xmlContentDefinition the XML content definition
* @param path the element path
*/
private void readTypes(CmsXmlContentDefinition xmlContentDefinition, String path) {
String typeName = CmsContentService.getTypeUri(xmlContentDefinition);
if (m_registeredTypes.containsKey(typeName)) {
return;
}
Type type = new Type(typeName);
type.setChoiceMaxOccurrence(xmlContentDefinition.getChoiceMaxOccurs());
m_registeredTypes.put(typeName, type);
if (type.isChoice()) {
Type choiceType = new Type(typeName + "/" + Type.CHOICE_ATTRIBUTE_NAME);
m_registeredTypes.put(choiceType.getId(), choiceType);
type.addAttribute(
Type.CHOICE_ATTRIBUTE_NAME,
choiceType.getId(),
1,
xmlContentDefinition.getChoiceMaxOccurs());
type = choiceType;
}
ArrayList<DisplayTypeEvaluator> evaluators = new ArrayList<DisplayTypeEvaluator>();
for (I_CmsXmlSchemaType subType : xmlContentDefinition.getTypeSequence()) {
String subTypeName = null;
String childPath = path + "/" + subType.getName();
String subAttributeName = CmsContentService.getAttributeName(subType.getName(), typeName);
DisplayTypeEvaluator ev = readConfiguration((A_CmsXmlContentValue)subType, childPath);
ev.setAttributeName(subAttributeName);
evaluators.add(ev);
if (subType.isSimpleType()) {
subTypeName = CmsContentService.TYPE_NAME_PREFIX + subType.getTypeName();
if (!m_registeredTypes.containsKey(subTypeName)) {
m_registeredTypes.put(subTypeName, new Type(subTypeName));
}
} else {
CmsXmlContentDefinition subTypeDefinition = ((CmsXmlNestedContentDefinition)subType).getNestedContentDefinition();
subTypeName = CmsContentService.getTypeUri(subTypeDefinition);
readTypes(subTypeDefinition, childPath);
}
type.addAttribute(subAttributeName, subTypeName, subType.getMinOccurs(), subType.getMaxOccurs());
}
DisplayType predecessor = null;
for (int i = 0; i < evaluators.size(); i++) {
DisplayTypeEvaluator ev = evaluators.get(i);
DisplayType successor = ((i + 1) < evaluators.size()) ? evaluators.get(i + 1).getProposedType() : null;
AttributeConfiguration evaluated = ev.getEvaluatedConfiguration(predecessor, successor);
m_attributeConfigurations.put(ev.getAttributeName(), evaluated);
predecessor = DisplayType.valueOf(evaluated.getDisplayType());
}
}
}
|
it-tavis/opencms-core
|
src/org/opencms/ade/contenteditor/CmsContentTypeVisitor.java
|
Java
|
lgpl-2.1
| 26,156
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qorganizeritemunionfilter.h"
#include "qorganizeritemunionfilter_p.h"
#include "qorganizeritemfilter_p.h"
#include "qorganizermanager.h"
QTM_BEGIN_NAMESPACE
/*!
\class QOrganizerItemUnionFilter
\brief The QOrganizerItemUnionFilter class provides a filter which unions the
results of other filters.
\inmodule QtOrganizer
\ingroup organizer-filters
\since 1.1
It may be used to select organizeritems which match all of the filters in the union
*/
Q_IMPLEMENT_ORGANIZERITEMFILTER_PRIVATE(QOrganizerItemUnionFilter);
/*!
* \fn QOrganizerItemUnionFilter::QOrganizerItemUnionFilter(const QOrganizerItemFilter& other)
* Constructs a copy of \a other if possible, otherwise constructs a new union filter
\since 1.1
*/
/*!
* Constructs a new intersection filter
\since 1.1
*/
QOrganizerItemUnionFilter::QOrganizerItemUnionFilter()
: QOrganizerItemFilter(new QOrganizerItemUnionFilterPrivate)
{
}
/*!
* Sets the filters whose criteria will be unioned to \a filters
* \sa filters()
\since 1.1
*/
void QOrganizerItemUnionFilter::setFilters(const QList<QOrganizerItemFilter>& filters)
{
Q_D(QOrganizerItemUnionFilter);
d->m_filters = filters;
}
/*!
* Prepends the given \a filter to the list of unioned filters
* \sa append(), filters()
\since 1.1
*/
void QOrganizerItemUnionFilter::prepend(const QOrganizerItemFilter& filter)
{
Q_D(QOrganizerItemUnionFilter);
d->m_filters.prepend(filter);
}
/*!
* Appends the given \a filter to the list of unioned filters
* \sa operator<<(), prepend(), filters()
\since 1.1
*/
void QOrganizerItemUnionFilter::append(const QOrganizerItemFilter& filter)
{
Q_D(QOrganizerItemUnionFilter);
d->m_filters.append(filter);
}
/*!
* Removes the given \a filter from the union list
* \sa filters(), append(), prepend(), clear()
\since 1.1
*/
void QOrganizerItemUnionFilter::remove(const QOrganizerItemFilter& filter)
{
Q_D(QOrganizerItemUnionFilter);
d->m_filters.removeAll(filter);
}
/*!
* Clears the list of filters. A cleared union filter will match no items.
* \sa filters(), remove()
\since 1.1
*/
void QOrganizerItemUnionFilter::clear()
{
Q_D(QOrganizerItemUnionFilter);
d->m_filters.clear();
}
/*!
* Appends the given \a filter to the list of unioned filters
* \sa append()
\since 1.1
*/
QOrganizerItemUnionFilter& QOrganizerItemUnionFilter::operator<<(const QOrganizerItemFilter& filter)
{
Q_D(QOrganizerItemUnionFilter);
d->m_filters << filter;
return *this;
}
/*!
* Returns the list of filters which form the union filter
* \sa setFilters(), prepend(), append(), remove()
\since 1.1
*/
QList<QOrganizerItemFilter> QOrganizerItemUnionFilter::filters() const
{
Q_D(const QOrganizerItemUnionFilter);
return d->m_filters;
}
QTM_END_NAMESPACE
|
enthought/qt-mobility
|
src/organizer/filters/qorganizeritemunionfilter.cpp
|
C++
|
lgpl-2.1
| 4,785
|
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2017 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.javadoc;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
import com.google.common.base.CharMatcher;
import com.puppycrawl.tools.checkstyle.api.DetailNode;
import com.puppycrawl.tools.checkstyle.api.JavadocTokenTypes;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
/**
* <p>
* Checks that <a href=
* "http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#firstsentence">
* Javadoc summary sentence</a> does not contain phrases that are not recommended to use.
* By default Check validate that first sentence is not empty:</p><br>
* <pre>
* <module name="SummaryJavadocCheck"/>
* </pre>
*
* <p>To ensure that summary do not contain phrase like "This method returns",
* use following config:
*
* <pre>
* <module name="SummaryJavadocCheck">
* <property name="forbiddenSummaryFragments"
* value="^This method returns.*"/>
* </module>
* </pre>
* <p>
* To specify period symbol at the end of first javadoc sentence - use following config:
* </p>
* <pre>
* <module name="SummaryJavadocCheck">
* <property name="period"
* value="period"/>
* </module>
* </pre>
*
*
* @author max
* @author <a href="mailto:nesterenko-aleksey@list.ru">Aleksey Nesterenko</a>
*/
public class SummaryJavadocCheck extends AbstractJavadocCheck {
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_SUMMARY_FIRST_SENTENCE = "summary.first.sentence";
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_SUMMARY_JAVADOC = "summary.javaDoc";
/**
* This regexp is used to convert multiline javadoc to single line without stars.
*/
private static final Pattern JAVADOC_MULTILINE_TO_SINGLELINE_PATTERN =
Pattern.compile("\n[ ]+(\\*)|^[ ]+(\\*)");
/** Period literal. */
private static final String PERIOD = ".";
/**
* Stores allowed values in document for inherit doc literal.
*/
private static final Set<Integer> SKIP_TOKENS = new HashSet<>(
Arrays.asList(JavadocTokenTypes.NEWLINE,
JavadocTokenTypes.LEADING_ASTERISK,
JavadocTokenTypes.EOF)
);
/**
* Regular expression for forbidden summary fragments.
*/
private Pattern forbiddenSummaryFragments = CommonUtils.createPattern("^$");
/**
* Period symbol at the end of first javadoc sentence.
*/
private String period = PERIOD;
/**
* Sets custom value of regular expression for forbidden summary fragments.
* @param pattern a pattern.
*/
public void setForbiddenSummaryFragments(Pattern pattern) {
forbiddenSummaryFragments = pattern;
}
/**
* Sets value of period symbol at the end of first javadoc sentence.
* @param period period's value.
*/
public void setPeriod(String period) {
this.period = period;
}
@Override
public int[] getDefaultJavadocTokens() {
return new int[] {
JavadocTokenTypes.JAVADOC,
};
}
@Override
public int[] getRequiredJavadocTokens() {
return getAcceptableJavadocTokens();
}
@Override
public int[] getAcceptableTokens() {
return new int[] {TokenTypes.BLOCK_COMMENT_BEGIN };
}
@Override
public int[] getRequiredTokens() {
return getAcceptableTokens();
}
@Override
public void visitJavadocToken(DetailNode ast) {
String firstSentence = getFirstSentence(ast);
final int endOfSentence = firstSentence.lastIndexOf(period);
if (endOfSentence == -1) {
if (!isOnlyInheritDoc(ast)) {
log(ast.getLineNumber(), MSG_SUMMARY_FIRST_SENTENCE);
}
}
else {
firstSentence = firstSentence.substring(0, endOfSentence);
if (containsForbiddenFragment(firstSentence)) {
log(ast.getLineNumber(), MSG_SUMMARY_JAVADOC);
}
}
}
/**
* Finds if inheritDoc is placed properly in java doc.
* @param ast Javadoc root node.
* @return true if inheritDoc is valid or false.
*/
private static boolean isOnlyInheritDoc(DetailNode ast) {
boolean extraTextFound = false;
boolean containsInheritDoc = false;
for (DetailNode child : ast.getChildren()) {
if (child.getType() == JavadocTokenTypes.TEXT) {
if (!child.getText().trim().isEmpty()) {
extraTextFound = true;
}
}
else if (child.getType() == JavadocTokenTypes.JAVADOC_INLINE_TAG) {
if (child.getChildren()[1].getType() == JavadocTokenTypes.INHERIT_DOC_LITERAL) {
containsInheritDoc = true;
}
else {
extraTextFound = true;
}
}
else if (!SKIP_TOKENS.contains(child.getType())) {
extraTextFound = true;
}
if (extraTextFound) {
break;
}
}
return containsInheritDoc && !extraTextFound;
}
/**
* Finds and returns first sentence.
* @param ast Javadoc root node.
* @return first sentence.
*/
private static String getFirstSentence(DetailNode ast) {
final StringBuilder result = new StringBuilder();
final String periodSuffix = PERIOD + ' ';
for (DetailNode child : ast.getChildren()) {
final String text = child.getText();
if (child.getType() != JavadocTokenTypes.JAVADOC_INLINE_TAG
&& text.contains(periodSuffix)) {
result.append(text.substring(0, text.indexOf(periodSuffix) + 1));
break;
}
else {
result.append(text);
}
}
return result.toString();
}
/**
* Tests if first sentence contains forbidden summary fragment.
* @param firstSentence String with first sentence.
* @return true, if first sentence contains forbidden summary fragment.
*/
private boolean containsForbiddenFragment(String firstSentence) {
String javadocText = JAVADOC_MULTILINE_TO_SINGLELINE_PATTERN
.matcher(firstSentence).replaceAll(" ");
javadocText = CharMatcher.WHITESPACE.trimAndCollapseFrom(javadocText, ' ');
return forbiddenSummaryFragments.matcher(javadocText).find();
}
}
|
AkshitaKukreja30/checkstyle
|
src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/SummaryJavadocCheck.java
|
Java
|
lgpl-2.1
| 7,878
|
/********************************************************************************/
/* Projeto: Biblioteca ZeusMDFe */
/* Biblioteca C# para emissão de Manifesto Eletrônico Fiscal de Documentos */
/* (https://mdfe-portal.sefaz.rs.gov.br/ */
/* */
/* Direitos Autorais Reservados (c) 2014 Adenilton Batista da Silva */
/* Zeusdev Tecnologia LTDA ME */
/* */
/* Você pode obter a última versão desse arquivo no GitHub */
/* localizado em https://github.com/adeniltonbs/Zeus.Net.NFe.NFCe */
/* */
/* */
/* Esta biblioteca é software livre; você pode redistribuí-la e/ou modificá-la */
/* sob os termos da Licença Pública Geral Menor do GNU conforme publicada pela */
/* Free Software Foundation; tanto a versão 2.1 da Licença, ou (a seu critério) */
/* qualquer versão posterior. */
/* */
/* Esta biblioteca é distribuída na expectativa de que seja útil, porém, SEM */
/* NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU */
/* ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral Menor*/
/* do GNU para mais detalhes. (Arquivo LICENÇA.TXT ou LICENSE.TXT) */
/* */
/* Você deve ter recebido uma cópia da Licença Pública Geral Menor do GNU junto*/
/* com esta biblioteca; se não, escreva para a Free Software Foundation, Inc., */
/* no endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. */
/* Você também pode obter uma copia da licença em: */
/* http://www.opensource.org/licenses/lgpl-license.php */
/* */
/* Zeusdev Tecnologia LTDA ME - adenilton@zeusautomacao.com.br */
/* http://www.zeusautomacao.com.br/ */
/* Rua Comendador Francisco josé da Cunha, 111 - Itabaiana - SE - 49500-000 */
/********************************************************************************/
using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using DFe.Classes.Entidades;
using DFe.Utils;
using DFe.Utils.Assinatura;
using MDFe.Classes.Flags;
using MDFe.Classes.Informacoes;
using MDFe.Utils.Configuracoes;
using MDFe.Utils.Flags;
using MDFe.Utils.Validacao;
using MDFEletronico = MDFe.Classes.Informacoes.MDFe;
namespace MDFe.Classes.Extencoes
{
public static class ExtMDFe
{
public static MDFEletronico Valida(this MDFEletronico mdfe)
{
if (mdfe == null) throw new ArgumentException("Erro de assinatura, MDFe esta null");
var xmlMdfe = FuncoesXml.ClasseParaXmlString(mdfe);
switch (MDFeConfiguracao.VersaoWebService.VersaoLayout)
{
case VersaoServico.Versao100:
Validador.Valida(xmlMdfe, "MDFe_v1.00.xsd");
break;
case VersaoServico.Versao300:
Validador.Valida(xmlMdfe, "MDFe_v3.00.xsd");
break;
}
var tipoModal = mdfe.InfMDFe.InfModal.Modal.GetType();
var xmlModal = FuncoesXml.ClasseParaXmlString(mdfe.InfMDFe.InfModal);
if (tipoModal == typeof (MDFeRodo))
{
switch (MDFeConfiguracao.VersaoWebService.VersaoLayout)
{
case VersaoServico.Versao100:
Validador.Valida(xmlModal, "MDFeModalRodoviario_v1.00.xsd");
break;
case VersaoServico.Versao300:
Validador.Valida(xmlModal, "MDFeModalRodoviario_v3.00.xsd");
break;
}
}
if (tipoModal == typeof (MDFeAereo))
{
switch (MDFeConfiguracao.VersaoWebService.VersaoLayout)
{
case VersaoServico.Versao100:
Validador.Valida(xmlModal, "MDFeModalAereo_v1.00.xsd");
break;
case VersaoServico.Versao300:
Validador.Valida(xmlModal, "MDFeModalAereo_v3.00.xsd");
break;
}
}
if (tipoModal == typeof (MDFeAquav))
{
switch (MDFeConfiguracao.VersaoWebService.VersaoLayout)
{
case VersaoServico.Versao100:
Validador.Valida(xmlModal, "MDFeModalAquaviario_v1.00.xsd");
break;
case VersaoServico.Versao300:
Validador.Valida(xmlModal, "MDFeModalAquaviario_v3.00.xsd");
break;
}
}
if (tipoModal == typeof (MDFeFerrov))
{
switch (MDFeConfiguracao.VersaoWebService.VersaoLayout)
{
case VersaoServico.Versao100:
Validador.Valida(xmlModal, "MDFeModalFerroviario_v1.00.xsd");
break;
case VersaoServico.Versao300:
Validador.Valida(xmlModal, "MDFeModalFerroviario_v3.00.xsd");
break;
}
}
return mdfe;
}
public static MDFEletronico Assina(this MDFEletronico mdfe, EventHandler<string> eventHandlerChaveMdfe = null, object quemInvocouEventoChaveMDFe = null)
{
if(mdfe == null) throw new ArgumentException("Erro de assinatura, MDFe esta null");
var modeloDocumentoFiscal = mdfe.InfMDFe.Ide.Mod;
var tipoEmissao = (int) mdfe.InfMDFe.Ide.TpEmis;
var codigoNumerico = mdfe.InfMDFe.Ide.CMDF;
var estado = mdfe.InfMDFe.Ide.CUF;
var dataEHoraEmissao = mdfe.InfMDFe.Ide.DhEmi;
var cnpj = mdfe.InfMDFe.Emit.CNPJ;
var numeroDocumento = mdfe.InfMDFe.Ide.NMDF;
int serie = mdfe.InfMDFe.Ide.Serie;
if (cnpj == null)
{
cnpj = mdfe.InfMDFe.Emit.CPF.PadLeft(14, '0');
}
var dadosChave = ChaveFiscal.ObterChave(estado, dataEHoraEmissao, cnpj, modeloDocumentoFiscal, serie, numeroDocumento, tipoEmissao, codigoNumerico);
mdfe.InfMDFe.Id = "MDFe" + dadosChave.Chave;
if (eventHandlerChaveMdfe != null)
eventHandlerChaveMdfe.Invoke(quemInvocouEventoChaveMDFe, dadosChave.Chave);
mdfe.InfMDFe.Versao = MDFeConfiguracao.VersaoWebService.VersaoLayout;
mdfe.InfMDFe.Ide.CDV = dadosChave.DigitoVerificador;
var assinatura = AssinaturaDigital.Assina(mdfe, mdfe.InfMDFe.Id, MDFeConfiguracao.X509Certificate2);
mdfe.Signature = assinatura;
return mdfe;
}
public static string XmlString(this MDFEletronico mdfe)
{
return FuncoesXml.ClasseParaXmlString(mdfe);
}
public static void SalvarXmlEmDisco(this MDFEletronico mdfe, string nomeArquivo = null)
{
if (MDFeConfiguracao.NaoSalvarXml()) return;
if (string.IsNullOrEmpty(nomeArquivo))
nomeArquivo = Path.Combine(MDFeConfiguracao.CaminhoSalvarXml, mdfe.Chave() + "-mdfe.xml");
FuncoesXml.ClasseParaArquivoXml(mdfe, nomeArquivo);
}
public static string Chave(this MDFEletronico mdfe)
{
var chave = mdfe.InfMDFe.Id.Substring(4, 44);
return chave;
}
public static int AmbienteSefazInt(this MDFEletronico mdfe)
{
var ambiente = mdfe.InfMDFe.Ide.TpAmb;
return (int) ambiente;
}
public static string CNPJEmitente(this MDFEletronico mdfe)
{
var cnpj = mdfe.InfMDFe.Emit.CNPJ;
return cnpj;
}
public static string CPFEmitente(this MDFEletronico mdfe)
{
var cpf = mdfe.InfMDFe.Emit.CPF;
return cpf;
}
public static string CNPJouCPFEmitente(this MDFEletronico mdfe)
{
var cnpj = CNPJEmitente(mdfe);
if (cnpj != null) return cnpj;
return CPFEmitente(mdfe).PadLeft(14, '0');
}
public static Estado UFEmitente(this MDFEletronico mdfe)
{
var estadoUf = mdfe.InfMDFe.Emit.EnderEmit.UF;
return estadoUf;
}
public static long CodigoIbgeMunicipioEmitente(this MDFEletronico mdfe)
{
var codigo = mdfe.InfMDFe.Emit.EnderEmit.CMun;
return codigo;
}
public static infMDFeSupl QrCode(this MDFEletronico mdfe, X509Certificate2 certificadoDigital,
Encoding encoding = null)
{
if (encoding == null)
encoding = Encoding.UTF8;
var qrCode = new StringBuilder(@"https://dfe-portal.svrs.rs.gov.br/mdfe/qrCode");
qrCode.Append("?");
qrCode.Append("chMDFe=").Append(mdfe.Chave());
qrCode.Append("&");
qrCode.Append("tpAmb=").Append(mdfe.AmbienteSefazInt());
switch (mdfe.InfMDFe.Ide.TpEmis)
{
case MDFeTipoEmissao.Contingencia:
var assinatura = Convert.ToBase64String(CreateSignaturePkcs1(certificadoDigital, encoding.GetBytes(mdfe.Chave())));
qrCode.Append("&sign=");
qrCode.Append(assinatura);
break;
}
return new infMDFeSupl
{
qrCodMDFe = qrCode.ToString()
};
}
private static byte[] CreateSignaturePkcs1(X509Certificate2 certificado, byte[] Value)
{
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)certificado.PrivateKey;
RSAPKCS1SignatureFormatter rsaF = new RSAPKCS1SignatureFormatter(rsa);
SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
byte[] hash = null;
hash = sha1.ComputeHash(Value);
rsaF.SetHashAlgorithm("SHA1");
return rsaF.CreateSignature(hash);
}
}
}
|
adrbarros/Zeus.Net.NFe.NFCe
|
MDFe.Classes/Extensoes/ExtMDFe.cs
|
C#
|
lgpl-2.1
| 10,935
|
/****************************************************************************
**
** 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 DEFAULT_CONTAINER_H
#define DEFAULT_CONTAINER_H
#include <QtDesigner/QDesignerContainerExtension>
#include <QtDesigner/extension.h>
#include <extensionfactory_p.h>
#include <QtGui/QStackedWidget>
#include <QtGui/QTabWidget>
#include <QtGui/QToolBox>
#include <QtGui/QScrollArea>
#include <QtGui/QDockWidget>
QT_BEGIN_NAMESPACE
namespace qdesigner_internal {
// ------------ QStackedWidgetContainer
class QStackedWidgetContainer: public QObject, public QDesignerContainerExtension
{
Q_OBJECT
Q_INTERFACES(QDesignerContainerExtension)
public:
explicit QStackedWidgetContainer(QStackedWidget *widget, QObject *parent = 0);
virtual int count() const { return m_widget->count(); }
virtual QWidget *widget(int index) const { return m_widget->widget(index); }
virtual int currentIndex() const { return m_widget->currentIndex(); }
virtual void setCurrentIndex(int index);
virtual void addWidget(QWidget *widget);
virtual void insertWidget(int index, QWidget *widget);
virtual void remove(int index);
private:
QStackedWidget *m_widget;
};
// ------------ QTabWidgetContainer
class QTabWidgetContainer: public QObject, public QDesignerContainerExtension
{
Q_OBJECT
Q_INTERFACES(QDesignerContainerExtension)
public:
explicit QTabWidgetContainer(QTabWidget *widget, QObject *parent = 0);
virtual int count() const { return m_widget->count(); }
virtual QWidget *widget(int index) const { return m_widget->widget(index); }
virtual int currentIndex() const { return m_widget->currentIndex(); }
virtual void setCurrentIndex(int index);
virtual void addWidget(QWidget *widget);
virtual void insertWidget(int index, QWidget *widget);
virtual void remove(int index);
private:
QTabWidget *m_widget;
};
// ------------ QToolBoxContainer
class QToolBoxContainer: public QObject, public QDesignerContainerExtension
{
Q_OBJECT
Q_INTERFACES(QDesignerContainerExtension)
public:
explicit QToolBoxContainer(QToolBox *widget, QObject *parent = 0);
virtual int count() const { return m_widget->count(); }
virtual QWidget *widget(int index) const { return m_widget->widget(index); }
virtual int currentIndex() const { return m_widget->currentIndex(); }
virtual void setCurrentIndex(int index);
virtual void addWidget(QWidget *widget);
virtual void insertWidget(int index, QWidget *widget);
virtual void remove(int index);
private:
QToolBox *m_widget;
};
// ------------ SingleChildContainer:
// Template for containers that have a single child widget using widget()/setWidget().
template <class Container>
class SingleChildContainer: public QDesignerContainerExtension
{
protected:
explicit SingleChildContainer(Container *widget, bool active = true);
public:
virtual int count() const;
virtual QWidget *widget(int index) const;
virtual int currentIndex() const;
virtual void setCurrentIndex(int /*index*/) {}
virtual void addWidget(QWidget *widget);
virtual void insertWidget(int index, QWidget *widget);
virtual void remove(int /*index*/) {}
private:
const bool m_active;
Container *m_container;
};
template <class Container>
SingleChildContainer<Container>::SingleChildContainer(Container *widget, bool active) :
m_active(active),
m_container(widget)
{
}
template <class Container>
int SingleChildContainer<Container>::count() const
{
return m_active && m_container->widget() ? 1 : 0;
}
template <class Container>
QWidget *SingleChildContainer<Container>::widget(int /* index */) const
{
return m_container->widget();
}
template <class Container>
int SingleChildContainer<Container>::currentIndex() const
{
return m_active && m_container->widget() ? 0 : -1;
}
template <class Container>
void SingleChildContainer<Container>::addWidget(QWidget *widget)
{
Q_ASSERT(m_container->widget() == 0);
widget->setParent(m_container);
m_container->setWidget(widget);
}
template <class Container>
void SingleChildContainer<Container>::insertWidget(int /* index */, QWidget *widget)
{
addWidget(widget);
}
// ------------ QScrollAreaContainer
class QScrollAreaContainer: public QObject, public SingleChildContainer<QScrollArea>
{
Q_OBJECT
Q_INTERFACES(QDesignerContainerExtension)
public:
explicit QScrollAreaContainer(QScrollArea *widget, QObject *parent = 0);
};
// --------------- QDockWidgetContainer
class QDockWidgetContainer: public QObject, public SingleChildContainer<QDockWidget>
{
Q_OBJECT
Q_INTERFACES(QDesignerContainerExtension)
public:
explicit QDockWidgetContainer(QDockWidget *widget, QObject *parent = 0);
};
typedef ExtensionFactory<QDesignerContainerExtension, QStackedWidget, QStackedWidgetContainer> QDesignerStackedWidgetContainerFactory;
typedef ExtensionFactory<QDesignerContainerExtension, QTabWidget, QTabWidgetContainer> QDesignerTabWidgetContainerFactory;
typedef ExtensionFactory<QDesignerContainerExtension, QToolBox, QToolBoxContainer> QDesignerToolBoxContainerFactory;
typedef ExtensionFactory<QDesignerContainerExtension, QScrollArea, QScrollAreaContainer> QScrollAreaContainerFactory;
typedef ExtensionFactory<QDesignerContainerExtension, QDockWidget, QDockWidgetContainer> QDockWidgetContainerFactory;
} // namespace qdesigner_internal
QT_END_NAMESPACE
#endif // DEFAULT_CONTAINER_H
|
igor-sfdc/qt-wk
|
tools/designer/src/components/formeditor/default_container.h
|
C
|
lgpl-2.1
| 6,850
|
/*
csound_type_system.c:
Copyright (C) 2012,2013 Steven Yi
This file is part of Csound.
The Csound Library is free software; you can redistribute it
and/or modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
Csound is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Csound; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
*/
#include "csound_type_system.h"
#include <string.h>
#include <stdio.h>
#include "csoundCore.h"
int csTypeExistsWithSameName(TYPE_POOL* pool, CS_TYPE* typeInstance) {
CS_TYPE_ITEM* current = pool->head;
while (current != NULL) {
/* printf("Search if type [%s] == [%s]",
current->varTypeName, typeInstance->varTypeName); */
if (strcmp(current->cstype->varTypeName,
typeInstance->varTypeName) == 0) {
return 1;
}
current = current->next;
}
return 0;
}
CS_TYPE* csoundGetTypeWithVarTypeName(TYPE_POOL* pool, char* typeName) {
CS_TYPE_ITEM* current = pool->head;
while (current != NULL) {
if (strcmp(typeName, current->cstype->varTypeName) == 0) {
return current->cstype;
}
current = current->next;
}
return NULL;
}
CS_TYPE* csoundGetTypeForVarName(TYPE_POOL* pool, char* varName) {
CS_TYPE_ITEM* current = pool->head;
char temp[2];
temp[0] = varName[0];
temp[1] = 0;
while (current != NULL) {
if (strcmp(temp, current->cstype->varTypeName) == 0) {
return current->cstype;
}
current = current->next;
}
return NULL;
}
int csoundAddVariableType(CSOUND* csound, TYPE_POOL* pool, CS_TYPE* typeInstance)
{
CS_TYPE_ITEM* item;
if (csTypeExistsWithSameName(pool, typeInstance)) {
return 0;
}
item = (CS_TYPE_ITEM*)csound->Calloc(csound, sizeof(CS_TYPE_ITEM));
item->cstype = typeInstance;
if (pool->head == NULL) {
pool->head = item;
} else {
CS_TYPE_ITEM* current = pool->head;
while (current->next) {
current = current->next;
}
current->next = item;
item->next = NULL;
}
/* printf("Adding type with type name: %s\n", typeInstance->varTypeName); */
return 1;
}
/* VAR POOL FUNCTIONS */
CS_VAR_POOL* csoundCreateVarPool(CSOUND* csound) {
CS_VAR_POOL* varPool = csound->Calloc(csound, sizeof(CS_VAR_POOL));
varPool->table = cs_hash_table_create(csound);
return varPool;
}
void csoundFreeVarPool(CSOUND* csound, CS_VAR_POOL* pool) {
if(pool->table) cs_hash_table_mfree_complete(csound, pool->table);
csound->Free(csound, pool);
}
char* getVarSimpleName(CSOUND* csound, const char* varName) {
char* retVal;
if (varName[0] != '[') {
retVal = (char*)csound->Calloc(csound, sizeof(char) * (strlen(varName) + 1));
strcpy(retVal, varName);
} else {
int start = 0;
int typeEnd = 0;
int len = strlen(varName);
int newFirstLen, newSecondLen, newTotalLen;
char* t = (char*) varName;
char* t2;
while(*t == '[') {
t++;
start++;
}
typeEnd = start;
t2 = t;
while(*t2 != ']' && *t2 != (char)0) {
t2++;
typeEnd++;
}
t2++;
typeEnd++;
newFirstLen = (typeEnd - start - 1);
newSecondLen = (len - typeEnd);
newTotalLen = newFirstLen + newSecondLen;
retVal = (char*)csound->Calloc(csound, sizeof(char) * (newTotalLen + 1));
strncpy(retVal, t, newFirstLen);
strncpy(retVal + newFirstLen, t2, newSecondLen);
}
return retVal;
}
CS_VARIABLE* csoundCreateVariable(void* csound, TYPE_POOL* pool,
CS_TYPE* type, char* name, void* typeArg)
{
CS_TYPE_ITEM* current = pool->head;
if(type != NULL)
while (current != NULL) {
if (strcmp(type->varTypeName, current->cstype->varTypeName) == 0) {
CS_VARIABLE* var = current->cstype->createVariable(csound, typeArg);
var->varType = type;
var->varName = cs_strdup(csound, name);
return var;
}
current = current->next;
}
else ((CSOUND *)csound)->ErrorMsg(csound,
"cannot create variable %s: NULL type", name);
return NULL;
}
//CS_VARIABLE* csoundFindVariableWithName(CSOUND* csound, CS_VAR_POOL* pool,
// const char* name) {
CS_VARIABLE* csoundFindVariableWithName(CSOUND* csound, CS_VAR_POOL* pool,
const char* name)
{
CS_VARIABLE* returnValue = cs_hash_table_get(csound, pool->table, (char*)name);
if (returnValue == NULL && pool->parent != NULL) {
returnValue = csoundFindVariableWithName(csound, pool->parent, name);
}
return returnValue;
}
CS_VARIABLE* csoundGetVariable(CS_VAR_POOL* pool, int index) {
CS_VARIABLE* current = pool->head;
int i;
for(i = 0; i < index || current != NULL; i++) {
/* THIS WAS WRONG!! && or || meant foR , ?? */
current = current->next;
}
return current;
}
//int csoundGetVariableIndex(CS_VAR_POOL* pool, CS_VARIABLE* var) {
// CS_VARIABLE* current = pool->head;
// int index = 0;
//
// if (current == NULL) {
// return -1;
// }
//
// for (index = 0; current != NULL; index++) {
// if (current == var) {
// return index;
// }
// }
// return -1;
//}
int csoundAddVariable(CSOUND* csound, CS_VAR_POOL* pool, CS_VARIABLE* var) {
if(var != NULL) {
if(pool->head == NULL) {
pool->head = var;
pool->tail = var;
} else {
pool->tail->next = var;
pool->tail = var;
}
cs_hash_table_put(csound, pool->table, var->varName, var);
// may need to revise this; var pools are accessed as MYFLT*,
// so need to ensure all memory is aligned to sizeof(MYFLT)
// boundaries maybe should align block size here to +7 before dividing?
var->memBlockIndex = (pool->poolSize / sizeof(MYFLT)) + (pool->varCount + 1);
pool->poolSize += var->memBlockSize;
pool->varCount += 1;
return 0;
} else return -1;
}
void recalculateVarPoolMemory(void* csound, CS_VAR_POOL* pool)
{
CS_VARIABLE* current = pool->head;
int varCount = 1;
pool->poolSize = 0;
while (current != NULL) {
/* VL 26-12-12: had to revert these lines to avoid memory crashes
with higher ksmps */
if(current->updateMemBlockSize != NULL) {
current->updateMemBlockSize(csound, current);
}
current->memBlockIndex = (pool->poolSize / sizeof(MYFLT)) + varCount;
pool->poolSize += current->memBlockSize;
current = current->next;
varCount++;
}
}
void reallocateVarPoolMemory(void* csound, CS_VAR_POOL* pool) {
CS_VARIABLE* current = pool->head;
CS_VAR_MEM* varMem = NULL;
size_t memSize;
pool->poolSize = 0;
while (current != NULL) {
varMem = current->memBlock;
memSize = current->memBlockSize;
if(current->updateMemBlockSize != NULL) {
current->updateMemBlockSize(csound, current);
}
// VL 14-3-2015 only realloc if we need to
if(memSize < current->memBlockSize) {
memSize = sizeof(CS_VAR_MEM) - sizeof(MYFLT) + current->memBlockSize;
varMem =
(CS_VAR_MEM *)((CSOUND *)csound)->ReAlloc(csound,varMem,
memSize);
current->memBlock = varMem;
}
pool->poolSize += current->memBlockSize;
current = current->next;
}
}
void deleteVarPoolMemory(void* csnd, CS_VAR_POOL* pool) {
CS_VARIABLE* current = pool->head, *tmp;
CSOUND *csound = (CSOUND *)csnd;
CS_TYPE* type;
while (current != NULL) {
tmp = current;
type = current->subType;
if (type->freeVariableMemory != NULL) {
type->freeVariableMemory(csound, current->memBlock);
}
csound->Free(csound, current->memBlock);
current = current->next;
csound->Free(csound, tmp);
}
}
void initializeVarPool(MYFLT* memBlock, CS_VAR_POOL* pool) {
CS_VARIABLE* current = pool->head;
int varNum = 1;
while (current != NULL) {
if (current->initializeVariableMemory != NULL) {
current->initializeVariableMemory(current,
memBlock + current->memBlockIndex);
}
varNum++;
current = current->next;
}
}
void debug_print_varpool(CSOUND* csound, CS_VAR_POOL* pool) {
CS_VARIABLE* gVar = pool->head;
int count = 0;
while(gVar != NULL) {
csound->Message(csound, " %d) %s:%s\n", count++,
gVar->varName, gVar->varType->varTypeName);
gVar = gVar->next;
}
}
|
max-ilse/csound
|
Engine/csound_type_system.c
|
C
|
lgpl-2.1
| 9,081
|
package com.sun.pdfview.function.postscript.operation;
import java.util.Stack;
final class Mod implements PostScriptOperation {
@Override
/**
* <i>int1 int2</i> <b>mod</b> <i>remainder</i> <p>
*
* returns the remainder that results from
* dividing int1 by int2. The sign of the result
* is the same as the sign of the dividend int1.
* Both operands must be integers and the result
* is an integer. <p>
*
* errors: stackunderflow, typecheck, undefinedresult
*/
public void eval(Stack<Object> environment) {
long int2 = (Long)environment.pop();
long int1 = (Long)environment.pop();
environment.push(int1 % int2);
}
}
|
Pixplicity/PDFrenderer
|
src/com/sun/pdfview/function/postscript/operation/Mod.java
|
Java
|
lgpl-2.1
| 657
|
/**
inRange.cpp: A tester for discrete range queries on in-memory data.
Modified from smatch.cpp, which was originally by Bernd Jaenichen <bernd
dot jaenichen at globalpark dot com>, 2010/4/28.
usage:
inRange <datadir> [where_1 [where_2 ...]]
The datadir argument must be provided. If the user provides addition
arguments, they will be treated as where clauses to be evaluated one at
a time. This program was originally provided by Bernd to reveal a bug
in the string search function ibis::text::stringSearch.
*/
#include "ibis.h"
#include <memory> // std::auto_ptr
/// Encapsulate the testing functions.
class tester {
public:
tester();
~tester();
void load(const char *datadir);
void query(const char *datadir, const char *where);
private:
void builtindata(const char* datadir);
};
tester::tester() {
#if defined(_DEBUG)
ibis::util::setVerboseLevel(5);
#elif defined(DEBUG)
ibis::util::setVerboseLevel(7);
#endif
}
tester::~tester() {
}
/// Generate some records. Use ibis::tablex interface and
/// ibis::table::row. The integer records go from 1 to 16, with the value
/// J repeated J times.
void tester::builtindata(const char *datadir) {
ibis::table::row irow;
std::auto_ptr<ibis::tablex> ta(ibis::tablex::create());
ta->addColumn("l", ibis::LONG);
irow.longsnames.push_back("l");
irow.longsvalues.resize(1);
for (int j = 1; j < 16; ++ j) {
irow.longsvalues.back() = j;
for (int i = 0; i < j; ++ i)
ta->appendRow(irow);
}
ta->write(datadir);
LOGGER(ibis::gVerbose > 0)
<< "generated " << ta->mRows() << " rows in directory " << datadir;
}
/// Load the data in the specified directory. If the directory contains
/// nothing it will generate some records using the function builtindata.
/// If some data records are found, it will run a minimal test that counts
/// the number of records.
void tester::load(const char *datadir) {
if (datadir == 0 || *datadir == 0) return;
try { // use existing data records
std::auto_ptr<ibis::table> table(ibis::table::create(datadir));
if (table.get() == 0) {
LOGGER(ibis::gVerbose >= 0)
<< "failed to load table from " << datadir;
return;
}
if (table->nRows() == 0 || table->nColumns() == 0) {
// empty or non-existent directory, create new data
builtindata(datadir);
table->addPartition(datadir);
}
std::auto_ptr<ibis::table> select(table->select("", "1=1"));
if (select.get() == 0) {
LOGGER(ibis::gVerbose >= 0)
<< "failed to select all rows from table " << table->name();
return;
}
LOGGER(select->nRows() != table->nRows() && ibis::gVerbose >= 0)
<< "expected to select " << table->nRows() << " row"
<< (table->nRows()>1?"s":"") << ", but got " << select->nRows();
}
catch (...) { // generate hard-coded data records
builtindata(datadir);
}
} // tester::load
/// Evaluate the query condition where on the data records in directory
/// datadir. Make use of the ibis::table interface. It retrieves the
/// values of the first column as strings after evaluating the query
/// conditions.
void tester::query(const char *datadir, const char *where) {
if (datadir == 0 || where == 0 || *datadir == 0 || *where == 0) return;
std::auto_ptr<ibis::table> table(ibis::table::create(datadir));
if (table.get() == 0) {
LOGGER(ibis::gVerbose >= 0)
<< "failed to load table from " << datadir;
return;
}
if (table->name() == 0 || *(table->name()) == 0) {
LOGGER(ibis::gVerbose >= 0)
<< "failed to find any data records in directory " << datadir;
return;
}
if (table->nColumns() == 0) {
LOGGER(ibis::gVerbose >= 0)
<< "Table " << table->name() << " in " << datadir << " is empty";
return;
}
ibis::table::stringList cnames = table->columnNames();
if (cnames.empty()) {
LOGGER(ibis::gVerbose >= 0)
<< "failed to retrieve column names from table " << table->name()
<< " in " << datadir;
return;
}
std::string selall = cnames.front();
for (unsigned j = 1; j < cnames.size(); ++ j) {
selall += ", ";
selall += cnames[j];
}
// create in-memory table to process where
std::auto_ptr<ibis::table> inmemory(table->select(selall.c_str(), "1=1"));
if (inmemory.get() == 0) {
LOGGER(ibis::gVerbose >= 0)
<< "failed to select all rows from table " << table->name();
return;
}
if (ibis::gVerbose > 0) { // an extra test with group-by
std::auto_ptr<ibis::table> groupby(inmemory->groupby(cnames.front()));
if (groupby.get() == 0) {
LOGGER(ibis::gVerbose > 0)
<< "failed to evaluate groupby(" << cnames.front()
<< " on table " << inmemory->name();
}
else {
std::cout << "\nThe result of groupby(" << cnames.front() << ")\n";
groupby->dump(std::cout);
std::cout << std::endl;
}
}
std::string sel1 = cnames.front();
sel1 += ", count(*)";
std::auto_ptr<ibis::table> select(inmemory->select(sel1.c_str(), where));
if (select.get() == 0) {
LOGGER(ibis::gVerbose >= 0)
<< "failed to select \"" << where << "\" on table"
<< inmemory->name();
return;
}
std::cout << "Number of rows produced by \"SELECT " << sel1
<< " WHERE " << where << "\": "
<< select->nRows() << std::endl;
select->dump(std::cout);
} // tester::query
int main(int argc, char** argv) {
if (argc < 2) {
printf("\nUsage:\n%s <datadir> [where_clause1] [where_clause2...]\n\n",
*argv);
return 0;
}
char *datadir = argv[1];
tester test0r;
test0r.load(datadir);
//ibis::gVerbose = 6;
if (argc == 2) { // try some built-in tests
test0r.query(datadir, "l IN (1,2)");
test0r.query(datadir, "l IN (1)");
test0r.query(datadir, "l IN (3)");
test0r.query(datadir, "l IN (1,3)");
}
for (int iarg = 2; iarg < argc; ++ iarg)
test0r.query(datadir, argv[iarg]);
return 0;
} // main
|
biddisco/fastbit
|
tests/inRange.cpp
|
C++
|
lgpl-2.1
| 5,904
|
/**
* \file
*
* \brief Peripheral I/O description for SAMD21E15A
*
* Copyright (c) 2014 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* 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. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifndef _SAMD21E15A_PIO_
#define _SAMD21E15A_PIO_
#define PIN_PA00 0 /**< \brief Pin Number for PA00 */
#define PORT_PA00 (1u << 0) /**< \brief PORT Mask for PA00 */
#define PIN_PA01 1 /**< \brief Pin Number for PA01 */
#define PORT_PA01 (1u << 1) /**< \brief PORT Mask for PA01 */
#define PIN_PA02 2 /**< \brief Pin Number for PA02 */
#define PORT_PA02 (1u << 2) /**< \brief PORT Mask for PA02 */
#define PIN_PA03 3 /**< \brief Pin Number for PA03 */
#define PORT_PA03 (1u << 3) /**< \brief PORT Mask for PA03 */
#define PIN_PA04 4 /**< \brief Pin Number for PA04 */
#define PORT_PA04 (1u << 4) /**< \brief PORT Mask for PA04 */
#define PIN_PA05 5 /**< \brief Pin Number for PA05 */
#define PORT_PA05 (1u << 5) /**< \brief PORT Mask for PA05 */
#define PIN_PA06 6 /**< \brief Pin Number for PA06 */
#define PORT_PA06 (1u << 6) /**< \brief PORT Mask for PA06 */
#define PIN_PA07 7 /**< \brief Pin Number for PA07 */
#define PORT_PA07 (1u << 7) /**< \brief PORT Mask for PA07 */
#define PIN_PA08 8 /**< \brief Pin Number for PA08 */
#define PORT_PA08 (1u << 8) /**< \brief PORT Mask for PA08 */
#define PIN_PA09 9 /**< \brief Pin Number for PA09 */
#define PORT_PA09 (1u << 9) /**< \brief PORT Mask for PA09 */
#define PIN_PA10 10 /**< \brief Pin Number for PA10 */
#define PORT_PA10 (1u << 10) /**< \brief PORT Mask for PA10 */
#define PIN_PA11 11 /**< \brief Pin Number for PA11 */
#define PORT_PA11 (1u << 11) /**< \brief PORT Mask for PA11 */
#define PIN_PA14 14 /**< \brief Pin Number for PA14 */
#define PORT_PA14 (1u << 14) /**< \brief PORT Mask for PA14 */
#define PIN_PA15 15 /**< \brief Pin Number for PA15 */
#define PORT_PA15 (1u << 15) /**< \brief PORT Mask for PA15 */
#define PIN_PA16 16 /**< \brief Pin Number for PA16 */
#define PORT_PA16 (1u << 16) /**< \brief PORT Mask for PA16 */
#define PIN_PA17 17 /**< \brief Pin Number for PA17 */
#define PORT_PA17 (1u << 17) /**< \brief PORT Mask for PA17 */
#define PIN_PA18 18 /**< \brief Pin Number for PA18 */
#define PORT_PA18 (1u << 18) /**< \brief PORT Mask for PA18 */
#define PIN_PA19 19 /**< \brief Pin Number for PA19 */
#define PORT_PA19 (1u << 19) /**< \brief PORT Mask for PA19 */
#define PIN_PA22 22 /**< \brief Pin Number for PA22 */
#define PORT_PA22 (1u << 22) /**< \brief PORT Mask for PA22 */
#define PIN_PA23 23 /**< \brief Pin Number for PA23 */
#define PORT_PA23 (1u << 23) /**< \brief PORT Mask for PA23 */
#define PIN_PA24 24 /**< \brief Pin Number for PA24 */
#define PORT_PA24 (1u << 24) /**< \brief PORT Mask for PA24 */
#define PIN_PA25 25 /**< \brief Pin Number for PA25 */
#define PORT_PA25 (1u << 25) /**< \brief PORT Mask for PA25 */
#define PIN_PA27 27 /**< \brief Pin Number for PA27 */
#define PORT_PA27 (1u << 27) /**< \brief PORT Mask for PA27 */
#define PIN_PA28 28 /**< \brief Pin Number for PA28 */
#define PORT_PA28 (1u << 28) /**< \brief PORT Mask for PA28 */
#define PIN_PA30 30 /**< \brief Pin Number for PA30 */
#define PORT_PA30 (1u << 30) /**< \brief PORT Mask for PA30 */
#define PIN_PA31 31 /**< \brief Pin Number for PA31 */
#define PORT_PA31 (1u << 31) /**< \brief PORT Mask for PA31 */
/* ========== PORT definition for CORE peripheral ========== */
#define PIN_PA30G_CORE_SWCLK 30 /**< \brief CORE signal: SWCLK on PA30 mux G */
#define MUX_PA30G_CORE_SWCLK 6
#define PINMUX_PA30G_CORE_SWCLK ((PIN_PA30G_CORE_SWCLK << 16) | MUX_PA30G_CORE_SWCLK)
#define PORT_PA30G_CORE_SWCLK (1u << 30)
/* ========== PORT definition for GCLK peripheral ========== */
#define PIN_PA14H_GCLK_IO0 14 /**< \brief GCLK signal: IO0 on PA14 mux H */
#define MUX_PA14H_GCLK_IO0 7
#define PINMUX_PA14H_GCLK_IO0 ((PIN_PA14H_GCLK_IO0 << 16) | MUX_PA14H_GCLK_IO0)
#define PORT_PA14H_GCLK_IO0 (1u << 14)
#define PIN_PA27H_GCLK_IO0 27 /**< \brief GCLK signal: IO0 on PA27 mux H */
#define MUX_PA27H_GCLK_IO0 7
#define PINMUX_PA27H_GCLK_IO0 ((PIN_PA27H_GCLK_IO0 << 16) | MUX_PA27H_GCLK_IO0)
#define PORT_PA27H_GCLK_IO0 (1u << 27)
#define PIN_PA28H_GCLK_IO0 28 /**< \brief GCLK signal: IO0 on PA28 mux H */
#define MUX_PA28H_GCLK_IO0 7
#define PINMUX_PA28H_GCLK_IO0 ((PIN_PA28H_GCLK_IO0 << 16) | MUX_PA28H_GCLK_IO0)
#define PORT_PA28H_GCLK_IO0 (1u << 28)
#define PIN_PA30H_GCLK_IO0 30 /**< \brief GCLK signal: IO0 on PA30 mux H */
#define MUX_PA30H_GCLK_IO0 7
#define PINMUX_PA30H_GCLK_IO0 ((PIN_PA30H_GCLK_IO0 << 16) | MUX_PA30H_GCLK_IO0)
#define PORT_PA30H_GCLK_IO0 (1u << 30)
#define PIN_PA15H_GCLK_IO1 15 /**< \brief GCLK signal: IO1 on PA15 mux H */
#define MUX_PA15H_GCLK_IO1 7
#define PINMUX_PA15H_GCLK_IO1 ((PIN_PA15H_GCLK_IO1 << 16) | MUX_PA15H_GCLK_IO1)
#define PORT_PA15H_GCLK_IO1 (1u << 15)
#define PIN_PA16H_GCLK_IO2 16 /**< \brief GCLK signal: IO2 on PA16 mux H */
#define MUX_PA16H_GCLK_IO2 7
#define PINMUX_PA16H_GCLK_IO2 ((PIN_PA16H_GCLK_IO2 << 16) | MUX_PA16H_GCLK_IO2)
#define PORT_PA16H_GCLK_IO2 (1u << 16)
#define PIN_PA17H_GCLK_IO3 17 /**< \brief GCLK signal: IO3 on PA17 mux H */
#define MUX_PA17H_GCLK_IO3 7
#define PINMUX_PA17H_GCLK_IO3 ((PIN_PA17H_GCLK_IO3 << 16) | MUX_PA17H_GCLK_IO3)
#define PORT_PA17H_GCLK_IO3 (1u << 17)
#define PIN_PA10H_GCLK_IO4 10 /**< \brief GCLK signal: IO4 on PA10 mux H */
#define MUX_PA10H_GCLK_IO4 7
#define PINMUX_PA10H_GCLK_IO4 ((PIN_PA10H_GCLK_IO4 << 16) | MUX_PA10H_GCLK_IO4)
#define PORT_PA10H_GCLK_IO4 (1u << 10)
#define PIN_PA11H_GCLK_IO5 11 /**< \brief GCLK signal: IO5 on PA11 mux H */
#define MUX_PA11H_GCLK_IO5 7
#define PINMUX_PA11H_GCLK_IO5 ((PIN_PA11H_GCLK_IO5 << 16) | MUX_PA11H_GCLK_IO5)
#define PORT_PA11H_GCLK_IO5 (1u << 11)
#define PIN_PA22H_GCLK_IO6 22 /**< \brief GCLK signal: IO6 on PA22 mux H */
#define MUX_PA22H_GCLK_IO6 7
#define PINMUX_PA22H_GCLK_IO6 ((PIN_PA22H_GCLK_IO6 << 16) | MUX_PA22H_GCLK_IO6)
#define PORT_PA22H_GCLK_IO6 (1u << 22)
#define PIN_PA23H_GCLK_IO7 23 /**< \brief GCLK signal: IO7 on PA23 mux H */
#define MUX_PA23H_GCLK_IO7 7
#define PINMUX_PA23H_GCLK_IO7 ((PIN_PA23H_GCLK_IO7 << 16) | MUX_PA23H_GCLK_IO7)
#define PORT_PA23H_GCLK_IO7 (1u << 23)
/* ========== PORT definition for EIC peripheral ========== */
#define PIN_PA16A_EIC_EXTINT0 16 /**< \brief EIC signal: EXTINT0 on PA16 mux A */
#define MUX_PA16A_EIC_EXTINT0 0
#define PINMUX_PA16A_EIC_EXTINT0 ((PIN_PA16A_EIC_EXTINT0 << 16) | MUX_PA16A_EIC_EXTINT0)
#define PORT_PA16A_EIC_EXTINT0 (1u << 16)
#define PIN_PA00A_EIC_EXTINT0 0 /**< \brief EIC signal: EXTINT0 on PA00 mux A */
#define MUX_PA00A_EIC_EXTINT0 0
#define PINMUX_PA00A_EIC_EXTINT0 ((PIN_PA00A_EIC_EXTINT0 << 16) | MUX_PA00A_EIC_EXTINT0)
#define PORT_PA00A_EIC_EXTINT0 (1u << 0)
#define PIN_PA17A_EIC_EXTINT1 17 /**< \brief EIC signal: EXTINT1 on PA17 mux A */
#define MUX_PA17A_EIC_EXTINT1 0
#define PINMUX_PA17A_EIC_EXTINT1 ((PIN_PA17A_EIC_EXTINT1 << 16) | MUX_PA17A_EIC_EXTINT1)
#define PORT_PA17A_EIC_EXTINT1 (1u << 17)
#define PIN_PA01A_EIC_EXTINT1 1 /**< \brief EIC signal: EXTINT1 on PA01 mux A */
#define MUX_PA01A_EIC_EXTINT1 0
#define PINMUX_PA01A_EIC_EXTINT1 ((PIN_PA01A_EIC_EXTINT1 << 16) | MUX_PA01A_EIC_EXTINT1)
#define PORT_PA01A_EIC_EXTINT1 (1u << 1)
#define PIN_PA18A_EIC_EXTINT2 18 /**< \brief EIC signal: EXTINT2 on PA18 mux A */
#define MUX_PA18A_EIC_EXTINT2 0
#define PINMUX_PA18A_EIC_EXTINT2 ((PIN_PA18A_EIC_EXTINT2 << 16) | MUX_PA18A_EIC_EXTINT2)
#define PORT_PA18A_EIC_EXTINT2 (1u << 18)
#define PIN_PA02A_EIC_EXTINT2 2 /**< \brief EIC signal: EXTINT2 on PA02 mux A */
#define MUX_PA02A_EIC_EXTINT2 0
#define PINMUX_PA02A_EIC_EXTINT2 ((PIN_PA02A_EIC_EXTINT2 << 16) | MUX_PA02A_EIC_EXTINT2)
#define PORT_PA02A_EIC_EXTINT2 (1u << 2)
#define PIN_PA03A_EIC_EXTINT3 3 /**< \brief EIC signal: EXTINT3 on PA03 mux A */
#define MUX_PA03A_EIC_EXTINT3 0
#define PINMUX_PA03A_EIC_EXTINT3 ((PIN_PA03A_EIC_EXTINT3 << 16) | MUX_PA03A_EIC_EXTINT3)
#define PORT_PA03A_EIC_EXTINT3 (1u << 3)
#define PIN_PA19A_EIC_EXTINT3 19 /**< \brief EIC signal: EXTINT3 on PA19 mux A */
#define MUX_PA19A_EIC_EXTINT3 0
#define PINMUX_PA19A_EIC_EXTINT3 ((PIN_PA19A_EIC_EXTINT3 << 16) | MUX_PA19A_EIC_EXTINT3)
#define PORT_PA19A_EIC_EXTINT3 (1u << 19)
#define PIN_PA04A_EIC_EXTINT4 4 /**< \brief EIC signal: EXTINT4 on PA04 mux A */
#define MUX_PA04A_EIC_EXTINT4 0
#define PINMUX_PA04A_EIC_EXTINT4 ((PIN_PA04A_EIC_EXTINT4 << 16) | MUX_PA04A_EIC_EXTINT4)
#define PORT_PA04A_EIC_EXTINT4 (1u << 4)
#define PIN_PA05A_EIC_EXTINT5 5 /**< \brief EIC signal: EXTINT5 on PA05 mux A */
#define MUX_PA05A_EIC_EXTINT5 0
#define PINMUX_PA05A_EIC_EXTINT5 ((PIN_PA05A_EIC_EXTINT5 << 16) | MUX_PA05A_EIC_EXTINT5)
#define PORT_PA05A_EIC_EXTINT5 (1u << 5)
#define PIN_PA06A_EIC_EXTINT6 6 /**< \brief EIC signal: EXTINT6 on PA06 mux A */
#define MUX_PA06A_EIC_EXTINT6 0
#define PINMUX_PA06A_EIC_EXTINT6 ((PIN_PA06A_EIC_EXTINT6 << 16) | MUX_PA06A_EIC_EXTINT6)
#define PORT_PA06A_EIC_EXTINT6 (1u << 6)
#define PIN_PA22A_EIC_EXTINT6 22 /**< \brief EIC signal: EXTINT6 on PA22 mux A */
#define MUX_PA22A_EIC_EXTINT6 0
#define PINMUX_PA22A_EIC_EXTINT6 ((PIN_PA22A_EIC_EXTINT6 << 16) | MUX_PA22A_EIC_EXTINT6)
#define PORT_PA22A_EIC_EXTINT6 (1u << 22)
#define PIN_PA07A_EIC_EXTINT7 7 /**< \brief EIC signal: EXTINT7 on PA07 mux A */
#define MUX_PA07A_EIC_EXTINT7 0
#define PINMUX_PA07A_EIC_EXTINT7 ((PIN_PA07A_EIC_EXTINT7 << 16) | MUX_PA07A_EIC_EXTINT7)
#define PORT_PA07A_EIC_EXTINT7 (1u << 7)
#define PIN_PA23A_EIC_EXTINT7 23 /**< \brief EIC signal: EXTINT7 on PA23 mux A */
#define MUX_PA23A_EIC_EXTINT7 0
#define PINMUX_PA23A_EIC_EXTINT7 ((PIN_PA23A_EIC_EXTINT7 << 16) | MUX_PA23A_EIC_EXTINT7)
#define PORT_PA23A_EIC_EXTINT7 (1u << 23)
#define PIN_PA28A_EIC_EXTINT8 28 /**< \brief EIC signal: EXTINT8 on PA28 mux A */
#define MUX_PA28A_EIC_EXTINT8 0
#define PINMUX_PA28A_EIC_EXTINT8 ((PIN_PA28A_EIC_EXTINT8 << 16) | MUX_PA28A_EIC_EXTINT8)
#define PORT_PA28A_EIC_EXTINT8 (1u << 28)
#define PIN_PA09A_EIC_EXTINT9 9 /**< \brief EIC signal: EXTINT9 on PA09 mux A */
#define MUX_PA09A_EIC_EXTINT9 0
#define PINMUX_PA09A_EIC_EXTINT9 ((PIN_PA09A_EIC_EXTINT9 << 16) | MUX_PA09A_EIC_EXTINT9)
#define PORT_PA09A_EIC_EXTINT9 (1u << 9)
#define PIN_PA10A_EIC_EXTINT10 10 /**< \brief EIC signal: EXTINT10 on PA10 mux A */
#define MUX_PA10A_EIC_EXTINT10 0
#define PINMUX_PA10A_EIC_EXTINT10 ((PIN_PA10A_EIC_EXTINT10 << 16) | MUX_PA10A_EIC_EXTINT10)
#define PORT_PA10A_EIC_EXTINT10 (1u << 10)
#define PIN_PA30A_EIC_EXTINT10 30 /**< \brief EIC signal: EXTINT10 on PA30 mux A */
#define MUX_PA30A_EIC_EXTINT10 0
#define PINMUX_PA30A_EIC_EXTINT10 ((PIN_PA30A_EIC_EXTINT10 << 16) | MUX_PA30A_EIC_EXTINT10)
#define PORT_PA30A_EIC_EXTINT10 (1u << 30)
#define PIN_PA18A_EIC_EXTINT10 18 /**< \brief EIC signal: EXTINT10 on PA18 mux A */
#define MUX_PA18A_EIC_EXTINT10 0
#define PINMUX_PA18A_EIC_EXTINT10 ((PIN_PA18A_EIC_EXTINT10 << 16) | MUX_PA18A_EIC_EXTINT10)
#define PORT_PA18A_EIC_EXTINT10 (1u << 18)
#define PIN_PA11A_EIC_EXTINT11 11 /**< \brief EIC signal: EXTINT11 on PA11 mux A */
#define MUX_PA11A_EIC_EXTINT11 0
#define PINMUX_PA11A_EIC_EXTINT11 ((PIN_PA11A_EIC_EXTINT11 << 16) | MUX_PA11A_EIC_EXTINT11)
#define PORT_PA11A_EIC_EXTINT11 (1u << 11)
#define PIN_PA31A_EIC_EXTINT11 31 /**< \brief EIC signal: EXTINT11 on PA31 mux A */
#define MUX_PA31A_EIC_EXTINT11 0
#define PINMUX_PA31A_EIC_EXTINT11 ((PIN_PA31A_EIC_EXTINT11 << 16) | MUX_PA31A_EIC_EXTINT11)
#define PORT_PA31A_EIC_EXTINT11 (1u << 31)
#define PIN_PA24A_EIC_EXTINT12 24 /**< \brief EIC signal: EXTINT12 on PA24 mux A */
#define MUX_PA24A_EIC_EXTINT12 0
#define PINMUX_PA24A_EIC_EXTINT12 ((PIN_PA24A_EIC_EXTINT12 << 16) | MUX_PA24A_EIC_EXTINT12)
#define PORT_PA24A_EIC_EXTINT12 (1u << 24)
#define PIN_PA25A_EIC_EXTINT13 25 /**< \brief EIC signal: EXTINT13 on PA25 mux A */
#define MUX_PA25A_EIC_EXTINT13 0
#define PINMUX_PA25A_EIC_EXTINT13 ((PIN_PA25A_EIC_EXTINT13 << 16) | MUX_PA25A_EIC_EXTINT13)
#define PORT_PA25A_EIC_EXTINT13 (1u << 25)
#define PIN_PA14A_EIC_EXTINT14 14 /**< \brief EIC signal: EXTINT14 on PA14 mux A */
#define MUX_PA14A_EIC_EXTINT14 0
#define PINMUX_PA14A_EIC_EXTINT14 ((PIN_PA14A_EIC_EXTINT14 << 16) | MUX_PA14A_EIC_EXTINT14)
#define PORT_PA14A_EIC_EXTINT14 (1u << 14)
#define PIN_PA15A_EIC_EXTINT15 15 /**< \brief EIC signal: EXTINT15 on PA15 mux A */
#define MUX_PA15A_EIC_EXTINT15 0
#define PINMUX_PA15A_EIC_EXTINT15 ((PIN_PA15A_EIC_EXTINT15 << 16) | MUX_PA15A_EIC_EXTINT15)
#define PORT_PA15A_EIC_EXTINT15 (1u << 15)
#define PIN_PA27A_EIC_EXTINT15 27 /**< \brief EIC signal: EXTINT15 on PA27 mux A */
#define MUX_PA27A_EIC_EXTINT15 0
#define PINMUX_PA27A_EIC_EXTINT15 ((PIN_PA27A_EIC_EXTINT15 << 16) | MUX_PA27A_EIC_EXTINT15)
#define PORT_PA27A_EIC_EXTINT15 (1u << 27)
#define PIN_PA08A_EIC_NMI 8 /**< \brief EIC signal: NMI on PA08 mux A */
#define MUX_PA08A_EIC_NMI 0
#define PINMUX_PA08A_EIC_NMI ((PIN_PA08A_EIC_NMI << 16) | MUX_PA08A_EIC_NMI)
#define PORT_PA08A_EIC_NMI (1u << 8)
/* ========== PORT definition for USB peripheral ========== */
#define PIN_PA24G_USB_DM 24 /**< \brief USB signal: DM on PA24 mux G */
#define MUX_PA24G_USB_DM 6
#define PINMUX_PA24G_USB_DM ((PIN_PA24G_USB_DM << 16) | MUX_PA24G_USB_DM)
#define PORT_PA24G_USB_DM (1u << 24)
#define PIN_PA25G_USB_DP 25 /**< \brief USB signal: DP on PA25 mux G */
#define MUX_PA25G_USB_DP 6
#define PINMUX_PA25G_USB_DP ((PIN_PA25G_USB_DP << 16) | MUX_PA25G_USB_DP)
#define PORT_PA25G_USB_DP (1u << 25)
#define PIN_PA23G_USB_SOF_1KHZ 23 /**< \brief USB signal: SOF_1KHZ on PA23 mux G */
#define MUX_PA23G_USB_SOF_1KHZ 6
#define PINMUX_PA23G_USB_SOF_1KHZ ((PIN_PA23G_USB_SOF_1KHZ << 16) | MUX_PA23G_USB_SOF_1KHZ)
#define PORT_PA23G_USB_SOF_1KHZ (1u << 23)
/* ========== PORT definition for SERCOM0 peripheral ========== */
#define PIN_PA04D_SERCOM0_PAD0 4 /**< \brief SERCOM0 signal: PAD0 on PA04 mux D */
#define MUX_PA04D_SERCOM0_PAD0 3
#define PINMUX_PA04D_SERCOM0_PAD0 ((PIN_PA04D_SERCOM0_PAD0 << 16) | MUX_PA04D_SERCOM0_PAD0)
#define PORT_PA04D_SERCOM0_PAD0 (1u << 4)
#define PIN_PA08C_SERCOM0_PAD0 8 /**< \brief SERCOM0 signal: PAD0 on PA08 mux C */
#define MUX_PA08C_SERCOM0_PAD0 2
#define PINMUX_PA08C_SERCOM0_PAD0 ((PIN_PA08C_SERCOM0_PAD0 << 16) | MUX_PA08C_SERCOM0_PAD0)
#define PORT_PA08C_SERCOM0_PAD0 (1u << 8)
#define PIN_PA05D_SERCOM0_PAD1 5 /**< \brief SERCOM0 signal: PAD1 on PA05 mux D */
#define MUX_PA05D_SERCOM0_PAD1 3
#define PINMUX_PA05D_SERCOM0_PAD1 ((PIN_PA05D_SERCOM0_PAD1 << 16) | MUX_PA05D_SERCOM0_PAD1)
#define PORT_PA05D_SERCOM0_PAD1 (1u << 5)
#define PIN_PA09C_SERCOM0_PAD1 9 /**< \brief SERCOM0 signal: PAD1 on PA09 mux C */
#define MUX_PA09C_SERCOM0_PAD1 2
#define PINMUX_PA09C_SERCOM0_PAD1 ((PIN_PA09C_SERCOM0_PAD1 << 16) | MUX_PA09C_SERCOM0_PAD1)
#define PORT_PA09C_SERCOM0_PAD1 (1u << 9)
#define PIN_PA06D_SERCOM0_PAD2 6 /**< \brief SERCOM0 signal: PAD2 on PA06 mux D */
#define MUX_PA06D_SERCOM0_PAD2 3
#define PINMUX_PA06D_SERCOM0_PAD2 ((PIN_PA06D_SERCOM0_PAD2 << 16) | MUX_PA06D_SERCOM0_PAD2)
#define PORT_PA06D_SERCOM0_PAD2 (1u << 6)
#define PIN_PA10C_SERCOM0_PAD2 10 /**< \brief SERCOM0 signal: PAD2 on PA10 mux C */
#define MUX_PA10C_SERCOM0_PAD2 2
#define PINMUX_PA10C_SERCOM0_PAD2 ((PIN_PA10C_SERCOM0_PAD2 << 16) | MUX_PA10C_SERCOM0_PAD2)
#define PORT_PA10C_SERCOM0_PAD2 (1u << 10)
#define PIN_PA07D_SERCOM0_PAD3 7 /**< \brief SERCOM0 signal: PAD3 on PA07 mux D */
#define MUX_PA07D_SERCOM0_PAD3 3
#define PINMUX_PA07D_SERCOM0_PAD3 ((PIN_PA07D_SERCOM0_PAD3 << 16) | MUX_PA07D_SERCOM0_PAD3)
#define PORT_PA07D_SERCOM0_PAD3 (1u << 7)
#define PIN_PA11C_SERCOM0_PAD3 11 /**< \brief SERCOM0 signal: PAD3 on PA11 mux C */
#define MUX_PA11C_SERCOM0_PAD3 2
#define PINMUX_PA11C_SERCOM0_PAD3 ((PIN_PA11C_SERCOM0_PAD3 << 16) | MUX_PA11C_SERCOM0_PAD3)
#define PORT_PA11C_SERCOM0_PAD3 (1u << 11)
/* ========== PORT definition for SERCOM1 peripheral ========== */
#define PIN_PA16C_SERCOM1_PAD0 16 /**< \brief SERCOM1 signal: PAD0 on PA16 mux C */
#define MUX_PA16C_SERCOM1_PAD0 2
#define PINMUX_PA16C_SERCOM1_PAD0 ((PIN_PA16C_SERCOM1_PAD0 << 16) | MUX_PA16C_SERCOM1_PAD0)
#define PORT_PA16C_SERCOM1_PAD0 (1u << 16)
#define PIN_PA00D_SERCOM1_PAD0 0 /**< \brief SERCOM1 signal: PAD0 on PA00 mux D */
#define MUX_PA00D_SERCOM1_PAD0 3
#define PINMUX_PA00D_SERCOM1_PAD0 ((PIN_PA00D_SERCOM1_PAD0 << 16) | MUX_PA00D_SERCOM1_PAD0)
#define PORT_PA00D_SERCOM1_PAD0 (1u << 0)
#define PIN_PA17C_SERCOM1_PAD1 17 /**< \brief SERCOM1 signal: PAD1 on PA17 mux C */
#define MUX_PA17C_SERCOM1_PAD1 2
#define PINMUX_PA17C_SERCOM1_PAD1 ((PIN_PA17C_SERCOM1_PAD1 << 16) | MUX_PA17C_SERCOM1_PAD1)
#define PORT_PA17C_SERCOM1_PAD1 (1u << 17)
#define PIN_PA01D_SERCOM1_PAD1 1 /**< \brief SERCOM1 signal: PAD1 on PA01 mux D */
#define MUX_PA01D_SERCOM1_PAD1 3
#define PINMUX_PA01D_SERCOM1_PAD1 ((PIN_PA01D_SERCOM1_PAD1 << 16) | MUX_PA01D_SERCOM1_PAD1)
#define PORT_PA01D_SERCOM1_PAD1 (1u << 1)
#define PIN_PA30D_SERCOM1_PAD2 30 /**< \brief SERCOM1 signal: PAD2 on PA30 mux D */
#define MUX_PA30D_SERCOM1_PAD2 3
#define PINMUX_PA30D_SERCOM1_PAD2 ((PIN_PA30D_SERCOM1_PAD2 << 16) | MUX_PA30D_SERCOM1_PAD2)
#define PORT_PA30D_SERCOM1_PAD2 (1u << 30)
#define PIN_PA18C_SERCOM1_PAD2 18 /**< \brief SERCOM1 signal: PAD2 on PA18 mux C */
#define MUX_PA18C_SERCOM1_PAD2 2
#define PINMUX_PA18C_SERCOM1_PAD2 ((PIN_PA18C_SERCOM1_PAD2 << 16) | MUX_PA18C_SERCOM1_PAD2)
#define PORT_PA18C_SERCOM1_PAD2 (1u << 18)
#define PIN_PA31D_SERCOM1_PAD3 31 /**< \brief SERCOM1 signal: PAD3 on PA31 mux D */
#define MUX_PA31D_SERCOM1_PAD3 3
#define PINMUX_PA31D_SERCOM1_PAD3 ((PIN_PA31D_SERCOM1_PAD3 << 16) | MUX_PA31D_SERCOM1_PAD3)
#define PORT_PA31D_SERCOM1_PAD3 (1u << 31)
#define PIN_PA19C_SERCOM1_PAD3 19 /**< \brief SERCOM1 signal: PAD3 on PA19 mux C */
#define MUX_PA19C_SERCOM1_PAD3 2
#define PINMUX_PA19C_SERCOM1_PAD3 ((PIN_PA19C_SERCOM1_PAD3 << 16) | MUX_PA19C_SERCOM1_PAD3)
#define PORT_PA19C_SERCOM1_PAD3 (1u << 19)
/* ========== PORT definition for SERCOM2 peripheral ========== */
#define PIN_PA08D_SERCOM2_PAD0 8 /**< \brief SERCOM2 signal: PAD0 on PA08 mux D */
#define MUX_PA08D_SERCOM2_PAD0 3
#define PINMUX_PA08D_SERCOM2_PAD0 ((PIN_PA08D_SERCOM2_PAD0 << 16) | MUX_PA08D_SERCOM2_PAD0)
#define PORT_PA08D_SERCOM2_PAD0 (1u << 8)
#define PIN_PA15A_SERCOM2_PAD0 15 /**< \brief SERCOM2 signal: PAD0 on PA15 mux A */
#define MUX_PA15A_SERCOM2_PAD0 0
#define PINMUX_PA15A_SERCOM2_PAD0 ((PIN_PA15A_SERCOM2_PAD0 << 16) | MUX_PA15A_SERCOM2_PAD0)
#define PORT_PA15A_SERCOM2_PAD0 (1u << 15)
#define PIN_PA09D_SERCOM2_PAD1 9 /**< \brief SERCOM2 signal: PAD1 on PA09 mux D */
#define MUX_PA09D_SERCOM2_PAD1 3
#define PINMUX_PA09D_SERCOM2_PAD1 ((PIN_PA09D_SERCOM2_PAD1 << 16) | MUX_PA09D_SERCOM2_PAD1)
#define PORT_PA09D_SERCOM2_PAD1 (1u << 9)
#define PIN_PA10D_SERCOM2_PAD2 10 /**< \brief SERCOM2 signal: PAD2 on PA10 mux D */
#define MUX_PA10D_SERCOM2_PAD2 3
#define PINMUX_PA10D_SERCOM2_PAD2 ((PIN_PA10D_SERCOM2_PAD2 << 16) | MUX_PA10D_SERCOM2_PAD2)
#define PORT_PA10D_SERCOM2_PAD2 (1u << 10)
#define PIN_PA14C_SERCOM2_PAD2 14 /**< \brief SERCOM2 signal: PAD2 on PA14 mux C */
#define MUX_PA14C_SERCOM2_PAD2 2
#define PINMUX_PA14C_SERCOM2_PAD2 ((PIN_PA14C_SERCOM2_PAD2 << 16) | MUX_PA14C_SERCOM2_PAD2)
#define PORT_PA14C_SERCOM2_PAD2 (1u << 14)
#define PIN_PA11D_SERCOM2_PAD3 11 /**< \brief SERCOM2 signal: PAD3 on PA11 mux D */
#define MUX_PA11D_SERCOM2_PAD3 3
#define PINMUX_PA11D_SERCOM2_PAD3 ((PIN_PA11D_SERCOM2_PAD3 << 16) | MUX_PA11D_SERCOM2_PAD3)
#define PORT_PA11D_SERCOM2_PAD3 (1u << 11)
#define PIN_PA15C_SERCOM2_PAD3 15 /**< \brief SERCOM2 signal: PAD3 on PA15 mux C */
#define MUX_PA15C_SERCOM2_PAD3 2
#define PINMUX_PA15C_SERCOM2_PAD3 ((PIN_PA15C_SERCOM2_PAD3 << 16) | MUX_PA15C_SERCOM2_PAD3)
#define PORT_PA15C_SERCOM2_PAD3 (1u << 15)
/* ========== PORT definition for SERCOM3 peripheral ========== */
#define PIN_PA16D_SERCOM3_PAD0 16 /**< \brief SERCOM3 signal: PAD0 on PA16 mux D */
#define MUX_PA16D_SERCOM3_PAD0 3
#define PINMUX_PA16D_SERCOM3_PAD0 ((PIN_PA16D_SERCOM3_PAD0 << 16) | MUX_PA16D_SERCOM3_PAD0)
#define PORT_PA16D_SERCOM3_PAD0 (1u << 16)
#define PIN_PA22C_SERCOM3_PAD0 22 /**< \brief SERCOM3 signal: PAD0 on PA22 mux C */
#define MUX_PA22C_SERCOM3_PAD0 2
#define PINMUX_PA22C_SERCOM3_PAD0 ((PIN_PA22C_SERCOM3_PAD0 << 16) | MUX_PA22C_SERCOM3_PAD0)
#define PORT_PA22C_SERCOM3_PAD0 (1u << 22)
#define PIN_PA27F_SERCOM3_PAD0 27 /**< \brief SERCOM3 signal: PAD0 on PA27 mux F */
#define MUX_PA27F_SERCOM3_PAD0 5
#define PINMUX_PA27F_SERCOM3_PAD0 ((PIN_PA27F_SERCOM3_PAD0 << 16) | MUX_PA27F_SERCOM3_PAD0)
#define PORT_PA27F_SERCOM3_PAD0 (1u << 27)
#define PIN_PA17D_SERCOM3_PAD1 17 /**< \brief SERCOM3 signal: PAD1 on PA17 mux D */
#define MUX_PA17D_SERCOM3_PAD1 3
#define PINMUX_PA17D_SERCOM3_PAD1 ((PIN_PA17D_SERCOM3_PAD1 << 16) | MUX_PA17D_SERCOM3_PAD1)
#define PORT_PA17D_SERCOM3_PAD1 (1u << 17)
#define PIN_PA23C_SERCOM3_PAD1 23 /**< \brief SERCOM3 signal: PAD1 on PA23 mux C */
#define MUX_PA23C_SERCOM3_PAD1 2
#define PINMUX_PA23C_SERCOM3_PAD1 ((PIN_PA23C_SERCOM3_PAD1 << 16) | MUX_PA23C_SERCOM3_PAD1)
#define PORT_PA23C_SERCOM3_PAD1 (1u << 23)
#define PIN_PA28F_SERCOM3_PAD1 28 /**< \brief SERCOM3 signal: PAD1 on PA28 mux F */
#define MUX_PA28F_SERCOM3_PAD1 5
#define PINMUX_PA28F_SERCOM3_PAD1 ((PIN_PA28F_SERCOM3_PAD1 << 16) | MUX_PA28F_SERCOM3_PAD1)
#define PORT_PA28F_SERCOM3_PAD1 (1u << 28)
#define PIN_PA18D_SERCOM3_PAD2 18 /**< \brief SERCOM3 signal: PAD2 on PA18 mux D */
#define MUX_PA18D_SERCOM3_PAD2 3
#define PINMUX_PA18D_SERCOM3_PAD2 ((PIN_PA18D_SERCOM3_PAD2 << 16) | MUX_PA18D_SERCOM3_PAD2)
#define PORT_PA18D_SERCOM3_PAD2 (1u << 18)
#define PIN_PA24C_SERCOM3_PAD2 24 /**< \brief SERCOM3 signal: PAD2 on PA24 mux C */
#define MUX_PA24C_SERCOM3_PAD2 2
#define PINMUX_PA24C_SERCOM3_PAD2 ((PIN_PA24C_SERCOM3_PAD2 << 16) | MUX_PA24C_SERCOM3_PAD2)
#define PORT_PA24C_SERCOM3_PAD2 (1u << 24)
#define PIN_PA19D_SERCOM3_PAD3 19 /**< \brief SERCOM3 signal: PAD3 on PA19 mux D */
#define MUX_PA19D_SERCOM3_PAD3 3
#define PINMUX_PA19D_SERCOM3_PAD3 ((PIN_PA19D_SERCOM3_PAD3 << 16) | MUX_PA19D_SERCOM3_PAD3)
#define PORT_PA19D_SERCOM3_PAD3 (1u << 19)
#define PIN_PA25C_SERCOM3_PAD3 25 /**< \brief SERCOM3 signal: PAD3 on PA25 mux C */
#define MUX_PA25C_SERCOM3_PAD3 2
#define PINMUX_PA25C_SERCOM3_PAD3 ((PIN_PA25C_SERCOM3_PAD3 << 16) | MUX_PA25C_SERCOM3_PAD3)
#define PORT_PA25C_SERCOM3_PAD3 (1u << 25)
/* ========== PORT definition for TCC0 peripheral ========== */
#define PIN_PA04E_TCC0_WO0 4 /**< \brief TCC0 signal: WO0 on PA04 mux E */
#define MUX_PA04E_TCC0_WO0 4
#define PINMUX_PA04E_TCC0_WO0 ((PIN_PA04E_TCC0_WO0 << 16) | MUX_PA04E_TCC0_WO0)
#define PORT_PA04E_TCC0_WO0 (1u << 4)
#define PIN_PA08E_TCC0_WO0 8 /**< \brief TCC0 signal: WO0 on PA08 mux E */
#define MUX_PA08E_TCC0_WO0 4
#define PINMUX_PA08E_TCC0_WO0 ((PIN_PA08E_TCC0_WO0 << 16) | MUX_PA08E_TCC0_WO0)
#define PORT_PA08E_TCC0_WO0 (1u << 8)
#define PIN_PA16F_TCC0_WO0 16 /**< \brief TCC0 signal: WO0 on PA16 mux F */
#define MUX_PA16F_TCC0_WO0 5
#define PINMUX_PA16F_TCC0_WO0 ((PIN_PA16F_TCC0_WO0 << 16) | MUX_PA16F_TCC0_WO0)
#define PORT_PA16F_TCC0_WO0 (1u << 16)
#define PIN_PA05E_TCC0_WO1 5 /**< \brief TCC0 signal: WO1 on PA05 mux E */
#define MUX_PA05E_TCC0_WO1 4
#define PINMUX_PA05E_TCC0_WO1 ((PIN_PA05E_TCC0_WO1 << 16) | MUX_PA05E_TCC0_WO1)
#define PORT_PA05E_TCC0_WO1 (1u << 5)
#define PIN_PA09E_TCC0_WO1 9 /**< \brief TCC0 signal: WO1 on PA09 mux E */
#define MUX_PA09E_TCC0_WO1 4
#define PINMUX_PA09E_TCC0_WO1 ((PIN_PA09E_TCC0_WO1 << 16) | MUX_PA09E_TCC0_WO1)
#define PORT_PA09E_TCC0_WO1 (1u << 9)
#define PIN_PA17F_TCC0_WO1 17 /**< \brief TCC0 signal: WO1 on PA17 mux F */
#define MUX_PA17F_TCC0_WO1 5
#define PINMUX_PA17F_TCC0_WO1 ((PIN_PA17F_TCC0_WO1 << 16) | MUX_PA17F_TCC0_WO1)
#define PORT_PA17F_TCC0_WO1 (1u << 17)
#define PIN_PA10F_TCC0_WO2 10 /**< \brief TCC0 signal: WO2 on PA10 mux F */
#define MUX_PA10F_TCC0_WO2 5
#define PINMUX_PA10F_TCC0_WO2 ((PIN_PA10F_TCC0_WO2 << 16) | MUX_PA10F_TCC0_WO2)
#define PORT_PA10F_TCC0_WO2 (1u << 10)
#define PIN_PA18F_TCC0_WO2 18 /**< \brief TCC0 signal: WO2 on PA18 mux F */
#define MUX_PA18F_TCC0_WO2 5
#define PINMUX_PA18F_TCC0_WO2 ((PIN_PA18F_TCC0_WO2 << 16) | MUX_PA18F_TCC0_WO2)
#define PORT_PA18F_TCC0_WO2 (1u << 18)
#define PIN_PA11F_TCC0_WO3 11 /**< \brief TCC0 signal: WO3 on PA11 mux F */
#define MUX_PA11F_TCC0_WO3 5
#define PINMUX_PA11F_TCC0_WO3 ((PIN_PA11F_TCC0_WO3 << 16) | MUX_PA11F_TCC0_WO3)
#define PORT_PA11F_TCC0_WO3 (1u << 11)
#define PIN_PA19F_TCC0_WO3 19 /**< \brief TCC0 signal: WO3 on PA19 mux F */
#define MUX_PA19F_TCC0_WO3 5
#define PINMUX_PA19F_TCC0_WO3 ((PIN_PA19F_TCC0_WO3 << 16) | MUX_PA19F_TCC0_WO3)
#define PORT_PA19F_TCC0_WO3 (1u << 19)
#define PIN_PA14F_TCC0_WO4 14 /**< \brief TCC0 signal: WO4 on PA14 mux F */
#define MUX_PA14F_TCC0_WO4 5
#define PINMUX_PA14F_TCC0_WO4 ((PIN_PA14F_TCC0_WO4 << 16) | MUX_PA14F_TCC0_WO4)
#define PORT_PA14F_TCC0_WO4 (1u << 14)
#define PIN_PA22F_TCC0_WO4 22 /**< \brief TCC0 signal: WO4 on PA22 mux F */
#define MUX_PA22F_TCC0_WO4 5
#define PINMUX_PA22F_TCC0_WO4 ((PIN_PA22F_TCC0_WO4 << 16) | MUX_PA22F_TCC0_WO4)
#define PORT_PA22F_TCC0_WO4 (1u << 22)
#define PIN_PA15F_TCC0_WO5 15 /**< \brief TCC0 signal: WO5 on PA15 mux F */
#define MUX_PA15F_TCC0_WO5 5
#define PINMUX_PA15F_TCC0_WO5 ((PIN_PA15F_TCC0_WO5 << 16) | MUX_PA15F_TCC0_WO5)
#define PORT_PA15F_TCC0_WO5 (1u << 15)
#define PIN_PA23F_TCC0_WO5 23 /**< \brief TCC0 signal: WO5 on PA23 mux F */
#define MUX_PA23F_TCC0_WO5 5
#define PINMUX_PA23F_TCC0_WO5 ((PIN_PA23F_TCC0_WO5 << 16) | MUX_PA23F_TCC0_WO5)
#define PORT_PA23F_TCC0_WO5 (1u << 23)
#define PIN_PA16F_TCC0_WO6 16 /**< \brief TCC0 signal: WO6 on PA16 mux F */
#define MUX_PA16F_TCC0_WO6 5
#define PINMUX_PA16F_TCC0_WO6 ((PIN_PA16F_TCC0_WO6 << 16) | MUX_PA16F_TCC0_WO6)
#define PORT_PA16F_TCC0_WO6 (1u << 16)
#define PIN_PA17F_TCC0_WO7 17 /**< \brief TCC0 signal: WO7 on PA17 mux F */
#define MUX_PA17F_TCC0_WO7 5
#define PINMUX_PA17F_TCC0_WO7 ((PIN_PA17F_TCC0_WO7 << 16) | MUX_PA17F_TCC0_WO7)
#define PORT_PA17F_TCC0_WO7 (1u << 17)
/* ========== PORT definition for TCC1 peripheral ========== */
#define PIN_PA06E_TCC1_WO0 6 /**< \brief TCC1 signal: WO0 on PA06 mux E */
#define MUX_PA06E_TCC1_WO0 4
#define PINMUX_PA06E_TCC1_WO0 ((PIN_PA06E_TCC1_WO0 << 16) | MUX_PA06E_TCC1_WO0)
#define PORT_PA06E_TCC1_WO0 (1u << 6)
#define PIN_PA10E_TCC1_WO0 10 /**< \brief TCC1 signal: WO0 on PA10 mux E */
#define MUX_PA10E_TCC1_WO0 4
#define PINMUX_PA10E_TCC1_WO0 ((PIN_PA10E_TCC1_WO0 << 16) | MUX_PA10E_TCC1_WO0)
#define PORT_PA10E_TCC1_WO0 (1u << 10)
#define PIN_PA30E_TCC1_WO0 30 /**< \brief TCC1 signal: WO0 on PA30 mux E */
#define MUX_PA30E_TCC1_WO0 4
#define PINMUX_PA30E_TCC1_WO0 ((PIN_PA30E_TCC1_WO0 << 16) | MUX_PA30E_TCC1_WO0)
#define PORT_PA30E_TCC1_WO0 (1u << 30)
#define PIN_PA07E_TCC1_WO1 7 /**< \brief TCC1 signal: WO1 on PA07 mux E */
#define MUX_PA07E_TCC1_WO1 4
#define PINMUX_PA07E_TCC1_WO1 ((PIN_PA07E_TCC1_WO1 << 16) | MUX_PA07E_TCC1_WO1)
#define PORT_PA07E_TCC1_WO1 (1u << 7)
#define PIN_PA11E_TCC1_WO1 11 /**< \brief TCC1 signal: WO1 on PA11 mux E */
#define MUX_PA11E_TCC1_WO1 4
#define PINMUX_PA11E_TCC1_WO1 ((PIN_PA11E_TCC1_WO1 << 16) | MUX_PA11E_TCC1_WO1)
#define PORT_PA11E_TCC1_WO1 (1u << 11)
#define PIN_PA31E_TCC1_WO1 31 /**< \brief TCC1 signal: WO1 on PA31 mux E */
#define MUX_PA31E_TCC1_WO1 4
#define PINMUX_PA31E_TCC1_WO1 ((PIN_PA31E_TCC1_WO1 << 16) | MUX_PA31E_TCC1_WO1)
#define PORT_PA31E_TCC1_WO1 (1u << 31)
#define PIN_PA08F_TCC1_WO2 8 /**< \brief TCC1 signal: WO2 on PA08 mux F */
#define MUX_PA08F_TCC1_WO2 5
#define PINMUX_PA08F_TCC1_WO2 ((PIN_PA08F_TCC1_WO2 << 16) | MUX_PA08F_TCC1_WO2)
#define PORT_PA08F_TCC1_WO2 (1u << 8)
#define PIN_PA24F_TCC1_WO2 24 /**< \brief TCC1 signal: WO2 on PA24 mux F */
#define MUX_PA24F_TCC1_WO2 5
#define PINMUX_PA24F_TCC1_WO2 ((PIN_PA24F_TCC1_WO2 << 16) | MUX_PA24F_TCC1_WO2)
#define PORT_PA24F_TCC1_WO2 (1u << 24)
#define PIN_PA09F_TCC1_WO3 9 /**< \brief TCC1 signal: WO3 on PA09 mux F */
#define MUX_PA09F_TCC1_WO3 5
#define PINMUX_PA09F_TCC1_WO3 ((PIN_PA09F_TCC1_WO3 << 16) | MUX_PA09F_TCC1_WO3)
#define PORT_PA09F_TCC1_WO3 (1u << 9)
#define PIN_PA25F_TCC1_WO3 25 /**< \brief TCC1 signal: WO3 on PA25 mux F */
#define MUX_PA25F_TCC1_WO3 5
#define PINMUX_PA25F_TCC1_WO3 ((PIN_PA25F_TCC1_WO3 << 16) | MUX_PA25F_TCC1_WO3)
#define PORT_PA25F_TCC1_WO3 (1u << 25)
/* ========== PORT definition for TCC2 peripheral ========== */
#define PIN_PA16E_TCC2_WO0 16 /**< \brief TCC2 signal: WO0 on PA16 mux E */
#define MUX_PA16E_TCC2_WO0 4
#define PINMUX_PA16E_TCC2_WO0 ((PIN_PA16E_TCC2_WO0 << 16) | MUX_PA16E_TCC2_WO0)
#define PORT_PA16E_TCC2_WO0 (1u << 16)
#define PIN_PA00E_TCC2_WO0 0 /**< \brief TCC2 signal: WO0 on PA00 mux E */
#define MUX_PA00E_TCC2_WO0 4
#define PINMUX_PA00E_TCC2_WO0 ((PIN_PA00E_TCC2_WO0 << 16) | MUX_PA00E_TCC2_WO0)
#define PORT_PA00E_TCC2_WO0 (1u << 0)
#define PIN_PA17E_TCC2_WO1 17 /**< \brief TCC2 signal: WO1 on PA17 mux E */
#define MUX_PA17E_TCC2_WO1 4
#define PINMUX_PA17E_TCC2_WO1 ((PIN_PA17E_TCC2_WO1 << 16) | MUX_PA17E_TCC2_WO1)
#define PORT_PA17E_TCC2_WO1 (1u << 17)
#define PIN_PA01E_TCC2_WO1 1 /**< \brief TCC2 signal: WO1 on PA01 mux E */
#define MUX_PA01E_TCC2_WO1 4
#define PINMUX_PA01E_TCC2_WO1 ((PIN_PA01E_TCC2_WO1 << 16) | MUX_PA01E_TCC2_WO1)
#define PORT_PA01E_TCC2_WO1 (1u << 1)
/* ========== PORT definition for TC3 peripheral ========== */
#define PIN_PA18E_TC3_WO0 18 /**< \brief TC3 signal: WO0 on PA18 mux E */
#define MUX_PA18E_TC3_WO0 4
#define PINMUX_PA18E_TC3_WO0 ((PIN_PA18E_TC3_WO0 << 16) | MUX_PA18E_TC3_WO0)
#define PORT_PA18E_TC3_WO0 (1u << 18)
#define PIN_PA14E_TC3_WO0 14 /**< \brief TC3 signal: WO0 on PA14 mux E */
#define MUX_PA14E_TC3_WO0 4
#define PINMUX_PA14E_TC3_WO0 ((PIN_PA14E_TC3_WO0 << 16) | MUX_PA14E_TC3_WO0)
#define PORT_PA14E_TC3_WO0 (1u << 14)
#define PIN_PA19E_TC3_WO1 19 /**< \brief TC3 signal: WO1 on PA19 mux E */
#define MUX_PA19E_TC3_WO1 4
#define PINMUX_PA19E_TC3_WO1 ((PIN_PA19E_TC3_WO1 << 16) | MUX_PA19E_TC3_WO1)
#define PORT_PA19E_TC3_WO1 (1u << 19)
#define PIN_PA15E_TC3_WO1 15 /**< \brief TC3 signal: WO1 on PA15 mux E */
#define MUX_PA15E_TC3_WO1 4
#define PINMUX_PA15E_TC3_WO1 ((PIN_PA15E_TC3_WO1 << 16) | MUX_PA15E_TC3_WO1)
#define PORT_PA15E_TC3_WO1 (1u << 15)
/* ========== PORT definition for TC4 peripheral ========== */
#define PIN_PA22E_TC4_WO0 22 /**< \brief TC4 signal: WO0 on PA22 mux E */
#define MUX_PA22E_TC4_WO0 4
#define PINMUX_PA22E_TC4_WO0 ((PIN_PA22E_TC4_WO0 << 16) | MUX_PA22E_TC4_WO0)
#define PORT_PA22E_TC4_WO0 (1u << 22)
#define PIN_PA23E_TC4_WO1 23 /**< \brief TC4 signal: WO1 on PA23 mux E */
#define MUX_PA23E_TC4_WO1 4
#define PINMUX_PA23E_TC4_WO1 ((PIN_PA23E_TC4_WO1 << 16) | MUX_PA23E_TC4_WO1)
#define PORT_PA23E_TC4_WO1 (1u << 23)
/* ========== PORT definition for TC5 peripheral ========== */
#define PIN_PA24E_TC5_WO0 24 /**< \brief TC5 signal: WO0 on PA24 mux E */
#define MUX_PA24E_TC5_WO0 4
#define PINMUX_PA24E_TC5_WO0 ((PIN_PA24E_TC5_WO0 << 16) | MUX_PA24E_TC5_WO0)
#define PORT_PA24E_TC5_WO0 (1u << 24)
#define PIN_PA25E_TC5_WO1 25 /**< \brief TC5 signal: WO1 on PA25 mux E */
#define MUX_PA25E_TC5_WO1 4
#define PINMUX_PA25E_TC5_WO1 ((PIN_PA25E_TC5_WO1 << 16) | MUX_PA25E_TC5_WO1)
#define PORT_PA25E_TC5_WO1 (1u << 25)
/* ========== PORT definition for ADC peripheral ========== */
#define PIN_PA02B_ADC_AIN0 2 /**< \brief ADC signal: AIN0 on PA02 mux B */
#define MUX_PA02B_ADC_AIN0 1
#define PINMUX_PA02B_ADC_AIN0 ((PIN_PA02B_ADC_AIN0 << 16) | MUX_PA02B_ADC_AIN0)
#define PORT_PA02B_ADC_AIN0 (1u << 2)
#define PIN_PA03B_ADC_AIN1 3 /**< \brief ADC signal: AIN1 on PA03 mux B */
#define MUX_PA03B_ADC_AIN1 1
#define PINMUX_PA03B_ADC_AIN1 ((PIN_PA03B_ADC_AIN1 << 16) | MUX_PA03B_ADC_AIN1)
#define PORT_PA03B_ADC_AIN1 (1u << 3)
#define PIN_PA04B_ADC_AIN4 4 /**< \brief ADC signal: AIN4 on PA04 mux B */
#define MUX_PA04B_ADC_AIN4 1
#define PINMUX_PA04B_ADC_AIN4 ((PIN_PA04B_ADC_AIN4 << 16) | MUX_PA04B_ADC_AIN4)
#define PORT_PA04B_ADC_AIN4 (1u << 4)
#define PIN_PA05B_ADC_AIN5 5 /**< \brief ADC signal: AIN5 on PA05 mux B */
#define MUX_PA05B_ADC_AIN5 1
#define PINMUX_PA05B_ADC_AIN5 ((PIN_PA05B_ADC_AIN5 << 16) | MUX_PA05B_ADC_AIN5)
#define PORT_PA05B_ADC_AIN5 (1u << 5)
#define PIN_PA06B_ADC_AIN6 6 /**< \brief ADC signal: AIN6 on PA06 mux B */
#define MUX_PA06B_ADC_AIN6 1
#define PINMUX_PA06B_ADC_AIN6 ((PIN_PA06B_ADC_AIN6 << 16) | MUX_PA06B_ADC_AIN6)
#define PORT_PA06B_ADC_AIN6 (1u << 6)
#define PIN_PA07B_ADC_AIN7 7 /**< \brief ADC signal: AIN7 on PA07 mux B */
#define MUX_PA07B_ADC_AIN7 1
#define PINMUX_PA07B_ADC_AIN7 ((PIN_PA07B_ADC_AIN7 << 16) | MUX_PA07B_ADC_AIN7)
#define PORT_PA07B_ADC_AIN7 (1u << 7)
#define PIN_PA08B_ADC_AIN16 8 /**< \brief ADC signal: AIN16 on PA08 mux B */
#define MUX_PA08B_ADC_AIN16 1
#define PINMUX_PA08B_ADC_AIN16 ((PIN_PA08B_ADC_AIN16 << 16) | MUX_PA08B_ADC_AIN16)
#define PORT_PA08B_ADC_AIN16 (1u << 8)
#define PIN_PA09B_ADC_AIN17 9 /**< \brief ADC signal: AIN17 on PA09 mux B */
#define MUX_PA09B_ADC_AIN17 1
#define PINMUX_PA09B_ADC_AIN17 ((PIN_PA09B_ADC_AIN17 << 16) | MUX_PA09B_ADC_AIN17)
#define PORT_PA09B_ADC_AIN17 (1u << 9)
#define PIN_PA10B_ADC_AIN18 10 /**< \brief ADC signal: AIN18 on PA10 mux B */
#define MUX_PA10B_ADC_AIN18 1
#define PINMUX_PA10B_ADC_AIN18 ((PIN_PA10B_ADC_AIN18 << 16) | MUX_PA10B_ADC_AIN18)
#define PORT_PA10B_ADC_AIN18 (1u << 10)
#define PIN_PA11B_ADC_AIN19 11 /**< \brief ADC signal: AIN19 on PA11 mux B */
#define MUX_PA11B_ADC_AIN19 1
#define PINMUX_PA11B_ADC_AIN19 ((PIN_PA11B_ADC_AIN19 << 16) | MUX_PA11B_ADC_AIN19)
#define PORT_PA11B_ADC_AIN19 (1u << 11)
#define PIN_PA04B_ADC_VREFP 4 /**< \brief ADC signal: VREFP on PA04 mux B */
#define MUX_PA04B_ADC_VREFP 1
#define PINMUX_PA04B_ADC_VREFP ((PIN_PA04B_ADC_VREFP << 16) | MUX_PA04B_ADC_VREFP)
#define PORT_PA04B_ADC_VREFP (1u << 4)
/* ========== PORT definition for AC peripheral ========== */
#define PIN_PA04B_AC_AIN0 4 /**< \brief AC signal: AIN0 on PA04 mux B */
#define MUX_PA04B_AC_AIN0 1
#define PINMUX_PA04B_AC_AIN0 ((PIN_PA04B_AC_AIN0 << 16) | MUX_PA04B_AC_AIN0)
#define PORT_PA04B_AC_AIN0 (1u << 4)
#define PIN_PA05B_AC_AIN1 5 /**< \brief AC signal: AIN1 on PA05 mux B */
#define MUX_PA05B_AC_AIN1 1
#define PINMUX_PA05B_AC_AIN1 ((PIN_PA05B_AC_AIN1 << 16) | MUX_PA05B_AC_AIN1)
#define PORT_PA05B_AC_AIN1 (1u << 5)
#define PIN_PA06B_AC_AIN2 6 /**< \brief AC signal: AIN2 on PA06 mux B */
#define MUX_PA06B_AC_AIN2 1
#define PINMUX_PA06B_AC_AIN2 ((PIN_PA06B_AC_AIN2 << 16) | MUX_PA06B_AC_AIN2)
#define PORT_PA06B_AC_AIN2 (1u << 6)
#define PIN_PA07B_AC_AIN3 7 /**< \brief AC signal: AIN3 on PA07 mux B */
#define MUX_PA07B_AC_AIN3 1
#define PINMUX_PA07B_AC_AIN3 ((PIN_PA07B_AC_AIN3 << 16) | MUX_PA07B_AC_AIN3)
#define PORT_PA07B_AC_AIN3 (1u << 7)
#define PIN_PA18H_AC_CMP0 18 /**< \brief AC signal: CMP0 on PA18 mux H */
#define MUX_PA18H_AC_CMP0 7
#define PINMUX_PA18H_AC_CMP0 ((PIN_PA18H_AC_CMP0 << 16) | MUX_PA18H_AC_CMP0)
#define PORT_PA18H_AC_CMP0 (1u << 18)
#define PIN_PA19H_AC_CMP1 19 /**< \brief AC signal: CMP1 on PA19 mux H */
#define MUX_PA19H_AC_CMP1 7
#define PINMUX_PA19H_AC_CMP1 ((PIN_PA19H_AC_CMP1 << 16) | MUX_PA19H_AC_CMP1)
#define PORT_PA19H_AC_CMP1 (1u << 19)
/* ========== PORT definition for DAC peripheral ========== */
#define PIN_PA02B_DAC_VOUT 2 /**< \brief DAC signal: VOUT on PA02 mux B */
#define MUX_PA02B_DAC_VOUT 1
#define PINMUX_PA02B_DAC_VOUT ((PIN_PA02B_DAC_VOUT << 16) | MUX_PA02B_DAC_VOUT)
#define PORT_PA02B_DAC_VOUT (1u << 2)
#define PIN_PA03B_DAC_VREFP 3 /**< \brief DAC signal: VREFP on PA03 mux B */
#define MUX_PA03B_DAC_VREFP 1
#define PINMUX_PA03B_DAC_VREFP ((PIN_PA03B_DAC_VREFP << 16) | MUX_PA03B_DAC_VREFP)
#define PORT_PA03B_DAC_VREFP (1u << 3)
/* ========== PORT definition for I2S peripheral ========== */
#define PIN_PA11G_I2S_FS0 11 /**< \brief I2S signal: FS0 on PA11 mux G */
#define MUX_PA11G_I2S_FS0 6
#define PINMUX_PA11G_I2S_FS0 ((PIN_PA11G_I2S_FS0 << 16) | MUX_PA11G_I2S_FS0)
#define PORT_PA11G_I2S_FS0 (1u << 11)
#define PIN_PA09G_I2S_MCK0 9 /**< \brief I2S signal: MCK0 on PA09 mux G */
#define MUX_PA09G_I2S_MCK0 6
#define PINMUX_PA09G_I2S_MCK0 ((PIN_PA09G_I2S_MCK0 << 16) | MUX_PA09G_I2S_MCK0)
#define PORT_PA09G_I2S_MCK0 (1u << 9)
#define PIN_PA10G_I2S_SCK0 10 /**< \brief I2S signal: SCK0 on PA10 mux G */
#define MUX_PA10G_I2S_SCK0 6
#define PINMUX_PA10G_I2S_SCK0 ((PIN_PA10G_I2S_SCK0 << 16) | MUX_PA10G_I2S_SCK0)
#define PORT_PA10G_I2S_SCK0 (1u << 10)
#define PIN_PA07G_I2S_SD0 7 /**< \brief I2S signal: SD0 on PA07 mux G */
#define MUX_PA07G_I2S_SD0 6
#define PINMUX_PA07G_I2S_SD0 ((PIN_PA07G_I2S_SD0 << 16) | MUX_PA07G_I2S_SD0)
#define PORT_PA07G_I2S_SD0 (1u << 7)
#define PIN_PA19G_I2S_SD0 19 /**< \brief I2S signal: SD0 on PA19 mux G */
#define MUX_PA19G_I2S_SD0 6
#define PINMUX_PA19G_I2S_SD0 ((PIN_PA19G_I2S_SD0 << 16) | MUX_PA19G_I2S_SD0)
#define PORT_PA19G_I2S_SD0 (1u << 19)
#define PIN_PA08G_I2S_SD1 8 /**< \brief I2S signal: SD1 on PA08 mux G */
#define MUX_PA08G_I2S_SD1 6
#define PINMUX_PA08G_I2S_SD1 ((PIN_PA08G_I2S_SD1 << 16) | MUX_PA08G_I2S_SD1)
#define PORT_PA08G_I2S_SD1 (1u << 8)
#endif /* _SAMD21E15A_PIO_ */
|
stevemarple/Arduino-org
|
hardware/arduino/samd/bootloaders/zero/Bootloader_D21/src/ASF/sam0/utils/cmsis/samd21/include/pio/samd21e15a.h
|
C
|
lgpl-2.1
| 45,495
|
/*
* Copyright (C) 2015 Red Hat, Inc.
*
* SPDX-License-Identifier: LGPL-2.0+
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include "config.h"
#include <libglnx.h>
#include <gio/gunixinputstream.h>
#include "otutil.h"
#include "ot-main.h"
#include "ot-remote-builtins.h"
/* XXX This belongs in libotutil. */
#include "ostree-chain-input-stream.h"
static gboolean opt_stdin;
static char **opt_keyrings;
/* ATTENTION:
* Please remember to update the bash-completion script (bash/ostree) and
* man page (man/ostree-remote.xml) when changing the option list.
*/
static GOptionEntry option_entries[] = {
{ "keyring", 'k', 0, G_OPTION_ARG_FILENAME_ARRAY, &opt_keyrings, "Import keys from a keyring file (repeatable)", "FILE" },
{ "stdin", 0, 0, G_OPTION_ARG_NONE, &opt_stdin, "Import keys from standard input", NULL },
{ NULL }
};
static gboolean
open_source_stream (GInputStream **out_source_stream,
GCancellable *cancellable,
GError **error)
{
g_autoptr(GInputStream) source_stream = NULL;
guint n_keyrings = 0;
gboolean ret = FALSE;
if (opt_keyrings != NULL)
n_keyrings = g_strv_length (opt_keyrings);
if (opt_stdin)
{
source_stream = g_unix_input_stream_new (STDIN_FILENO, FALSE);
}
else
{
g_autoptr(GPtrArray) streams = NULL;
guint ii;
streams = g_ptr_array_new_with_free_func (g_object_unref);
for (ii = 0; ii < n_keyrings; ii++)
{
g_autoptr(GFile) file = NULL;
GFileInputStream *input_stream = NULL;
file = g_file_new_for_path (opt_keyrings[ii]);
input_stream = g_file_read (file, cancellable, error);
if (input_stream == NULL)
goto out;
/* Takes ownership. */
g_ptr_array_add (streams, input_stream);
}
/* Chain together all the --keyring options as one long stream. */
source_stream = (GInputStream *) ostree_chain_input_stream_new (streams);
}
*out_source_stream = g_steal_pointer (&source_stream);
ret = TRUE;
out:
return ret;
}
gboolean
ot_remote_builtin_gpg_import (int argc, char **argv, OstreeCommandInvocation *invocation, GCancellable *cancellable, GError **error)
{
g_autoptr(GOptionContext) context = NULL;
g_autoptr(OstreeRepo) repo = NULL;
g_autoptr(GInputStream) source_stream = NULL;
const char *remote_name;
const char * const *key_ids;
guint imported = 0;
gboolean ret = FALSE;
context = g_option_context_new ("NAME [KEY-ID...]");
if (!ostree_option_context_parse (context, option_entries, &argc, &argv,
invocation, &repo, cancellable, error))
goto out;
if (argc < 2)
{
ot_util_usage_error (context, "NAME must be specified", error);
goto out;
}
if (opt_stdin && opt_keyrings != NULL)
{
ot_util_usage_error (context, "--keyring and --stdin are mutually exclusive", error);
goto out;
}
remote_name = argv[1];
key_ids = (argc > 2) ? (const char * const *) argv + 2 : NULL;
if (!open_source_stream (&source_stream, cancellable, error))
goto out;
if (!ostree_repo_remote_gpg_import (repo, remote_name, source_stream,
key_ids, &imported, cancellable, error))
goto out;
/* XXX If we ever add internationalization, use ngettext() here. */
g_print ("Imported %u GPG key%s to remote \"%s\"\n",
imported, (imported == 1) ? "" : "s", remote_name);
ret = TRUE;
out:
return ret;
}
|
GNOME/ostree
|
src/ostree/ot-remote-builtin-gpg-import.c
|
C
|
lgpl-2.1
| 4,225
|
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** 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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "subversionplugin.h"
#include "settingspage.h"
#include "subversioneditor.h"
#include "subversionsubmiteditor.h"
#include "subversionclient.h"
#include "subversionconstants.h"
#include "subversioncontrol.h"
#include <vcsbase/basevcseditorfactory.h>
#include <vcsbase/vcscommand.h>
#include <vcsbase/vcsbaseeditor.h>
#include <vcsbase/basevcssubmiteditorfactory.h>
#include <vcsbase/vcsbaseconstants.h>
#include <vcsbase/vcsoutputwindow.h>
#include <vcsbase/vcsbaseeditorparameterwidget.h>
#include <texteditor/textdocument.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/documentmanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/id.h>
#include <coreplugin/locator/commandlocator.h>
#include <coreplugin/messagemanager.h>
#include <utils/fileutils.h>
#include <utils/hostosinfo.h>
#include <utils/mimetypes/mimedatabase.h>
#include <utils/parameteraction.h>
#include <utils/qtcassert.h>
#include <utils/synchronousprocess.h>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QTextCodec>
#include <QtPlugin>
#include <QProcessEnvironment>
#include <QUrl>
#include <QXmlStreamReader>
#include <QAction>
#include <QFileDialog>
#include <QMenu>
#include <QMessageBox>
#include <QInputDialog>
#include <limits.h>
#ifdef WITH_TESTS
#include <QTest>
#endif
using namespace Core;
using namespace Utils;
using namespace VcsBase;
namespace Subversion {
namespace Internal {
const char CMD_ID_SUBVERSION_MENU[] = "Subversion.Menu";
const char CMD_ID_ADD[] = "Subversion.Add";
const char CMD_ID_DELETE_FILE[] = "Subversion.Delete";
const char CMD_ID_REVERT[] = "Subversion.Revert";
const char CMD_ID_DIFF_PROJECT[] = "Subversion.DiffAll";
const char CMD_ID_DIFF_CURRENT[] = "Subversion.DiffCurrent";
const char CMD_ID_COMMIT_ALL[] = "Subversion.CommitAll";
const char CMD_ID_REVERT_ALL[] = "Subversion.RevertAll";
const char CMD_ID_COMMIT_CURRENT[] = "Subversion.CommitCurrent";
const char CMD_ID_FILELOG_CURRENT[] = "Subversion.FilelogCurrent";
const char CMD_ID_ANNOTATE_CURRENT[] = "Subversion.AnnotateCurrent";
const char CMD_ID_STATUS[] = "Subversion.Status";
const char CMD_ID_PROJECTLOG[] = "Subversion.ProjectLog";
const char CMD_ID_REPOSITORYLOG[] = "Subversion.RepositoryLog";
const char CMD_ID_REPOSITORYUPDATE[] = "Subversion.RepositoryUpdate";
const char CMD_ID_REPOSITORYDIFF[] = "Subversion.RepositoryDiff";
const char CMD_ID_REPOSITORYSTATUS[] = "Subversion.RepositoryStatus";
const char CMD_ID_UPDATE[] = "Subversion.Update";
const char CMD_ID_COMMIT_PROJECT[] = "Subversion.CommitProject";
const char CMD_ID_DESCRIBE[] = "Subversion.Describe";
const VcsBaseEditorParameters editorParameters[] = {
{
LogOutput,
Constants::SUBVERSION_LOG_EDITOR_ID,
Constants::SUBVERSION_LOG_EDITOR_DISPLAY_NAME,
Constants::SUBVERSION_LOG_MIMETYPE},
{ AnnotateOutput,
Constants::SUBVERSION_BLAME_EDITOR_ID,
Constants::SUBVERSION_BLAME_EDITOR_DISPLAY_NAME,
Constants::SUBVERSION_BLAME_MIMETYPE}
};
// Utility to find a parameter set by type
static const VcsBaseEditorParameters *findType(int ie)
{
const EditorContentType et = static_cast<EditorContentType>(ie);
return VcsBaseEditor::findType(editorParameters, sizeof(editorParameters)/sizeof(editorParameters[0]), et);
}
static inline QString debugCodec(const QTextCodec *c)
{
return c ? QString::fromLatin1(c->name()) : QString::fromLatin1("Null codec");
}
// Parse "svn status" output for added/modified/deleted files
// "M<7blanks>file"
typedef QList<SubversionSubmitEditor::StatusFilePair> StatusList;
StatusList parseStatusOutput(const QString &output)
{
StatusList changeSet;
const QString newLine = QString(QLatin1Char('\n'));
const QStringList list = output.split(newLine, QString::SkipEmptyParts);
foreach (const QString &l, list) {
const QString line =l.trimmed();
if (line.size() > 8) {
const QChar state = line.at(0);
if (state == QLatin1Char('A') || state == QLatin1Char('D') || state == QLatin1Char('M')) {
const QString fileName = line.mid(7); // Column 8 starting from svn 1.6
changeSet.push_back(SubversionSubmitEditor::StatusFilePair(QString(state), fileName.trimmed()));
}
}
}
return changeSet;
}
// Return a list of names for the internal svn directories
static inline QStringList svnDirectories()
{
QStringList rc(QLatin1String(".svn"));
if (HostOsInfo::isWindowsHost())
// Option on Windows systems to avoid hassle with some IDEs
rc.push_back(QLatin1String("_svn"));
return rc;
}
// ------------- SubversionPlugin
SubversionPlugin *SubversionPlugin::m_subversionPluginInstance = 0;
SubversionPlugin::SubversionPlugin() :
m_svnDirectories(svnDirectories())
{
}
SubversionPlugin::~SubversionPlugin()
{
delete m_client;
cleanCommitMessageFile();
}
void SubversionPlugin::cleanCommitMessageFile()
{
if (!m_commitMessageFileName.isEmpty()) {
QFile::remove(m_commitMessageFileName);
m_commitMessageFileName.clear();
m_commitRepository.clear();
}
}
bool SubversionPlugin::isCommitEditorOpen() const
{
return !m_commitMessageFileName.isEmpty();
}
const VcsBaseSubmitEditorParameters submitParameters = {
Constants::SUBVERSION_SUBMIT_MIMETYPE,
Constants::SUBVERSION_COMMIT_EDITOR_ID,
Constants::SUBVERSION_COMMIT_EDITOR_DISPLAY_NAME,
VcsBaseSubmitEditorParameters::DiffFiles
};
bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *errorMessage)
{
Q_UNUSED(errorMessage)
using namespace Constants;
using namespace Core::Constants;
Context context(SUBVERSION_CONTEXT);
initializeVcs(new SubversionControl(this), context);
m_subversionPluginInstance = this;
Utils::MimeDatabase::addMimeTypes(QLatin1String(":/trolltech.subversion/Subversion.mimetypes.xml"));
m_client = new SubversionClient;
addAutoReleasedObject(new SettingsPage(versionControl()));
addAutoReleasedObject(new VcsSubmitEditorFactory(&submitParameters,
[]() { return new SubversionSubmitEditor(&submitParameters); }));
static const char *describeSlot = SLOT(describe(QString,QString));
const int editorCount = sizeof(editorParameters) / sizeof(editorParameters[0]);
const auto widgetCreator = []() { return new SubversionEditorWidget; };
for (int i = 0; i < editorCount; i++)
addAutoReleasedObject(new VcsEditorFactory(editorParameters + i, widgetCreator, this, describeSlot));
const QString prefix = QLatin1String("svn");
m_commandLocator = new CommandLocator("Subversion", prefix, prefix);
addAutoReleasedObject(m_commandLocator);
// Register actions
ActionContainer *toolsContainer = ActionManager::actionContainer(M_TOOLS);
ActionContainer *subversionMenu = ActionManager::createMenu(Id(CMD_ID_SUBVERSION_MENU));
subversionMenu->menu()->setTitle(tr("&Subversion"));
toolsContainer->addMenu(subversionMenu);
m_menuAction = subversionMenu->menu()->menuAction();
Command *command;
m_diffCurrentAction = new ParameterAction(tr("Diff Current File"), tr("Diff \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_diffCurrentAction,
CMD_ID_DIFF_CURRENT, context);
command->setAttribute(Command::CA_UpdateText);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+S,Meta+D") : tr("Alt+S,Alt+D")));
connect(m_diffCurrentAction, SIGNAL(triggered()), this, SLOT(diffCurrentFile()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_filelogCurrentAction = new ParameterAction(tr("Filelog Current File"), tr("Filelog \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_filelogCurrentAction,
CMD_ID_FILELOG_CURRENT, context);
command->setAttribute(Command::CA_UpdateText);
connect(m_filelogCurrentAction, SIGNAL(triggered()), this,
SLOT(filelogCurrentFile()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_annotateCurrentAction = new ParameterAction(tr("Annotate Current File"), tr("Annotate \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_annotateCurrentAction,
CMD_ID_ANNOTATE_CURRENT, context);
command->setAttribute(Command::CA_UpdateText);
connect(m_annotateCurrentAction, SIGNAL(triggered()), this,
SLOT(annotateCurrentFile()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
subversionMenu->addSeparator(context);
m_addAction = new ParameterAction(tr("Add"), tr("Add \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_addAction, CMD_ID_ADD,
context);
command->setAttribute(Command::CA_UpdateText);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+S,Meta+A") : tr("Alt+S,Alt+A")));
connect(m_addAction, SIGNAL(triggered()), this, SLOT(addCurrentFile()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_commitCurrentAction = new ParameterAction(tr("Commit Current File"), tr("Commit \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_commitCurrentAction,
CMD_ID_COMMIT_CURRENT, context);
command->setAttribute(Command::CA_UpdateText);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+S,Meta+C") : tr("Alt+S,Alt+C")));
connect(m_commitCurrentAction, SIGNAL(triggered()), this, SLOT(startCommitCurrentFile()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_deleteAction = new ParameterAction(tr("Delete..."), tr("Delete \"%1\"..."), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_deleteAction, CMD_ID_DELETE_FILE,
context);
command->setAttribute(Command::CA_UpdateText);
connect(m_deleteAction, &QAction::triggered, this, &SubversionPlugin::promptToDeleteCurrentFile);
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_revertAction = new ParameterAction(tr("Revert..."), tr("Revert \"%1\"..."), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_revertAction, CMD_ID_REVERT,
context);
command->setAttribute(Command::CA_UpdateText);
connect(m_revertAction, SIGNAL(triggered()), this, SLOT(revertCurrentFile()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
subversionMenu->addSeparator(context);
m_diffProjectAction = new ParameterAction(tr("Diff Project"), tr("Diff Project \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_diffProjectAction, CMD_ID_DIFF_PROJECT,
context);
command->setAttribute(Command::CA_UpdateText);
connect(m_diffProjectAction, SIGNAL(triggered()), this, SLOT(diffProject()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_statusProjectAction = new ParameterAction(tr("Project Status"), tr("Status of Project \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_statusProjectAction, CMD_ID_STATUS,
context);
command->setAttribute(Command::CA_UpdateText);
connect(m_statusProjectAction, SIGNAL(triggered()), this, SLOT(projectStatus()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_logProjectAction = new ParameterAction(tr("Log Project"), tr("Log Project \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_logProjectAction, CMD_ID_PROJECTLOG, context);
command->setAttribute(Command::CA_UpdateText);
connect(m_logProjectAction, SIGNAL(triggered()), this, SLOT(logProject()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_updateProjectAction = new ParameterAction(tr("Update Project"), tr("Update Project \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_updateProjectAction, CMD_ID_UPDATE, context);
connect(m_updateProjectAction, SIGNAL(triggered()), this, SLOT(updateProject()));
command->setAttribute(Command::CA_UpdateText);
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_commitProjectAction = new ParameterAction(tr("Commit Project"), tr("Commit Project \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_commitProjectAction, CMD_ID_COMMIT_PROJECT, context);
connect(m_commitProjectAction, SIGNAL(triggered()), this, SLOT(startCommitProject()));
command->setAttribute(Command::CA_UpdateText);
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
subversionMenu->addSeparator(context);
m_diffRepositoryAction = new QAction(tr("Diff Repository"), this);
command = ActionManager::registerAction(m_diffRepositoryAction, CMD_ID_REPOSITORYDIFF, context);
connect(m_diffRepositoryAction, SIGNAL(triggered()), this, SLOT(diffRepository()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_statusRepositoryAction = new QAction(tr("Repository Status"), this);
command = ActionManager::registerAction(m_statusRepositoryAction, CMD_ID_REPOSITORYSTATUS, context);
connect(m_statusRepositoryAction, SIGNAL(triggered()), this, SLOT(statusRepository()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_logRepositoryAction = new QAction(tr("Log Repository"), this);
command = ActionManager::registerAction(m_logRepositoryAction, CMD_ID_REPOSITORYLOG, context);
connect(m_logRepositoryAction, SIGNAL(triggered()), this, SLOT(logRepository()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_updateRepositoryAction = new QAction(tr("Update Repository"), this);
command = ActionManager::registerAction(m_updateRepositoryAction, CMD_ID_REPOSITORYUPDATE, context);
connect(m_updateRepositoryAction, SIGNAL(triggered()), this, SLOT(updateRepository()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_commitAllAction = new QAction(tr("Commit All Files"), this);
command = ActionManager::registerAction(m_commitAllAction, CMD_ID_COMMIT_ALL,
context);
connect(m_commitAllAction, SIGNAL(triggered()), this, SLOT(startCommitAll()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_describeAction = new QAction(tr("Describe..."), this);
command = ActionManager::registerAction(m_describeAction, CMD_ID_DESCRIBE, context);
connect(m_describeAction, SIGNAL(triggered()), this, SLOT(slotDescribe()));
subversionMenu->addAction(command);
m_revertRepositoryAction = new QAction(tr("Revert Repository..."), this);
command = ActionManager::registerAction(m_revertRepositoryAction, CMD_ID_REVERT_ALL,
context);
connect(m_revertRepositoryAction, SIGNAL(triggered()), this, SLOT(revertAll()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
// Actions of the submit editor
Context svncommitcontext(Constants::SUBVERSION_COMMIT_EDITOR_ID);
m_submitCurrentLogAction = new QAction(VcsBaseSubmitEditor::submitIcon(), tr("Commit"), this);
command = ActionManager::registerAction(m_submitCurrentLogAction, SUBMIT_CURRENT, svncommitcontext);
command->setAttribute(Command::CA_UpdateText);
connect(m_submitCurrentLogAction, SIGNAL(triggered()), this, SLOT(submitCurrentLog()));
m_submitDiffAction = new QAction(VcsBaseSubmitEditor::diffIcon(), tr("Diff &Selected Files"), this);
ActionManager::registerAction(m_submitDiffAction , DIFF_SELECTED, svncommitcontext);
m_submitUndoAction = new QAction(tr("&Undo"), this);
ActionManager::registerAction(m_submitUndoAction, Core::Constants::UNDO, svncommitcontext);
m_submitRedoAction = new QAction(tr("&Redo"), this);
ActionManager::registerAction(m_submitRedoAction, Core::Constants::REDO, svncommitcontext);
return true;
}
SubversionClient *SubversionPlugin::client() const
{
QTC_CHECK(m_client);
return m_client;
}
bool SubversionPlugin::submitEditorAboutToClose()
{
if (!isCommitEditorOpen())
return true;
SubversionSubmitEditor *editor = qobject_cast<SubversionSubmitEditor *>(submitEditor());
QTC_ASSERT(editor, return true);
IDocument *editorDocument = editor->document();
QTC_ASSERT(editorDocument, return true);
// Submit editor closing. Make it write out the commit message
// and retrieve files
const QFileInfo editorFile = editorDocument->filePath().toFileInfo();
const QFileInfo changeFile(m_commitMessageFileName);
if (editorFile.absoluteFilePath() != changeFile.absoluteFilePath())
return true; // Oops?!
// Prompt user. Force a prompt unless submit was actually invoked (that
// is, the editor was closed or shutdown).
VcsBaseClientSettings &newSettings = client()->settings();
const VcsBaseSubmitEditor::PromptSubmitResult answer =
editor->promptSubmit(tr("Closing Subversion Editor"),
tr("Do you want to commit the change?"),
tr("The commit message check failed. Do you want to commit the change?"),
newSettings.boolPointer(SubversionSettings::promptOnSubmitKey),
!m_submitActionTriggered);
m_submitActionTriggered = false;
switch (answer) {
case VcsBaseSubmitEditor::SubmitCanceled:
return false; // Keep editing and change file
case VcsBaseSubmitEditor::SubmitDiscarded:
cleanCommitMessageFile();
return true; // Cancel all
default:
break;
}
const QStringList fileList = editor->checkedFiles();
bool closeEditor = true;
if (!fileList.empty()) {
// get message & commit
closeEditor = DocumentManager::saveDocument(editorDocument);
if (closeEditor) {
VcsCommand *commitCmd = m_client->createCommitCmd(m_commitRepository,
fileList,
m_commitMessageFileName);
QObject::connect(commitCmd, &VcsCommand::finished,
this, [this]() { cleanCommitMessageFile(); });
commitCmd->execute();
}
}
return closeEditor;
}
void SubversionPlugin::diffCommitFiles(const QStringList &files)
{
m_client->diff(m_commitRepository, files, QStringList());
}
SubversionSubmitEditor *SubversionPlugin::openSubversionSubmitEditor(const QString &fileName)
{
IEditor *editor = EditorManager::openEditor(fileName, Constants::SUBVERSION_COMMIT_EDITOR_ID);
SubversionSubmitEditor *submitEditor = qobject_cast<SubversionSubmitEditor*>(editor);
QTC_ASSERT(submitEditor, return 0);
setSubmitEditor(submitEditor);
submitEditor->registerActions(m_submitUndoAction, m_submitRedoAction, m_submitCurrentLogAction, m_submitDiffAction);
connect(submitEditor, &VcsBaseSubmitEditor::diffSelectedFiles,
this, &SubversionPlugin::diffCommitFiles);
submitEditor->setCheckScriptWorkingDirectory(m_commitRepository);
return submitEditor;
}
void SubversionPlugin::updateActions(VcsBasePlugin::ActionState as)
{
if (!enableMenuAction(as, m_menuAction)) {
m_commandLocator->setEnabled(false);
return;
}
const bool hasTopLevel = currentState().hasTopLevel();
m_commandLocator->setEnabled(hasTopLevel);
m_logRepositoryAction->setEnabled(hasTopLevel);
const QString projectName = currentState().currentProjectName();
m_diffProjectAction->setParameter(projectName);
m_statusProjectAction->setParameter(projectName);
m_updateProjectAction->setParameter(projectName);
m_logProjectAction->setParameter(projectName);
m_commitProjectAction->setParameter(projectName);
const bool repoEnabled = currentState().hasTopLevel();
m_commitAllAction->setEnabled(repoEnabled);
m_describeAction->setEnabled(repoEnabled);
m_revertRepositoryAction->setEnabled(repoEnabled);
m_diffRepositoryAction->setEnabled(repoEnabled);
m_statusRepositoryAction->setEnabled(repoEnabled);
m_updateRepositoryAction->setEnabled(repoEnabled);
const QString fileName = currentState().currentFileName();
m_addAction->setParameter(fileName);
m_deleteAction->setParameter(fileName);
m_revertAction->setParameter(fileName);
m_diffCurrentAction->setParameter(fileName);
m_commitCurrentAction->setParameter(fileName);
m_filelogCurrentAction->setParameter(fileName);
m_annotateCurrentAction->setParameter(fileName);
}
void SubversionPlugin::addCurrentFile()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasFile(), return);
vcsAdd(state.currentFileTopLevel(), state.relativeCurrentFile());
}
void SubversionPlugin::revertAll()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
const QString title = tr("Revert repository");
if (QMessageBox::warning(ICore::dialogParent(), title,
tr("Revert all pending changes to the repository?"),
QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
return;
// NoteL: Svn "revert ." doesn not work.
QStringList args;
args << QLatin1String("revert");
args << SubversionClient::addAuthenticationOptions(client()->settings());
args << QLatin1String("--recursive") << state.topLevel();
const SubversionResponse revertResponse
= runSvn(state.topLevel(), args, m_client->vcsTimeoutS(),
VcsCommand::SshPasswordPrompt | VcsCommand::ShowStdOut);
if (revertResponse.error)
QMessageBox::warning(ICore::dialogParent(), title,
tr("Revert failed: %1").arg(revertResponse.message), QMessageBox::Ok);
else
subVersionControl()->emitRepositoryChanged(state.topLevel());
}
void SubversionPlugin::revertCurrentFile()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasFile(), return);
QStringList args(QLatin1String("diff"));
args << SubversionClient::addAuthenticationOptions(client()->settings());
args.push_back(state.relativeCurrentFile());
const SubversionResponse diffResponse
= runSvn(state.currentFileTopLevel(), args, m_client->vcsTimeoutS(), 0);
if (diffResponse.error)
return;
if (diffResponse.stdOut.isEmpty())
return;
if (QMessageBox::warning(ICore::dialogParent(), QLatin1String("svn revert"),
tr("The file has been changed. Do you want to revert it?"),
QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
return;
FileChangeBlocker fcb(state.currentFile());
// revert
args.clear();
args << QLatin1String("revert");
args << SubversionClient::addAuthenticationOptions(client()->settings());
args << state.relativeCurrentFile();
const SubversionResponse revertResponse
= runSvn(state.currentFileTopLevel(), args, m_client->vcsTimeoutS(),
VcsCommand::SshPasswordPrompt | VcsCommand::ShowStdOut);
if (!revertResponse.error)
subVersionControl()->emitFilesChanged(QStringList(state.currentFile()));
}
void SubversionPlugin::diffProject()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasProject(), return);
const QString relativeProject = state.relativeCurrentProject();
m_client->diff(state.currentProjectTopLevel(),
relativeProject.isEmpty() ? QStringList() : QStringList(relativeProject),
QStringList());
}
void SubversionPlugin::diffCurrentFile()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasFile(), return);
m_client->diff(state.currentFileTopLevel(), QStringList(state.relativeCurrentFile()),
QStringList());
}
void SubversionPlugin::startCommitCurrentFile()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasFile(), return);
startCommit(state.currentFileTopLevel(), QStringList(state.relativeCurrentFile()));
}
void SubversionPlugin::startCommitAll()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
startCommit(state.topLevel());
}
void SubversionPlugin::startCommitProject()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasProject(), return);
startCommit(state.currentProjectPath());
}
/* Start commit of files of a single repository by displaying
* template and files in a submit editor. On closing, the real
* commit will start. */
void SubversionPlugin::startCommit(const QString &workingDir, const QStringList &files)
{
if (raiseSubmitEditor())
return;
if (isCommitEditorOpen()) {
VcsOutputWindow::appendWarning(tr("Another commit is currently being executed."));
return;
}
QStringList args(QLatin1String("status"));
args << SubversionClient::addAuthenticationOptions(client()->settings());
args += files;
const SubversionResponse response
= runSvn(workingDir, args, m_client->vcsTimeoutS(), 0);
if (response.error)
return;
// Get list of added/modified/deleted files
const StatusList statusOutput = parseStatusOutput(response.stdOut);
if (statusOutput.empty()) {
VcsOutputWindow::appendWarning(tr("There are no modified files."));
return;
}
m_commitRepository = workingDir;
// Create a new submit change file containing the submit template
TempFileSaver saver;
saver.setAutoRemove(false);
// TODO: Retrieve submit template from
const QString submitTemplate;
// Create a submit
saver.write(submitTemplate.toUtf8());
if (!saver.finalize()) {
VcsOutputWindow::appendError(saver.errorString());
return;
}
m_commitMessageFileName = saver.fileName();
// Create a submit editor and set file list
SubversionSubmitEditor *editor = openSubversionSubmitEditor(m_commitMessageFileName);
QTC_ASSERT(editor, return);
editor->setStatusList(statusOutput);
}
void SubversionPlugin::filelogCurrentFile()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasFile(), return);
filelog(state.currentFileTopLevel(), state.relativeCurrentFile(), true);
}
void SubversionPlugin::logProject()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasProject(), return);
filelog(state.currentProjectTopLevel(), state.relativeCurrentProject());
}
void SubversionPlugin::logRepository()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
filelog(state.topLevel());
}
void SubversionPlugin::diffRepository()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
m_client->diff(state.topLevel(), QStringList(), QStringList());
}
void SubversionPlugin::statusRepository()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
svnStatus(state.topLevel());
}
void SubversionPlugin::updateRepository()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
svnUpdate(state.topLevel());
}
void SubversionPlugin::svnStatus(const QString &workingDir, const QString &relativePath)
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
QStringList args(QLatin1String("status"));
args << SubversionClient::addAuthenticationOptions(client()->settings());
if (!relativePath.isEmpty())
args.append(relativePath);
VcsOutputWindow::setRepository(workingDir);
runSvn(workingDir, args, m_client->vcsTimeoutS(),
VcsCommand::ShowStdOut | VcsCommand::ShowSuccessMessage);
VcsOutputWindow::clearRepository();
}
void SubversionPlugin::filelog(const QString &workingDir,
const QString &file,
bool enableAnnotationContextMenu)
{
m_client->log(workingDir, QStringList(file), QStringList(), enableAnnotationContextMenu);
}
void SubversionPlugin::updateProject()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasProject(), return);
svnUpdate(state.currentProjectTopLevel(), state.relativeCurrentProject());
}
void SubversionPlugin::svnUpdate(const QString &workingDir, const QString &relativePath)
{
QStringList args(QLatin1String("update"));
args << SubversionClient::addAuthenticationOptions(client()->settings());
args.push_back(QLatin1String(Constants::NON_INTERACTIVE_OPTION));
if (!relativePath.isEmpty())
args.append(relativePath);
const SubversionResponse response
= runSvn(workingDir, args, 10 * m_client->vcsTimeoutS(),
VcsCommand::SshPasswordPrompt | VcsCommand::ShowStdOut);
if (!response.error)
subVersionControl()->emitRepositoryChanged(workingDir);
}
void SubversionPlugin::annotateCurrentFile()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasFile(), return);
vcsAnnotate(state.currentFileTopLevel(), state.relativeCurrentFile());
}
void SubversionPlugin::annotateVersion(const QString &workingDirectory,
const QString &file,
const QString &revision,
int lineNr)
{
vcsAnnotate(workingDirectory, file, revision, lineNr);
}
void SubversionPlugin::vcsAnnotate(const QString &workingDir, const QString &file,
const QString &revision /* = QString() */,
int lineNumber /* = -1 */)
{
const QString source = VcsBaseEditor::getSource(workingDir, file);
QTextCodec *codec = VcsBaseEditor::getCodec(source);
QStringList args(QLatin1String("annotate"));
const VcsBaseClientSettings &s = client()->settings();
args << SubversionClient::addAuthenticationOptions(s);
if (s.boolValue(SubversionSettings::spaceIgnorantAnnotationKey))
args << QLatin1String("-x") << QLatin1String("-uw");
if (!revision.isEmpty())
args << QLatin1String("-r") << revision;
args.push_back(QLatin1String("-v"));
args.append(QDir::toNativeSeparators(file));
const SubversionResponse response
= runSvn(workingDir, args, m_client->vcsTimeoutS(),
VcsCommand::SshPasswordPrompt | VcsCommand::ForceCLocale, codec);
if (response.error)
return;
// Re-use an existing view if possible to support
// the common usage pattern of continuously changing and diffing a file
if (lineNumber <= 0)
lineNumber = VcsBaseEditor::lineNumberOfCurrentEditor(source);
// Determine id
const QStringList files = QStringList(file);
const QString id = VcsBaseEditor::getTitleId(workingDir, files, revision);
const QString tag = VcsBaseEditor::editorTag(AnnotateOutput, workingDir, files);
if (IEditor *editor = VcsBaseEditor::locateEditorByTag(tag)) {
editor->document()->setContents(response.stdOut.toUtf8());
VcsBaseEditor::gotoLineOfEditor(editor, lineNumber);
EditorManager::activateEditor(editor);
} else {
const QString title = QString::fromLatin1("svn annotate %1").arg(id);
IEditor *newEditor = showOutputInEditor(title, response.stdOut, AnnotateOutput, source, codec);
VcsBaseEditor::tagEditor(newEditor, tag);
VcsBaseEditor::gotoLineOfEditor(newEditor, lineNumber);
}
}
void SubversionPlugin::projectStatus()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasProject(), return);
svnStatus(state.currentProjectTopLevel(), state.relativeCurrentProject());
}
void SubversionPlugin::describe(const QString &source, const QString &changeNr)
{
// To describe a complete change, find the top level and then do
//svn diff -r 472958:472959 <top level>
const QFileInfo fi(source);
QString topLevel;
const bool manages = managesDirectory(fi.isDir() ? source : fi.absolutePath(), &topLevel);
if (!manages || topLevel.isEmpty())
return;
if (Subversion::Constants::debug)
qDebug() << Q_FUNC_INFO << source << topLevel << changeNr;
// Number must be >= 1
bool ok;
const int number = changeNr.toInt(&ok);
if (!ok || number < 1)
return;
const QString title = QString::fromLatin1("svn describe %1#%2").arg(fi.fileName(), changeNr);
m_client->describe(topLevel, number, title);
}
void SubversionPlugin::slotDescribe()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
QInputDialog inputDialog(ICore::dialogParent());
inputDialog.setWindowFlags(inputDialog.windowFlags() & ~Qt::WindowContextHelpButtonHint);
inputDialog.setInputMode(QInputDialog::IntInput);
inputDialog.setIntRange(1, INT_MAX);
inputDialog.setWindowTitle(tr("Describe"));
inputDialog.setLabelText(tr("Revision number:"));
if (inputDialog.exec() != QDialog::Accepted)
return;
const int revision = inputDialog.intValue();
describe(state.topLevel(), QString::number(revision));
}
void SubversionPlugin::submitCurrentLog()
{
m_submitActionTriggered = true;
QTC_ASSERT(submitEditor(), return);
EditorManager::closeDocument(submitEditor()->document());
}
SubversionResponse SubversionPlugin::runSvn(const QString &workingDir,
const QStringList &arguments,
int timeOutS, unsigned flags,
QTextCodec *outputCodec) const
{
const FileName executable = client()->vcsBinary();
SubversionResponse response;
if (executable.isEmpty()) {
response.error = true;
response.message =tr("No subversion executable specified.");
return response;
}
const SynchronousProcessResponse sp_resp =
VcsBasePlugin::runVcs(workingDir, executable, arguments, timeOutS,
flags, outputCodec);
response.error = sp_resp.result != SynchronousProcessResponse::Finished;
if (response.error)
response.message = sp_resp.exitMessage(executable.toString(), timeOutS);
response.stdErr = sp_resp.stdErr;
response.stdOut = sp_resp.stdOut;
return response;
}
IEditor *SubversionPlugin::showOutputInEditor(const QString &title, const QString &output,
int editorType, const QString &source,
QTextCodec *codec)
{
const VcsBaseEditorParameters *params = findType(editorType);
QTC_ASSERT(params, return 0);
const Id id = params->id;
if (Subversion::Constants::debug)
qDebug() << "SubversionPlugin::showOutputInEditor" << title << id.name()
<< "Size= " << output.size() << " Type=" << editorType << debugCodec(codec);
QString s = title;
IEditor *editor = EditorManager::openEditorWithContents(id, &s, output.toUtf8());
connect(editor, SIGNAL(annotateRevisionRequested(QString,QString,QString,int)),
this, SLOT(annotateVersion(QString,QString,QString,int)));
SubversionEditorWidget *e = qobject_cast<SubversionEditorWidget*>(editor->widget());
if (!e)
return 0;
e->setForceReadOnly(true);
s.replace(QLatin1Char(' '), QLatin1Char('_'));
e->textDocument()->setSuggestedFileName(s);
if (!source.isEmpty())
e->setSource(source);
if (codec)
e->setCodec(codec);
return editor;
}
SubversionPlugin *SubversionPlugin::instance()
{
QTC_ASSERT(m_subversionPluginInstance, return m_subversionPluginInstance);
return m_subversionPluginInstance;
}
QString SubversionPlugin::monitorFile(const QString &repository) const
{
QTC_ASSERT(!repository.isEmpty(), return QString());
QDir repoDir(repository);
foreach (const QString &svnDir, m_svnDirectories) {
if (repoDir.exists(svnDir)) {
QFileInfo fi(repoDir.absoluteFilePath(svnDir + QLatin1String("/wc.db")));
if (fi.exists() && fi.isFile())
return fi.absoluteFilePath();
}
}
return QString();
}
QString SubversionPlugin::synchronousTopic(const QString &repository) const
{
return m_client->synchronousTopic(repository);
}
bool SubversionPlugin::vcsAdd(const QString &workingDir, const QString &rawFileName)
{
const QString file = QDir::toNativeSeparators(rawFileName);
QStringList args;
args << QLatin1String("add")
<< SubversionClient::addAuthenticationOptions(client()->settings())
<< QLatin1String("--parents") << file;
const SubversionResponse response
= runSvn(workingDir, args, m_client->vcsTimeoutS(),
VcsCommand::SshPasswordPrompt | VcsCommand::ShowStdOut);
return !response.error;
}
bool SubversionPlugin::vcsDelete(const QString &workingDir, const QString &rawFileName)
{
const QString file = QDir::toNativeSeparators(rawFileName);
QStringList args;
args << QLatin1String("delete");
args << SubversionClient::addAuthenticationOptions(client()->settings())
<< QLatin1String("--force") << file;
const SubversionResponse response
= runSvn(workingDir, args, m_client->vcsTimeoutS(),
VcsCommand::SshPasswordPrompt | VcsCommand::ShowStdOut);
return !response.error;
}
bool SubversionPlugin::vcsMove(const QString &workingDir, const QString &from, const QString &to)
{
QStringList args(QLatin1String("move"));
args << SubversionClient::addAuthenticationOptions(client()->settings());
args << QDir::toNativeSeparators(from) << QDir::toNativeSeparators(to);
const SubversionResponse response
= runSvn(workingDir, args, m_client->vcsTimeoutS(),
VcsCommand::SshPasswordPrompt | VcsCommand::ShowStdOut
| VcsCommand::FullySynchronously);
return !response.error;
}
bool SubversionPlugin::vcsCheckout(const QString &directory, const QByteArray &url)
{
QUrl tempUrl = QUrl::fromEncoded(url);
QString username = tempUrl.userName();
QString password = tempUrl.password();
QStringList args = QStringList(QLatin1String("checkout"));
args << QLatin1String(Constants::NON_INTERACTIVE_OPTION) ;
if (!username.isEmpty()) {
// If url contains username and password we have to use separate username and password
// arguments instead of passing those in the url. Otherwise the subversion 'non-interactive'
// authentication will always fail (if the username and password data are not stored locally),
// if for example we are logging into a new host for the first time using svn. There seems to
// be a bug in subversion, so this might get fixed in the future.
tempUrl.setUserInfo(QString());
args << QLatin1String("--username") << username;
if (!password.isEmpty())
args << QLatin1String("--password") << password;
}
args << QLatin1String(tempUrl.toEncoded()) << directory;
const SubversionResponse response
= runSvn(directory, args, 10 * m_client->vcsTimeoutS(), VcsCommand::SshPasswordPrompt);
return !response.error;
}
bool SubversionPlugin::managesDirectory(const QString &directory, QString *topLevel /* = 0 */) const
{
const QDir dir(directory);
if (topLevel)
topLevel->clear();
/* Subversion >= 1.7 has ".svn" directory in the root of the working copy. Check for
* furthest parent containing ".svn/wc.db". Need to check for furthest parent as closer
* parents may be svn:externals. */
QDir parentDir = dir;
while (!parentDir.isRoot()) {
if (checkSVNSubDir(parentDir)) {
if (topLevel)
*topLevel = parentDir.absolutePath();
return true;
}
if (!parentDir.cdUp())
break;
}
return false;
}
bool SubversionPlugin::managesFile(const QString &workingDirectory, const QString &fileName) const
{
QStringList args;
args << QLatin1String("status");
args << SubversionClient::addAuthenticationOptions(client()->settings()) << fileName;
SubversionResponse response
= runSvn(workingDirectory, args, m_client->vcsTimeoutS(), 0);
return response.stdOut.isEmpty() || response.stdOut.at(0) != QLatin1Char('?');
}
// Check whether SVN management subdirs exist.
bool SubversionPlugin::checkSVNSubDir(const QDir &directory) const
{
const int dirCount = m_svnDirectories.size();
for (int i = 0; i < dirCount; i++) {
const QDir svnDir(directory.absoluteFilePath(m_svnDirectories.at(i)));
if (!svnDir.exists())
continue;
if (!svnDir.exists(QLatin1String("wc.db")))
continue;
return true;
}
return false;
}
SubversionControl *SubversionPlugin::subVersionControl() const
{
return static_cast<SubversionControl *>(versionControl());
}
#ifdef WITH_TESTS
void SubversionPlugin::testLogResolving()
{
QByteArray data(
"------------------------------------------------------------------------\n"
"r1439551 | philip | 2013-01-28 20:19:55 +0200 (Mon, 28 Jan 2013) | 4 lines\n"
"\n"
"* subversion/tests/cmdline/update_tests.py\n"
" (update_moved_dir_file_move): Resolve conflict, adjust expectations,\n"
" remove XFail.\n"
"\n"
"------------------------------------------------------------------------\n"
"r1439540 | philip | 2013-01-28 20:06:36 +0200 (Mon, 28 Jan 2013) | 4 lines\n"
"\n"
"* subversion/tests/cmdline/update_tests.py\n"
" (update_moved_dir_edited_leaf_del): Do non-recursive resolution, adjust\n"
" expectations, remove XFail.\n"
"\n"
);
VcsBaseEditorWidget::testLogResolving(editorParameters[0].id, data, "r1439551", "r1439540");
}
#endif
} // Internal
} // Subversion
|
xianian/qt-creator
|
src/plugins/subversion/subversionplugin.cpp
|
C++
|
lgpl-2.1
| 44,793
|
namespace Chat.MicroServices.Authentication.Entities
{
using System;
using System.Data.Linq.Mapping;
using System.Runtime.Serialization;
using Cqrs.Entities;
/// <summary>
/// A User
/// </summary>
[Serializable]
[DataContract]
[Table(Name = "Users")]
public class UserEntity : Entity
{
[DataMember]
[Column(IsPrimaryKey = true)]
public override Guid Rsn { get; set; }
[DataMember]
[Column]
public override int SortingOrder { get; set; }
[DataMember]
[Column]
public override bool IsLogicallyDeleted { get; set; }
[DataMember]
[Column]
public string FirstName { get; set; }
[DataMember]
[Column]
public string LastName { get; set; }
}
}
|
cdmdotnet/CQRS
|
Chat/Chat.MicroServices/Authentication/Entities/UserEntity.cs
|
C#
|
lgpl-2.1
| 687
|
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the documentation 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 Digia Plc 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 <QtGui>
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
setWindowTitle("Dock Widgets");
setupDockWindow();
setupContents();
setupMenus();
textBrowser = new QTextBrowser(this);
connect(headingList, SIGNAL(itemClicked(QListWidgetItem *)),
this, SLOT(updateText(QListWidgetItem *)));
updateText(headingList->item(0));
headingList->setCurrentRow(0);
setCentralWidget(textBrowser);
}
void MainWindow::setupContents()
{
QFile titlesFile(":/Resources/titles.txt");
titlesFile.open(QFile::ReadOnly);
int chapter = 0;
do {
QString line = titlesFile.readLine().trimmed();
QStringList parts = line.split("\t", QString::SkipEmptyParts);
if (parts.size() != 2)
break;
QString chapterTitle = parts[0];
QString fileName = parts[1];
QFile chapterFile(fileName);
chapterFile.open(QFile::ReadOnly);
QListWidgetItem *item = new QListWidgetItem(chapterTitle, headingList);
item->setData(Qt::DisplayRole, chapterTitle);
item->setData(Qt::UserRole, chapterFile.readAll());
item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
chapterFile.close();
chapter++;
} while (titlesFile.isOpen());
titlesFile.close();
}
void MainWindow::setupDockWindow()
{
//! [0]
contentsWindow = new QDockWidget(tr("Table of Contents"), this);
contentsWindow->setAllowedAreas(Qt::LeftDockWidgetArea
| Qt::RightDockWidgetArea);
addDockWidget(Qt::LeftDockWidgetArea, contentsWindow);
headingList = new QListWidget(contentsWindow);
contentsWindow->setWidget(headingList);
//! [0]
}
void MainWindow::setupMenus()
{
QAction *exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcut(tr("Ctrl+Q"));
exitAct->setStatusTip(tr("Exit the application"));
connect(exitAct, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(exitAct);
}
void MainWindow::updateText(QListWidgetItem *item)
{
QString text = item->data(Qt::UserRole).toString();
textBrowser->setHtml(text);
}
|
eric100lin/Qt-4.8.6
|
doc/src/snippets/dockwidgets/mainwindow.cpp
|
C++
|
lgpl-2.1
| 4,242
|
/****************************************************************************
**
** 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 QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsymbianevent.h"
QT_BEGIN_NAMESPACE
/*!
\class QSymbianEvent
\brief The QSymbianEvent class contains a Symbian event of any type.
\since 4.6
The class is used as a generic container type for all types of Symbian
events.
\note This class is only available on Symbian.
\sa QApplication::symbianEventFilter()
*/
/*!
\enum QSymbianEvent::Type
\value InvalidEvent The event is not valid.
\value WindowServerEvent Indicates an event of type \c TWsEvent.
\value CommandEvent Indicates that the event is a Symbian command.
\value ResourceChangeEvent Indicates that the event is a Symbian resource change type.
*/
/*!
\fn QSymbianEvent::type() const
Returns the event type contained in the QSymbianEvent instance.
*/
/*!
\fn QSymbianEvent::isValid() const
Returns whether this QSymbianEvent instance contains a valid event.
*/
/*!
Constructs a QSymbianEvent containing the given window server event
\a windowServerEvent.
*/
QSymbianEvent::QSymbianEvent(const TWsEvent *windowServerEvent)
: m_type(WindowServerEvent)
, m_eventPtr(windowServerEvent)
{
}
/*!
Constructs a QSymbianEvent containing the given event value
\a value. The type of event is controlled by the \a eventType parameter.
*/
QSymbianEvent::QSymbianEvent(QSymbianEvent::Type eventType, int value)
{
switch (eventType) {
case CommandEvent:
case ResourceChangeEvent:
m_type = eventType;
m_eventValue = value;
break;
default:
m_type = InvalidEvent;
m_eventValue = 0;
break;
}
}
/*!
Destroys the QSymbianEvent.
*/
QSymbianEvent::~QSymbianEvent()
{
}
/*!
Returns the window server event contained in the class instance, or 0 if the event type
is not \c WindowServerEvent.
*/
const TWsEvent *QSymbianEvent::windowServerEvent() const
{
return (m_type == WindowServerEvent) ? static_cast<const TWsEvent *>(m_eventPtr) : 0;
}
/*!
Returns the command contained in the class instance, or 0 if the event type
is not \c CommandEvent.
*/
int QSymbianEvent::command() const
{
return (m_type == CommandEvent) ? m_eventValue : 0;
}
/*!
Returns the resource change type contained in the class instance, or 0 if the event type
is not \c ResourceChangeEvent.
*/
int QSymbianEvent::resourceChangeType() const
{
return (m_type == ResourceChangeEvent) ? m_eventValue : 0;
}
QT_END_NAMESPACE
|
sunblithe/qt-everywhere-opensource-src-4.7.1
|
src/gui/symbian/qsymbianevent.cpp
|
C++
|
lgpl-2.1
| 4,408
|
#ifndef __GSK_XML_VALUE_READER_H_
#define __GSK_XML_VALUE_READER_H_
/*
*
* GskXmlValueReader -- streaming GValue instantiation from XML.
*
*/
#include <glib-object.h>
#include "gskgtypeloader.h"
G_BEGIN_DECLS
typedef struct _GskXmlValueReader GskXmlValueReader;
/* Callback to asynchronously return a GValue. */
typedef void (*GskXmlValueFunc) (const GValue *value, gpointer user_data);
GskXmlValueReader *
gsk_xml_value_reader_new (GskGtypeLoader *type_loader,
GType output_type,
GskXmlValueFunc value_func,
gpointer value_func_data,
GDestroyNotify value_func_destroy);
void gsk_xml_value_reader_free (GskXmlValueReader *reader);
gboolean gsk_xml_value_reader_input (GskXmlValueReader *reader,
const char *input,
guint len,
GError **error);
void gsk_xml_value_reader_set_pos (GskXmlValueReader *reader,
const char *filename,
gint lineno,
gint charno);
gboolean gsk_xml_value_reader_had_error (GskXmlValueReader *reader);
/* Load an object from an XML file, for program configuration, etc. */
GObject * gsk_load_object_from_xml_file (const char *path,
GskGtypeLoader *type_loader,
GType object_type,
GError **error);
G_END_DECLS
#endif
|
davebenson/gsk
|
src/store/gskxmlvaluereader.h
|
C
|
lgpl-2.1
| 1,383
|
from nxdrive.tests.common_unit_test import UnitTestCase
from nxdrive.client import RemoteDocumentClient
from nxdrive.client import LocalClient
class TestSharedFolders(UnitTestCase):
def test_move_sync_root_child_to_user_workspace(self):
"""See https://jira.nuxeo.com/browse/NXP-14870"""
admin_remote_client = self.root_remote_client
user1_workspace_path = ('/default-domain/UserWorkspaces/'
'nuxeoDriveTestUser-user-1')
try:
# Get remote and local clients
remote_user1 = RemoteDocumentClient(
self.nuxeo_url, self.user_1, u'nxdrive-test-device-1',
self.version, password=self.password_1,
upload_tmp_dir=self.upload_tmp_dir)
remote_user2 = RemoteDocumentClient(
self.nuxeo_url, self.user_2, u'nxdrive-test-device-2',
self.version, password=self.password_2,
upload_tmp_dir=self.upload_tmp_dir)
local_user2 = LocalClient(self.local_nxdrive_folder_2)
# Make sure personal workspace is created for user1
remote_user1.make_file_in_user_workspace('File in user workspace',
filename='UWFile.txt')
# As user1 register personal workspace as a sync root
remote_user1.register_as_root(user1_workspace_path)
# As user1 create a parent folder in user1's personal workspace
remote_user1.make_folder(user1_workspace_path, 'Parent')
# As user1 grant Everything permission to user2 on parent folder
parent_folder_path = user1_workspace_path + '/Parent'
op_input = "doc:" + parent_folder_path
admin_remote_client.execute("Document.SetACE", op_input=op_input, user="nuxeoDriveTestUser_user_2",
permission="Everything", grant="true")
# As user1 create a child folder in parent folder
remote_user1.make_folder(parent_folder_path, 'Child')
# As user2 register parent folder as a sync root
remote_user2.register_as_root(parent_folder_path)
remote_user2.unregister_as_root(self.workspace)
# Start engine for user2
self.engine_2.start()
# Wait for synchronization
self.wait_sync(wait_for_async=True, wait_for_engine_1=False, wait_for_engine_2=True)
# Check locally synchronized content
self.assertEquals(len(local_user2.get_children_info('/')), 1)
self.assertTrue(local_user2.exists('/Parent'))
self.assertTrue(local_user2.exists('/Parent/Child'))
# As user1 move child folder to user1's personal workspace
remote_user1.move(parent_folder_path + '/Child',
user1_workspace_path)
# Wait for synchronization
self.wait_sync(wait_for_async=True, wait_for_engine_1=False, wait_for_engine_2=True)
# Check locally synchronized content
self.assertFalse(local_user2.exists('/Parent/Child'))
finally:
# Cleanup user1 personal workspace
if admin_remote_client.exists(user1_workspace_path):
admin_remote_client.delete(user1_workspace_path,
use_trash=False)
|
loopingz/nuxeo-drive
|
nuxeo-drive-client/nxdrive/tests/test_shared_folders.py
|
Python
|
lgpl-2.1
| 3,409
|
/*=========================================================================
Program: FEMuS
Module: MultiLevelProblem
Authors: Eugenio Aulisa, Simone Bnà, Giorgio Bornia
Copyright (c) FEMuS
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
//----------------------------------------------------------------------------
// includes :
//----------------------------------------------------------------------------
#include "MultiLevelProblem.hpp"
#include "MultiLevelSolution.hpp"
#include "MonolithicFSINonLinearImplicitSystem.hpp"
#include "ImplicitRungeKuttaSystem.hpp"
#include "TransientSystem.hpp"
#include "FemusConfig.hpp"
#include "Parameter.hpp"
#include "MultiLevelMeshTwo.hpp"
#include "GeomElTypeEnum.hpp"
#include <iostream>
namespace femus {
bool (* Mesh::_SetRefinementFlag)(const std::vector < double >& x, const int &ElemGroupNumber,const int &level) = NULL;
MultiLevelProblem::MultiLevelProblem():
_files(NULL)
{
}
MultiLevelProblem::MultiLevelProblem( MultiLevelSolution *ml_sol):
_ml_sol(ml_sol),
_ml_msh(ml_sol->_mlMesh),
_gridn(_ml_msh->GetNumberOfLevels()),
_files(NULL)
{
}
MultiLevelProblem::~MultiLevelProblem(){
for( system_iterator iterator = _systems.begin(); iterator != _systems.end(); iterator++) {
delete iterator->second;
}
}
void MultiLevelProblem::SetMultiLevelMeshAndSolution(MultiLevelMesh * ml_mesh, MultiLevelSolution * ml_sol) {
_ml_sol = ml_sol;
_ml_msh = ml_sol->_mlMesh;
_gridn = _ml_msh->GetNumberOfLevels();
}
System & MultiLevelProblem::add_system (const std::string& sys_type,
const std::string& name)
{
// If the user already built a system with this name, we'll
// trust them and we'll use it. That way they can pre-add
// non-standard derived system classes, and if their restart file
// has some non-standard sys_type we won't throw an error.
if (_systems.count(name))
{
return this->get_system(name);
}
// Build a basic System
else if (sys_type == "Basic")
this->add_system<System> (name);
// Build a Newmark system
// else if (sys_type == "Newmark")
// this->add_system<NewmarkSystem> (name);
// Build an Explicit system
else if ((sys_type == "Explicit"))
this->add_system<ExplicitSystem> (name);
// Build an Implicit system
else if ((sys_type == "Implicit") ||
(sys_type == "Steady" ))
this->add_system<ImplicitSystem> (name);
// build a transient implicit linear system
else if ((sys_type == "Transient") ||
(sys_type == "TransientImplicit") ||
(sys_type == "TransientLinearImplicit"))
this->add_system<TransientLinearImplicitSystem> (name);
// build a transient implicit nonlinear system
else if (sys_type == "TransientNonlinearImplicit")
this->add_system<TransientNonlinearImplicitSystem> (name);
// build a transient explicit system
else if (sys_type == "TransientExplicit")
this->add_system<TransientExplicitSystem> (name);
// build a linear implicit system
else if (sys_type == "LinearImplicit")
this->add_system<LinearImplicitSystem> (name);
// build a nonlinear implicit system
else if (sys_type == "NonlinearImplicit")
this->add_system<NonLinearImplicitSystem> (name);
else
{
std::cerr << "ERROR: Unknown system type: " << sys_type << std::endl;
}
// Return a reference to the new system
return this->get_system(name);
}
void MultiLevelProblem::clear ()
{
// Clear any additional parameters
parameters.clear();
// clear the systems. We must delete them
// since we newed them!
while (!_systems.empty())
{
system_iterator pos = _systems.begin();
System *sys = pos->second;
delete sys;
sys = NULL;
_systems.erase (pos);
}
}
// void MultiLevelProblem::init()
// {
// const unsigned int n_sys = this->n_systems();
//
// assert(n_sys != 0);
//
// for (unsigned int i=0; i != this->n_systems(); ++i)
// this->get_system(i).init();
// }
void MultiLevelProblem::SetQuadratureRuleAllGeomElems(const std::string quadr_order_in) {
std::vector< std::string > qrule_list(1);
qrule_list[0] = quadr_order_in;
SetQuadratureRuleAllGeomElemsMultiple(qrule_list);
// _qrule.resize(1);
// _qrule[0].reserve(N_GEOM_ELS);
//
// for (int iel = 0; iel < femus::geom_elems.size(); iel++) {
// Gauss qrule_temp(femus::geom_elems[iel].c_str(),quadr_order_in.c_str());
// _qrule[0].push_back(qrule_temp);
// }
return;
}
void MultiLevelProblem::SetQuadratureRuleAllGeomElemsMultiple(const std::vector<std::string> quadr_order_in_vec) {
_qrule.resize(quadr_order_in_vec.size());
for (int q = 0; q < _qrule.size(); q++) {
_qrule[q].reserve(N_GEOM_ELS);
for (int iel = 0; iel < femus::geom_elems.size(); iel++) {
Gauss qrule_temp(femus::geom_elems[iel].c_str(),quadr_order_in_vec[q].c_str());
_qrule[q].push_back(qrule_temp);
}
}
return;
}
} //end namespace femus
|
giorgiobornia/femus
|
src/03_equations/MultiLevelProblem.cpp
|
C++
|
lgpl-2.1
| 5,312
|
/*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A.
GNU Lesser General Public License
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation,
version 2.1 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*****************************************************************/
package jade.core.sam;
/**
* A provider of values for a given counter. The <code>isDifferential()<code> method
* indicates whether provided values are differential or total. In the former case
* if the counter value is now H and was K when <code>getValue()</code> was invoked at
* previous round, <code>getValue()</code> must return H-K.
*/
public interface CounterValueProvider {
long getValue();
boolean isDifferential();
}
|
djovanovic/JADE_PROJECT
|
src/jade/core/sam/CounterValueProvider.java
|
Java
|
lgpl-2.1
| 1,483
|
/*
Copyright (C) 2014 Fredrik Johansson
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/
#include <gmp.h>
#include "flint.h"
#include "ulong_extras.h"
#include "nmod_vec.h"
#include "nmod_poly.h"
void
nmod_poly_set_trunc(nmod_poly_t res, const nmod_poly_t poly, slong n)
{
if (poly == res)
{
nmod_poly_truncate(res, n);
}
else
{
slong rlen;
rlen = FLINT_MIN(n, poly->length);
while (rlen > 0 && poly->coeffs[rlen - 1] == 0)
rlen--;
nmod_poly_fit_length(res, rlen);
_nmod_vec_set(res->coeffs, poly->coeffs, rlen);
_nmod_poly_set_length(res, rlen);
}
}
|
fredrik-johansson/flint2
|
nmod_poly/set_trunc.c
|
C
|
lgpl-2.1
| 943
|
/*
* xmlformat - registration of xml object formats
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef XMLFORMAT_COMMON_H
#define XMLFORMAT_COMMON_H
// Categories
#define XMLFORMAT_COMMON_CATEGORIES "Categories"
#define XMLFORMAT_COMMON_CATEGORIES_CATEGORY "Category"
// Class
#define XMLFORMAT_COMMON_CLASS "Class"
#define XMLFORMAT_COMMON_CLASS_CONTENT "Content"
#define XMLFORMAT_COMMON_CLASS_CONTENT_PUBLIC "PUBLIC"
#define XMLFORMAT_COMMON_CLASS_CONTENT_PRIVATE "PRIVATE"
#define XMLFORMAT_COMMON_CLASS_CONTENT_CONFIDENTIAL "CONFIDENTIAL"
#define XMLFORMAT_COMMON_CLASS_CONTENT_DEFAULT XMLFORMAT_COMMON_CONTENT_PUBLIC
// DateValueType
#define XMLFORMAT_COMMON_DATEVALUETYPE "DateValueType"
#define XMLFORMAT_COMMON_DATEVALUETYPE_DATE "DATE"
#define XMLFORMAT_COMMON_DATEVALUETYPE_DATETIME "DATE-TIME"
// DateTimeContent
#define XMLFORMAT_COMMON_DATETIMECONTENT "DateTimeContent"
#define XMLFORMAT_COMMON_DATETIMECONTENT_CONTENT "Content" // Element
#define XMLFORMAT_COMMON_DATETIMECONTENT_VALUE "Value" // Attribute
#define XMLFORMAT_COMMON_DATETIMECONTENT_TIMEZONEID "TimezoneID" // Attribute
// Multitext
#define XMLFORMAT_COMMON_MULTITEXT "MultiText"
#define XMLFORMAT_COMMON_MULTITEXT_CONTENT "Content"
#define XMLFORMAT_COMMON_MULTITEXT_ALTERNATIVETEXTREP "AlternativeTextRep"
#define XMLFORMAT_COMMON_MULTITEXT_LANGUAGE "Language"
// StringContent
#define XMLFORMAT_COMMON_STRINGCONTENT "StringContent"
#define XMLFORMAT_COMMON_STRINGCONTENT_CONTENT "Content"
#endif /* XMLFORMAT_COMMON_H */
|
ianmartin/autoimportopensync
|
formats/xmlformat-common.h
|
C
|
lgpl-2.1
| 2,249
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.boot.model.source.internal.hbm;
import org.hibernate.boot.model.source.spi.SizeSource;
/**
* Implementation of SizeSource
*
* @author Steve Ebersole
* @author Gail Badner
*/
public class SizeSourceImpl implements SizeSource {
private final Integer length;
private final Integer scale;
private final Integer precision;
public SizeSourceImpl(Integer length, Integer scale, Integer precision) {
this.length = length;
this.scale = scale;
this.precision = precision;
}
@Override
public Integer getLength() {
return length;
}
@Override
public Integer getPrecision() {
return precision;
}
@Override
public Integer getScale() {
return scale;
}
}
|
1fechner/FeatureExtractor
|
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/SizeSourceImpl.java
|
Java
|
lgpl-2.1
| 934
|
/*
* Copyright 2007 Stephen Liu
* For license terms, see the file COPYING along with this library.
*/
#ifndef __spdictarray_hpp__
#define __spdictarray_hpp__
#include <stdio.h>
#include "spdictionary.hpp"
// sorted array
class SP_DictSortedArrayNode {
public:
SP_DictSortedArrayNode( void * item = 0 );
~SP_DictSortedArrayNode();
void setItem( void * item );
void * getItem() const;
void * takeItem();
private:
void * mItem;
};
class SP_DictSortedArrayIterator : public SP_DictIterator {
public:
SP_DictSortedArrayIterator( SP_DictSortedArrayNode ** list, int count );
virtual ~SP_DictSortedArrayIterator();
virtual const void * getNext( int * level = 0 );
private:
SP_DictSortedArrayNode ** mList;
int mCount;
int mIndex;
};
class SP_DictSortedArray : public SP_Dictionary {
public:
SP_DictSortedArray( SP_DictHandler * handler );
virtual ~SP_DictSortedArray();
virtual int insert( void * item );
virtual const void * search( const void * key ) const;
virtual void * remove( const void * key );
virtual int getCount() const;
virtual SP_DictIterator * getIterator() const;
private:
// @return >= 0 : found, -1 : not found
int binarySearch( const void * item, int * insertPoint = 0,
int firstIndex = 0, int size = -1 ) const;
SP_DictSortedArrayNode ** mList;
int mMaxCount;
int mCount;
SP_DictHandler * mHandler;
};
#endif
|
electri/spdict
|
spdictarray.hpp
|
C++
|
lgpl-2.1
| 1,371
|
/****************************************************************************
**
** 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 QLALR 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$
**
****************************************************************************/
#include "qparser.h"
|
igor-sfdc/qt-wk
|
util/qlalr/examples/qparser/qparser.cpp
|
C++
|
lgpl-2.1
| 1,515
|
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// "liveMedia"
// Copyright (c) 1996-2015 Live Networks, Inc. All rights reserved.
// A RTSP server
// Implementation
#include "RTSPServer.hh"
#include "RTSPCommon.hh"
#include "RTSPRegisterSender.hh"
#include "ProxyServerMediaSession.hh"
#include "Base64.hh"
#include <GroupsockHelper.hh>
#define ALLOW_RTSP_SERVER_PORT_REUSE
////////// RTSPServer implementation //////////
RTSPServer*
RTSPServer::createNew(UsageEnvironment& env, Port ourPort,
UserAuthenticationDatabase* authDatabase,
unsigned reclamationSeconds) {
int ourSocket = setUpOurSocket(env, ourPort);
if (ourSocket == -1) return NULL;
return new RTSPServer(env, ourSocket, ourPort, authDatabase, reclamationSeconds);
}
Boolean RTSPServer::lookupByName(UsageEnvironment& env,
char const* name,
RTSPServer*& resultServer) {
resultServer = NULL; // unless we succeed
Medium* medium;
if (!Medium::lookupByName(env, name, medium)) return False;
if (!medium->isRTSPServer()) {
env.setResultMsg(name, " is not a RTSP server");
return False;
}
resultServer = (RTSPServer*)medium;
return True;
}
void rtspRegisterResponseHandler(RTSPClient* rtspClient, int resultCode, char* resultString); // forward
// A class that represents the state of a "REGISTER" request in progress:
class RegisterRequestRecord: public RTSPRegisterSender {
public:
RegisterRequestRecord(RTSPServer& ourServer, unsigned requestId,
char const* remoteClientNameOrAddress, portNumBits remoteClientPortNum, char const* rtspURLToRegister,
RTSPServer::responseHandlerForREGISTER* responseHandler, Authenticator* authenticator,
Boolean requestStreamingViaTCP, char const* proxyURLSuffix)
: RTSPRegisterSender(ourServer.envir(), remoteClientNameOrAddress, remoteClientPortNum, rtspURLToRegister,
rtspRegisterResponseHandler, authenticator,
requestStreamingViaTCP, proxyURLSuffix, True/*reuseConnection*/,
#ifdef DEBUG
1/*verbosityLevel*/,
#else
0/*verbosityLevel*/,
#endif
NULL),
fOurServer(ourServer), fRequestId(requestId), fResponseHandler(responseHandler) {
// Add ourself to our server's 'pending REGISTER requests' table:
ourServer.fPendingRegisterRequests->Add((char const*)this, this);
}
virtual ~RegisterRequestRecord() {
// Remove ourself from the server's 'pending REGISTER requests' hash table before we go:
fOurServer.fPendingRegisterRequests->Remove((char const*)this);
}
void handleResponse(int resultCode, char* resultString) {
if (resultCode == 0) {
// The "REGISTER" request succeeded, so use the still-open RTSP socket to await incoming commands from the remote endpoint:
int sock;
struct sockaddr_in remoteAddress;
grabConnection(sock, remoteAddress);
if (sock >= 0) (void)fOurServer.createNewClientConnection(sock, remoteAddress);
}
if (fResponseHandler != NULL) {
// Call our (REGISTER-specific) response handler now:
(*fResponseHandler)(&fOurServer, fRequestId, resultCode, resultString);
} else {
// We need to delete[] "resultString" before we leave:
delete[] resultString;
}
// We're completely done with the REGISTER command now, so delete ourself now:
delete this;
}
private:
RTSPServer& fOurServer;
unsigned fRequestId;
RTSPServer::responseHandlerForREGISTER* fResponseHandler;
};
void rtspRegisterResponseHandler(RTSPClient* rtspClient, int resultCode, char* resultString) {
RegisterRequestRecord* registerRequestRecord = (RegisterRequestRecord*)rtspClient;
registerRequestRecord->handleResponse(resultCode, resultString);
}
unsigned RTSPServer::registerStream(ServerMediaSession* serverMediaSession,
char const* remoteClientNameOrAddress, portNumBits remoteClientPortNum,
responseHandlerForREGISTER* responseHandler,
char const* username, char const* password,
Boolean receiveOurStreamViaTCP, char const* proxyURLSuffix) {
// Create a new "RegisterRequestRecord" that will send the "REGISTER" command.
// (This object will automatically get deleted after we get a response to the "REGISTER" command, or if we're deleted.)
Authenticator* authenticator = NULL;
if (username != NULL) {
if (password == NULL) password = "";
authenticator = new Authenticator(username, password);
}
unsigned requestId = ++fRegisterRequestCounter;
new RegisterRequestRecord(*this, requestId,
remoteClientNameOrAddress, remoteClientPortNum, rtspURL(serverMediaSession),
responseHandler, authenticator,
receiveOurStreamViaTCP, proxyURLSuffix);
delete authenticator; // we can do this here because it was copied to the "RegisterRequestRecord"
return requestId;
}
char* RTSPServer
::rtspURL(ServerMediaSession const* serverMediaSession, int clientSocket) const {
char* urlPrefix = rtspURLPrefix(clientSocket);
char const* sessionName = serverMediaSession->streamName();
char* resultURL = new char[strlen(urlPrefix) + strlen(sessionName) + 1];
sprintf(resultURL, "%s%s", urlPrefix, sessionName);
delete[] urlPrefix;
return resultURL;
}
char* RTSPServer::rtspURLPrefix(int clientSocket) const {
struct sockaddr_in ourAddress;
if (clientSocket < 0) {
// Use our default IP address in the URL:
ourAddress.sin_addr.s_addr = ReceivingInterfaceAddr != 0
? ReceivingInterfaceAddr
: ourIPAddress(envir()); // hack
} else {
SOCKLEN_T namelen = sizeof ourAddress;
getsockname(clientSocket, (struct sockaddr*)&ourAddress, &namelen);
}
char urlBuffer[100]; // more than big enough for "rtsp://<ip-address>:<port>/"
portNumBits portNumHostOrder = ntohs(fServerPort.num());
if (portNumHostOrder == 554 /* the default port number */) {
sprintf(urlBuffer, "rtsp://%s/", AddressString(ourAddress).val());
} else {
sprintf(urlBuffer, "rtsp://%s:%hu/",
AddressString(ourAddress).val(), portNumHostOrder);
}
return strDup(urlBuffer);
}
UserAuthenticationDatabase* RTSPServer::setAuthenticationDatabase(UserAuthenticationDatabase* newDB) {
UserAuthenticationDatabase* oldDB = fAuthDB;
fAuthDB = newDB;
return oldDB;
}
Boolean RTSPServer::setUpTunnelingOverHTTP(Port httpPort) {
fHTTPServerSocket = setUpOurSocket(envir(), httpPort);
if (fHTTPServerSocket >= 0) {
fHTTPServerPort = httpPort;
envir().taskScheduler().turnOnBackgroundReadHandling(fHTTPServerSocket,
incomingConnectionHandlerHTTP, this);
return True;
}
return False;
}
portNumBits RTSPServer::httpServerPortNum() const {
return ntohs(fHTTPServerPort.num());
}
char const* RTSPServer::allowedCommandNames() {
return "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE, GET_PARAMETER, SET_PARAMETER";
}
Boolean RTSPServer::weImplementREGISTER(char const* /*proxyURLSuffix*/, char*& responseStr) {
// By default, servers do not implement our custom "REGISTER" command:
responseStr = NULL;
return False;
}
void RTSPServer::implementCmd_REGISTER(char const* /*url*/, char const* /*urlSuffix*/, int /*socketToRemoteServer*/,
Boolean /*deliverViaTCP*/, char const* /*proxyURLSuffix*/) {
// By default, this function is a 'noop'
}
UserAuthenticationDatabase* RTSPServer::getAuthenticationDatabaseForCommand(char const* /*cmdName*/) {
// default implementation
return fAuthDB;
}
Boolean RTSPServer::specialClientAccessCheck(int /*clientSocket*/, struct sockaddr_in& /*clientAddr*/, char const* /*urlSuffix*/) {
// default implementation
return True;
}
Boolean RTSPServer::specialClientUserAccessCheck(int /*clientSocket*/, struct sockaddr_in& /*clientAddr*/,
char const* /*urlSuffix*/, char const * /*username*/) {
// default implementation; no further access restrictions:
return True;
}
RTSPServer::RTSPServer(UsageEnvironment& env,
int ourSocket, Port ourPort,
UserAuthenticationDatabase* authDatabase,
unsigned reclamationSeconds)
: GenericMediaServer(env, ourSocket, ourPort, reclamationSeconds),
fHTTPServerSocket(-1), fHTTPServerPort(0),
fClientConnectionsForHTTPTunneling(NULL), // will get created if needed
fTCPStreamingDatabase(HashTable::create(ONE_WORD_HASH_KEYS)),
fPendingRegisterRequests(HashTable::create(ONE_WORD_HASH_KEYS)), fRegisterRequestCounter(0),
fAuthDB(authDatabase), fAllowStreamingRTPOverTCP(True) {
}
// A data structure that is used to implement "fTCPStreamingDatabase"
// (and the "noteTCPStreamingOnSocket()" and "stopTCPStreamingOnSocket()" member functions):
class streamingOverTCPRecord {
public:
streamingOverTCPRecord(u_int32_t sessionId, unsigned trackNum, streamingOverTCPRecord* next)
: fNext(next), fSessionId(sessionId), fTrackNum(trackNum) {
}
virtual ~streamingOverTCPRecord() {
delete fNext;
}
streamingOverTCPRecord* fNext;
u_int32_t fSessionId;
unsigned fTrackNum;
};
RTSPServer::~RTSPServer() {
// Turn off background HTTP read handling (if any):
envir().taskScheduler().turnOffBackgroundReadHandling(fHTTPServerSocket);
::closeSocket(fHTTPServerSocket);
delete fClientConnectionsForHTTPTunneling;
cleanup(); // Removes all "ClientSession" and "ClientConnection" objects, and their tables.
// Delete any pending REGISTER requests:
RegisterRequestRecord* registerRequest;
while ((registerRequest = (RegisterRequestRecord*)fPendingRegisterRequests->getFirst()) != NULL) {
delete registerRequest;
}
delete fPendingRegisterRequests;
// Empty out and close "fTCPStreamingDatabase":
streamingOverTCPRecord* sotcp;
while ((sotcp = (streamingOverTCPRecord*)fTCPStreamingDatabase->getFirst()) != NULL) {
delete sotcp;
}
delete fTCPStreamingDatabase;
}
Boolean RTSPServer::isRTSPServer() const {
return True;
}
void RTSPServer::incomingConnectionHandlerHTTP(void* instance, int /*mask*/) {
RTSPServer* server = (RTSPServer*)instance;
server->incomingConnectionHandlerHTTP();
}
void RTSPServer::incomingConnectionHandlerHTTP() {
incomingConnectionHandlerOnSocket(fHTTPServerSocket);
}
void RTSPServer
::noteTCPStreamingOnSocket(int socketNum, RTSPClientSession* clientSession, unsigned trackNum) {
streamingOverTCPRecord* sotcpCur
= (streamingOverTCPRecord*)fTCPStreamingDatabase->Lookup((char const*)socketNum);
streamingOverTCPRecord* sotcpNew
= new streamingOverTCPRecord(clientSession->fOurSessionId, trackNum, sotcpCur);
fTCPStreamingDatabase->Add((char const*)socketNum, sotcpNew);
}
void RTSPServer
::unnoteTCPStreamingOnSocket(int socketNum, RTSPClientSession* clientSession, unsigned trackNum) {
if (socketNum < 0) return;
streamingOverTCPRecord* sotcpHead
= (streamingOverTCPRecord*)fTCPStreamingDatabase->Lookup((char const*)socketNum);
if (sotcpHead == NULL) return;
// Look for a record of the (session,track); remove it if found:
streamingOverTCPRecord* sotcp = sotcpHead;
streamingOverTCPRecord* sotcpPrev = sotcpHead;
do {
if (sotcp->fSessionId == clientSession->fOurSessionId && sotcp->fTrackNum == trackNum) break;
sotcpPrev = sotcp;
sotcp = sotcp->fNext;
} while (sotcp != NULL);
if (sotcp == NULL) return; // not found
if (sotcp == sotcpHead) {
// We found it at the head of the list. Remove it and reinsert the tail into the hash table:
sotcpHead = sotcp->fNext;
sotcp->fNext = NULL;
delete sotcp;
if (sotcpHead == NULL) {
// There were no more entries on the list. Remove the original entry from the hash table:
fTCPStreamingDatabase->Remove((char const*)socketNum);
} else {
// Add the rest of the list into the hash table (replacing the original):
fTCPStreamingDatabase->Add((char const*)socketNum, sotcpHead);
}
} else {
// We found it on the list, but not at the head. Unlink it:
sotcpPrev->fNext = sotcp->fNext;
sotcp->fNext = NULL;
delete sotcp;
}
}
void RTSPServer::stopTCPStreamingOnSocket(int socketNum) {
// Close any stream that is streaming over "socketNum" (using RTP/RTCP-over-TCP streaming):
streamingOverTCPRecord* sotcp
= (streamingOverTCPRecord*)fTCPStreamingDatabase->Lookup((char const*)socketNum);
if (sotcp != NULL) {
do {
char sessionIdStr[9];
sprintf(sessionIdStr, "%08X", sotcp->fSessionId);
RTSPClientSession* clientSession
= (RTSPServer::RTSPClientSession*)(fClientSessions->Lookup(sessionIdStr));
if (clientSession != NULL) {
clientSession->deleteStreamByTrack(sotcp->fTrackNum);
}
streamingOverTCPRecord* sotcpNext = sotcp->fNext;
sotcp->fNext = NULL;
delete sotcp;
sotcp = sotcpNext;
} while (sotcp != NULL);
fTCPStreamingDatabase->Remove((char const*)socketNum);
}
}
////////// RTSPServer::RTSPClientConnection implementation //////////
RTSPServer::RTSPClientConnection
::RTSPClientConnection(RTSPServer& ourServer, int clientSocket, struct sockaddr_in clientAddr)
: GenericMediaServer::ClientConnection(ourServer, clientSocket, clientAddr),
fOurRTSPServer(ourServer), fClientInputSocket(fOurSocket), fClientOutputSocket(fOurSocket),
fIsActive(True), fRecursionCount(0), fOurSessionCookie(NULL) {
resetRequestBuffer();
}
RTSPServer::RTSPClientConnection::~RTSPClientConnection() {
if (fOurSessionCookie != NULL) {
// We were being used for RTSP-over-HTTP tunneling. Also remove ourselves from the 'session cookie' hash table before we go:
fOurRTSPServer.fClientConnectionsForHTTPTunneling->Remove(fOurSessionCookie);
delete[] fOurSessionCookie;
}
closeSocketsRTSP();
}
// Special mechanism for handling our custom "REGISTER" command:
RTSPServer::RTSPClientConnection::ParamsForREGISTER
::ParamsForREGISTER(RTSPServer::RTSPClientConnection* ourConnection, char const* url, char const* urlSuffix,
Boolean reuseConnection, Boolean deliverViaTCP, char const* proxyURLSuffix)
: fOurConnection(ourConnection), fURL(strDup(url)), fURLSuffix(strDup(urlSuffix)),
fReuseConnection(reuseConnection), fDeliverViaTCP(deliverViaTCP), fProxyURLSuffix(strDup(proxyURLSuffix)) {
}
RTSPServer::RTSPClientConnection::ParamsForREGISTER::~ParamsForREGISTER() {
delete[] fURL; delete[] fURLSuffix; delete[] fProxyURLSuffix;
}
// Handler routines for specific RTSP commands:
void RTSPServer::RTSPClientConnection::handleCmd_OPTIONS() {
snprintf((char*)fResponseBuffer, sizeof fResponseBuffer,
"RTSP/1.0 200 OK\r\nCSeq: %s\r\n%sPublic: %s\r\n\r\n",
fCurrentCSeq, dateHeader(), fOurRTSPServer.allowedCommandNames());
}
void RTSPServer::RTSPClientConnection
::handleCmd_GET_PARAMETER(char const* /*fullRequestStr*/) {
// By default, we implement "GET_PARAMETER" (on the entire server) just as a 'no op', and send back a dummy response.
// (If you want to handle this type of "GET_PARAMETER" differently, you can do so by defining a subclass of "RTSPServer"
// and "RTSPServer::RTSPClientConnection", and then reimplement this virtual function in your subclass.)
setRTSPResponse("200 OK", LIVEMEDIA_LIBRARY_VERSION_STRING);
}
void RTSPServer::RTSPClientConnection
::handleCmd_SET_PARAMETER(char const* /*fullRequestStr*/) {
// By default, we implement "SET_PARAMETER" (on the entire server) just as a 'no op', and send back an empty response.
// (If you want to handle this type of "SET_PARAMETER" differently, you can do so by defining a subclass of "RTSPServer"
// and "RTSPServer::RTSPClientConnection", and then reimplement this virtual function in your subclass.)
setRTSPResponse("200 OK");
}
void RTSPServer::RTSPClientConnection
::handleCmd_DESCRIBE(char const* urlPreSuffix, char const* urlSuffix, char const* fullRequestStr) {
ServerMediaSession* session = NULL;
char* sdpDescription = NULL;
char* rtspURL = NULL;
do {
char urlTotalSuffix[2*RTSP_PARAM_STRING_MAX];
// enough space for urlPreSuffix/urlSuffix'\0'
urlTotalSuffix[0] = '\0';
if (urlPreSuffix[0] != '\0') {
strcat(urlTotalSuffix, urlPreSuffix);
strcat(urlTotalSuffix, "/");
}
strcat(urlTotalSuffix, urlSuffix);
if (!authenticationOK("DESCRIBE", urlTotalSuffix, fullRequestStr)) break;
// We should really check that the request contains an "Accept:" #####
// for "application/sdp", because that's what we're sending back #####
// Begin by looking up the "ServerMediaSession" object for the specified "urlTotalSuffix":
session = fOurServer.lookupServerMediaSession(urlTotalSuffix);
if (session == NULL) {
handleCmd_notFound();
break;
}
// Increment the "ServerMediaSession" object's reference count, in case someone removes it
// while we're using it:
session->incrementReferenceCount();
// Then, assemble a SDP description for this session:
sdpDescription = session->generateSDPDescription();
if (sdpDescription == NULL) {
// This usually means that a file name that was specified for a
// "ServerMediaSubsession" does not exist.
setRTSPResponse("404 File Not Found, Or In Incorrect Format");
break;
}
unsigned sdpDescriptionSize = strlen(sdpDescription);
// Also, generate our RTSP URL, for the "Content-Base:" header
// (which is necessary to ensure that the correct URL gets used in subsequent "SETUP" requests).
rtspURL = fOurRTSPServer.rtspURL(session, fClientInputSocket);
snprintf((char*)fResponseBuffer, sizeof fResponseBuffer,
"RTSP/1.0 200 OK\r\nCSeq: %s\r\n"
"%s"
"Content-Base: %s/\r\n"
"Content-Type: application/sdp\r\n"
"Content-Length: %d\r\n\r\n"
"%s",
fCurrentCSeq,
dateHeader(),
rtspURL,
sdpDescriptionSize,
sdpDescription);
} while (0);
if (session != NULL) {
// Decrement its reference count, now that we're done using it:
session->decrementReferenceCount();
if (session->referenceCount() == 0 && session->deleteWhenUnreferenced()) {
fOurServer.removeServerMediaSession(session);
}
}
delete[] sdpDescription;
delete[] rtspURL;
}
static void lookForHeader(char const* headerName, char const* source, unsigned sourceLen, char* resultStr, unsigned resultMaxSize) {
resultStr[0] = '\0'; // by default, return an empty string
unsigned headerNameLen = strlen(headerName);
for (int i = 0; i < (int)(sourceLen-headerNameLen); ++i) {
if (strncmp(&source[i], headerName, headerNameLen) == 0 && source[i+headerNameLen] == ':') {
// We found the header. Skip over any whitespace, then copy the rest of the line to "resultStr":
for (i += headerNameLen+1; i < (int)sourceLen && (source[i] == ' ' || source[i] == '\t'); ++i) {}
for (unsigned j = i; j < sourceLen; ++j) {
if (source[j] == '\r' || source[j] == '\n') {
// We've found the end of the line. Copy it to the result (if it will fit):
if (j-i+1 > resultMaxSize) break;
char const* resultSource = &source[i];
char const* resultSourceEnd = &source[j];
while (resultSource < resultSourceEnd) *resultStr++ = *resultSource++;
*resultStr = '\0';
break;
}
}
}
}
}
void RTSPServer
::RTSPClientConnection::handleCmd_REGISTER(char const* url, char const* urlSuffix, char const* fullRequestStr,
Boolean reuseConnection, Boolean deliverViaTCP, char const* proxyURLSuffix) {
char* responseStr;
if (fOurRTSPServer.weImplementREGISTER(proxyURLSuffix, responseStr)) {
// The "REGISTER" command - if we implement it - may require access control:
if (!authenticationOK("REGISTER", urlSuffix, fullRequestStr)) return;
// We implement the "REGISTER" command by first replying to it, then actually handling it
// (in a separate event-loop task, that will get called after the reply has been done):
setRTSPResponse(responseStr == NULL ? "200 OK" : responseStr);
delete[] responseStr;
ParamsForREGISTER* registerParams = new ParamsForREGISTER(this, url, urlSuffix, reuseConnection, deliverViaTCP, proxyURLSuffix);
envir().taskScheduler().scheduleDelayedTask(0, (TaskFunc*)continueHandlingREGISTER, registerParams);
} else if (responseStr != NULL) {
setRTSPResponse(responseStr);
delete[] responseStr;
} else {
handleCmd_notSupported();
}
}
void RTSPServer::RTSPClientConnection::handleCmd_bad() {
// Don't do anything with "fCurrentCSeq", because it might be nonsense
snprintf((char*)fResponseBuffer, sizeof fResponseBuffer,
"RTSP/1.0 400 Bad Request\r\n%sAllow: %s\r\n\r\n",
dateHeader(), fOurRTSPServer.allowedCommandNames());
}
void RTSPServer::RTSPClientConnection::handleCmd_notSupported() {
snprintf((char*)fResponseBuffer, sizeof fResponseBuffer,
"RTSP/1.0 405 Method Not Allowed\r\nCSeq: %s\r\n%sAllow: %s\r\n\r\n",
fCurrentCSeq, dateHeader(), fOurRTSPServer.allowedCommandNames());
}
void RTSPServer::RTSPClientConnection::handleCmd_notFound() {
setRTSPResponse("404 Stream Not Found");
}
void RTSPServer::RTSPClientConnection::handleCmd_sessionNotFound() {
setRTSPResponse("454 Session Not Found");
}
void RTSPServer::RTSPClientConnection::handleCmd_unsupportedTransport() {
setRTSPResponse("461 Unsupported Transport");
}
Boolean RTSPServer::RTSPClientConnection::parseHTTPRequestString(char* resultCmdName, unsigned resultCmdNameMaxSize,
char* urlSuffix, unsigned urlSuffixMaxSize,
char* sessionCookie, unsigned sessionCookieMaxSize,
char* acceptStr, unsigned acceptStrMaxSize) {
// Check for the limited HTTP requests that we expect for specifying RTSP-over-HTTP tunneling.
// This parser is currently rather dumb; it should be made smarter #####
char const* reqStr = (char const*)fRequestBuffer;
unsigned const reqStrSize = fRequestBytesAlreadySeen;
// Read everything up to the first space as the command name:
Boolean parseSucceeded = False;
unsigned i;
for (i = 0; i < resultCmdNameMaxSize-1 && i < reqStrSize; ++i) {
char c = reqStr[i];
if (c == ' ' || c == '\t') {
parseSucceeded = True;
break;
}
resultCmdName[i] = c;
}
resultCmdName[i] = '\0';
if (!parseSucceeded) return False;
// Look for the string "HTTP/", before the first \r or \n:
parseSucceeded = False;
for (; i < reqStrSize-5 && reqStr[i] != '\r' && reqStr[i] != '\n'; ++i) {
if (reqStr[i] == 'H' && reqStr[i+1] == 'T' && reqStr[i+2]== 'T' && reqStr[i+3]== 'P' && reqStr[i+4]== '/') {
i += 5; // to advance past the "HTTP/"
parseSucceeded = True;
break;
}
}
if (!parseSucceeded) return False;
// Get the 'URL suffix' that occurred before this:
unsigned k = i-6;
while (k > 0 && reqStr[k] == ' ') --k; // back up over white space
unsigned j = k;
while (j > 0 && reqStr[j] != ' ' && reqStr[j] != '/') --j;
// The URL suffix is in position (j,k]:
if (k - j + 1 > urlSuffixMaxSize) return False; // there's no room>
unsigned n = 0;
while (++j <= k) urlSuffix[n++] = reqStr[j];
urlSuffix[n] = '\0';
// Look for various headers that we're interested in:
lookForHeader("x-sessioncookie", &reqStr[i], reqStrSize-i, sessionCookie, sessionCookieMaxSize);
lookForHeader("Accept", &reqStr[i], reqStrSize-i, acceptStr, acceptStrMaxSize);
return True;
}
void RTSPServer::RTSPClientConnection::handleHTTPCmd_notSupported() {
snprintf((char*)fResponseBuffer, sizeof fResponseBuffer,
"HTTP/1.1 405 Method Not Allowed\r\n%s\r\n\r\n",
dateHeader());
}
void RTSPServer::RTSPClientConnection::handleHTTPCmd_notFound() {
snprintf((char*)fResponseBuffer, sizeof fResponseBuffer,
"HTTP/1.1 404 Not Found\r\n%s\r\n\r\n",
dateHeader());
}
void RTSPServer::RTSPClientConnection::handleHTTPCmd_OPTIONS() {
#ifdef DEBUG
fprintf(stderr, "Handled HTTP \"OPTIONS\" request\n");
#endif
// Construct a response to the "OPTIONS" command that notes that our special headers (for RTSP-over-HTTP tunneling) are allowed:
snprintf((char*)fResponseBuffer, sizeof fResponseBuffer,
"HTTP/1.1 200 OK\r\n"
"%s"
"Access-Control-Allow-Origin: *\r\n"
"Access-Control-Allow-Methods: POST, GET, OPTIONS\r\n"
"Access-Control-Allow-Headers: x-sessioncookie, Pragma, Cache-Control\r\n"
"Access-Control-Max-Age: 1728000\r\n"
"\r\n",
dateHeader());
}
void RTSPServer::RTSPClientConnection::handleHTTPCmd_TunnelingGET(char const* sessionCookie) {
// Record ourself as having this 'session cookie', so that a subsequent HTTP "POST" command (with the same 'session cookie')
// can find us:
if (fOurRTSPServer.fClientConnectionsForHTTPTunneling == NULL) {
fOurRTSPServer.fClientConnectionsForHTTPTunneling = HashTable::create(STRING_HASH_KEYS);
}
delete[] fOurSessionCookie; fOurSessionCookie = strDup(sessionCookie);
fOurRTSPServer.fClientConnectionsForHTTPTunneling->Add(sessionCookie, (void*)this);
#ifdef DEBUG
fprintf(stderr, "Handled HTTP \"GET\" request (client output socket: %d)\n", fClientOutputSocket);
#endif
// Construct our response:
snprintf((char*)fResponseBuffer, sizeof fResponseBuffer,
"HTTP/1.1 200 OK\r\n"
"%s"
"Cache-Control: no-cache\r\n"
"Pragma: no-cache\r\n"
"Content-Type: application/x-rtsp-tunnelled\r\n"
"\r\n",
dateHeader());
}
Boolean RTSPServer::RTSPClientConnection
::handleHTTPCmd_TunnelingPOST(char const* sessionCookie, unsigned char const* extraData, unsigned extraDataSize) {
// Use the "sessionCookie" string to look up the separate "RTSPClientConnection" object that should have been used to handle
// an earlier HTTP "GET" request:
if (fOurRTSPServer.fClientConnectionsForHTTPTunneling == NULL) {
fOurRTSPServer.fClientConnectionsForHTTPTunneling = HashTable::create(STRING_HASH_KEYS);
}
RTSPServer::RTSPClientConnection* prevClientConnection
= (RTSPServer::RTSPClientConnection*)(fOurRTSPServer.fClientConnectionsForHTTPTunneling->Lookup(sessionCookie));
if (prevClientConnection == NULL) {
// There was no previous HTTP "GET" request; treat this "POST" request as bad:
handleHTTPCmd_notSupported();
fIsActive = False; // triggers deletion of ourself
return False;
}
#ifdef DEBUG
fprintf(stderr, "Handled HTTP \"POST\" request (client input socket: %d)\n", fClientInputSocket);
#endif
// Change the previous "RTSPClientSession" object's input socket to ours. It will be used for subsequent requests:
prevClientConnection->changeClientInputSocket(fClientInputSocket, extraData, extraDataSize);
fClientInputSocket = fClientOutputSocket = -1; // so the socket doesn't get closed when we get deleted
return True;
}
void RTSPServer::RTSPClientConnection::handleHTTPCmd_StreamingGET(char const* /*urlSuffix*/, char const* /*fullRequestStr*/) {
// By default, we don't support requests to access streams via HTTP:
handleHTTPCmd_notSupported();
}
void RTSPServer::RTSPClientConnection::resetRequestBuffer() {
ClientConnection::resetRequestBuffer();
fLastCRLF = &fRequestBuffer[-3]; // hack: Ensures that we don't think we have end-of-msg if the data starts with <CR><LF>
fBase64RemainderCount = 0;
}
void RTSPServer::RTSPClientConnection::closeSocketsRTSP() {
// First, tell our server to stop any streaming that it might be doing over our output socket:
fOurRTSPServer.stopTCPStreamingOnSocket(fClientOutputSocket);
// Turn off background handling on our input socket (and output socket, if different); then close it (or them):
if (fClientOutputSocket != fClientInputSocket) {
envir().taskScheduler().disableBackgroundHandling(fClientOutputSocket);
::closeSocket(fClientOutputSocket);
}
fClientOutputSocket = -1;
closeSockets(); // closes fClientInputSocket
}
void RTSPServer::RTSPClientConnection::handleAlternativeRequestByte(void* instance, u_int8_t requestByte) {
RTSPClientConnection* connection = (RTSPClientConnection*)instance;
connection->handleAlternativeRequestByte1(requestByte);
}
void RTSPServer::RTSPClientConnection::handleAlternativeRequestByte1(u_int8_t requestByte) {
if (requestByte == 0xFF) {
// Hack: The new handler of the input TCP socket encountered an error reading it. Indicate this:
handleRequestBytes(-1);
} else if (requestByte == 0xFE) {
// Another hack: The new handler of the input TCP socket no longer needs it, so take back control of it:
envir().taskScheduler().setBackgroundHandling(fClientInputSocket, SOCKET_READABLE|SOCKET_EXCEPTION,
incomingRequestHandler, this);
} else {
// Normal case: Add this character to our buffer; then try to handle the data that we have buffered so far:
if (fRequestBufferBytesLeft == 0 || fRequestBytesAlreadySeen >= REQUEST_BUFFER_SIZE) return;
fRequestBuffer[fRequestBytesAlreadySeen] = requestByte;
handleRequestBytes(1);
}
}
// A special version of "parseTransportHeader()", used just for parsing the "Transport:" header in an incoming "REGISTER" command:
static void parseTransportHeaderForREGISTER(char const* buf,
Boolean &reuseConnection,
Boolean& deliverViaTCP,
char*& proxyURLSuffix) {
// Initialize the result parameters to default values:
reuseConnection = False;
deliverViaTCP = False;
proxyURLSuffix = NULL;
// First, find "Transport:"
while (1) {
if (*buf == '\0') return; // not found
if (*buf == '\r' && *(buf+1) == '\n' && *(buf+2) == '\r') return; // end of the headers => not found
if (_strncasecmp(buf, "Transport:", 10) == 0) break;
++buf;
}
// Then, run through each of the fields, looking for ones we handle:
char const* fields = buf + 10;
while (*fields == ' ') ++fields;
char* field = strDupSize(fields);
while (sscanf(fields, "%[^;\r\n]", field) == 1) {
if (strcmp(field, "reuse_connection") == 0) {
reuseConnection = True;
} else if (_strncasecmp(field, "preferred_delivery_protocol=udp", 31) == 0) {
deliverViaTCP = False;
} else if (_strncasecmp(field, "preferred_delivery_protocol=interleaved", 39) == 0) {
deliverViaTCP = True;
} else if (_strncasecmp(field, "proxy_url_suffix=", 17) == 0) {
delete[] proxyURLSuffix;
proxyURLSuffix = strDup(field+17);
}
fields += strlen(field);
while (*fields == ';' || *fields == ' ' || *fields == '\t') ++fields; // skip over separating ';' chars or whitespace
if (*fields == '\0' || *fields == '\r' || *fields == '\n') break;
}
delete[] field;
}
void RTSPServer::RTSPClientConnection::handleRequestBytes(int newBytesRead) {
int numBytesRemaining = 0;
++fRecursionCount;
do {
RTSPServer::RTSPClientSession* clientSession = NULL;
if (newBytesRead < 0 || (unsigned)newBytesRead >= fRequestBufferBytesLeft) {
// Either the client socket has died, or the request was too big for us.
// Terminate this connection:
#ifdef DEBUG
fprintf(stderr, "RTSPClientConnection[%p]::handleRequestBytes() read %d new bytes (of %d); terminating connection!\n", this, newBytesRead, fRequestBufferBytesLeft);
#endif
fIsActive = False;
break;
}
Boolean endOfMsg = False;
unsigned char* ptr = &fRequestBuffer[fRequestBytesAlreadySeen];
#ifdef DEBUG
ptr[newBytesRead] = '\0';
fprintf(stderr, "RTSPClientConnection[%p]::handleRequestBytes() %s %d new bytes:%s\n",
this, numBytesRemaining > 0 ? "processing" : "read", newBytesRead, ptr);
#endif
if (fClientOutputSocket != fClientInputSocket && numBytesRemaining == 0) {
// We're doing RTSP-over-HTTP tunneling, and input commands are assumed to have been Base64-encoded.
// We therefore Base64-decode as much of this new data as we can (i.e., up to a multiple of 4 bytes).
// But first, we remove any whitespace that may be in the input data:
unsigned toIndex = 0;
for (int fromIndex = 0; fromIndex < newBytesRead; ++fromIndex) {
char c = ptr[fromIndex];
if (!(c == ' ' || c == '\t' || c == '\r' || c == '\n')) { // not 'whitespace': space,tab,CR,NL
ptr[toIndex++] = c;
}
}
newBytesRead = toIndex;
unsigned numBytesToDecode = fBase64RemainderCount + newBytesRead;
unsigned newBase64RemainderCount = numBytesToDecode%4;
numBytesToDecode -= newBase64RemainderCount;
if (numBytesToDecode > 0) {
ptr[newBytesRead] = '\0';
unsigned decodedSize;
unsigned char* decodedBytes = base64Decode((char const*)(ptr-fBase64RemainderCount), numBytesToDecode, decodedSize);
#ifdef DEBUG
fprintf(stderr, "Base64-decoded %d input bytes into %d new bytes:", numBytesToDecode, decodedSize);
for (unsigned k = 0; k < decodedSize; ++k) fprintf(stderr, "%c", decodedBytes[k]);
fprintf(stderr, "\n");
#endif
// Copy the new decoded bytes in place of the old ones (we can do this because there are fewer decoded bytes than original):
unsigned char* to = ptr-fBase64RemainderCount;
for (unsigned i = 0; i < decodedSize; ++i) *to++ = decodedBytes[i];
// Then copy any remaining (undecoded) bytes to the end:
for (unsigned j = 0; j < newBase64RemainderCount; ++j) *to++ = (ptr-fBase64RemainderCount+numBytesToDecode)[j];
newBytesRead = decodedSize - fBase64RemainderCount + newBase64RemainderCount;
// adjust to allow for the size of the new decoded data (+ remainder)
delete[] decodedBytes;
}
fBase64RemainderCount = newBase64RemainderCount;
}
unsigned char* tmpPtr = fLastCRLF + 2;
if (fBase64RemainderCount == 0) { // no more Base-64 bytes remain to be read/decoded
// Look for the end of the message: <CR><LF><CR><LF>
if (tmpPtr < fRequestBuffer) tmpPtr = fRequestBuffer;
while (tmpPtr < &ptr[newBytesRead-1]) {
if (*tmpPtr == '\r' && *(tmpPtr+1) == '\n') {
if (tmpPtr - fLastCRLF == 2) { // This is it:
endOfMsg = True;
break;
}
fLastCRLF = tmpPtr;
}
++tmpPtr;
}
}
fRequestBufferBytesLeft -= newBytesRead;
fRequestBytesAlreadySeen += newBytesRead;
if (!endOfMsg) break; // subsequent reads will be needed to complete the request
// Parse the request string into command name and 'CSeq', then handle the command:
fRequestBuffer[fRequestBytesAlreadySeen] = '\0';
char cmdName[RTSP_PARAM_STRING_MAX];
char urlPreSuffix[RTSP_PARAM_STRING_MAX];
char urlSuffix[RTSP_PARAM_STRING_MAX];
char cseq[RTSP_PARAM_STRING_MAX];
char sessionIdStr[RTSP_PARAM_STRING_MAX];
unsigned contentLength = 0;
fLastCRLF[2] = '\0'; // temporarily, for parsing
Boolean parseSucceeded = parseRTSPRequestString((char*)fRequestBuffer, fLastCRLF+2 - fRequestBuffer,
cmdName, sizeof cmdName,
urlPreSuffix, sizeof urlPreSuffix,
urlSuffix, sizeof urlSuffix,
cseq, sizeof cseq,
sessionIdStr, sizeof sessionIdStr,
contentLength);
fLastCRLF[2] = '\r'; // restore its value
Boolean playAfterSetup = False;
if (parseSucceeded) {
#ifdef DEBUG
fprintf(stderr, "parseRTSPRequestString() succeeded, returning cmdName \"%s\", urlPreSuffix \"%s\", urlSuffix \"%s\", CSeq \"%s\", Content-Length %u, with %d bytes following the message.\n", cmdName, urlPreSuffix, urlSuffix, cseq, contentLength, ptr + newBytesRead - (tmpPtr + 2));
#endif
// If there was a "Content-Length:" header, then make sure we've received all of the data that it specified:
if (ptr + newBytesRead < tmpPtr + 2 + contentLength) break; // we still need more data; subsequent reads will give it to us
// If the request included a "Session:" id, and it refers to a client session that's
// current ongoing, then use this command to indicate 'liveness' on that client session:
Boolean const requestIncludedSessionId = sessionIdStr[0] != '\0';
if (requestIncludedSessionId) {
clientSession = (RTSPServer::RTSPClientSession*)(fOurRTSPServer.fClientSessions->Lookup(sessionIdStr));
if (clientSession != NULL) clientSession->noteLiveness();
}
// We now have a complete RTSP request.
// Handle the specified command (beginning with commands that are session-independent):
fCurrentCSeq = cseq;
if (strcmp(cmdName, "OPTIONS") == 0) {
// If the "OPTIONS" command included a "Session:" id for a session that doesn't exist,
// then treat this as an error:
if (requestIncludedSessionId && clientSession == NULL) {
handleCmd_sessionNotFound();
} else {
// Normal case:
handleCmd_OPTIONS();
}
} else if (urlPreSuffix[0] == '\0' && urlSuffix[0] == '*' && urlSuffix[1] == '\0') {
// The special "*" URL means: an operation on the entire server. This works only for GET_PARAMETER and SET_PARAMETER:
if (strcmp(cmdName, "GET_PARAMETER") == 0) {
handleCmd_GET_PARAMETER((char const*)fRequestBuffer);
} else if (strcmp(cmdName, "SET_PARAMETER") == 0) {
handleCmd_SET_PARAMETER((char const*)fRequestBuffer);
} else {
handleCmd_notSupported();
}
} else if (strcmp(cmdName, "DESCRIBE") == 0) {
handleCmd_DESCRIBE(urlPreSuffix, urlSuffix, (char const*)fRequestBuffer);
} else if (strcmp(cmdName, "SETUP") == 0) {
Boolean areAuthenticated = True;
if (!requestIncludedSessionId) {
// No session id was present in the request. So create a new "RTSPClientSession" object
// for this request. Choose a random (unused) 32-bit integer for the session id
// (it will be encoded as a 8-digit hex number). (We avoid choosing session id 0,
// because that has a special use (by "OnDemandServerMediaSubsession").)
// But first, make sure that we're authenticated to perform this command:
char urlTotalSuffix[2*RTSP_PARAM_STRING_MAX];
// enough space for urlPreSuffix/urlSuffix'\0'
urlTotalSuffix[0] = '\0';
if (urlPreSuffix[0] != '\0') {
strcat(urlTotalSuffix, urlPreSuffix);
strcat(urlTotalSuffix, "/");
}
strcat(urlTotalSuffix, urlSuffix);
if (authenticationOK("SETUP", urlTotalSuffix, (char const*)fRequestBuffer)) {
u_int32_t sessionId;
do {
sessionId = (u_int32_t)our_random32();
sprintf(sessionIdStr, "%08X", sessionId);
} while (sessionId == 0 || fOurRTSPServer.fClientSessions->Lookup(sessionIdStr) != NULL);
clientSession = (RTSPClientSession*)fOurRTSPServer.createNewClientSession(sessionId);
fOurRTSPServer.fClientSessions->Add(sessionIdStr, clientSession);
} else {
areAuthenticated = False;
}
}
if (clientSession != NULL) {
clientSession->handleCmd_SETUP(this, urlPreSuffix, urlSuffix, (char const*)fRequestBuffer);
playAfterSetup = clientSession->fStreamAfterSETUP;
} else if (areAuthenticated) {
handleCmd_sessionNotFound();
}
} else if (strcmp(cmdName, "TEARDOWN") == 0
|| strcmp(cmdName, "PLAY") == 0
|| strcmp(cmdName, "PAUSE") == 0
|| strcmp(cmdName, "GET_PARAMETER") == 0
|| strcmp(cmdName, "SET_PARAMETER") == 0) {
if (clientSession != NULL) {
clientSession->handleCmd_withinSession(this, cmdName, urlPreSuffix, urlSuffix, (char const*)fRequestBuffer);
} else {
handleCmd_sessionNotFound();
}
} else if (strcmp(cmdName, "REGISTER") == 0) {
// Because - unlike other commands - an implementation of this command needs
// the entire URL, we re-parse the command to get it:
char* url = strDupSize((char*)fRequestBuffer);
if (sscanf((char*)fRequestBuffer, "%*s %s", url) == 1) {
// Check for special command-specific parameters in a "Transport:" header:
Boolean reuseConnection, deliverViaTCP;
char* proxyURLSuffix;
parseTransportHeaderForREGISTER((const char*)fRequestBuffer, reuseConnection, deliverViaTCP, proxyURLSuffix);
handleCmd_REGISTER(url, urlSuffix, (char const*)fRequestBuffer, reuseConnection, deliverViaTCP, proxyURLSuffix);
delete[] proxyURLSuffix;
} else {
handleCmd_bad();
}
delete[] url;
} else {
// The command is one that we don't handle:
handleCmd_notSupported();
}
} else {
#ifdef DEBUG
fprintf(stderr, "parseRTSPRequestString() failed; checking now for HTTP commands (for RTSP-over-HTTP tunneling)...\n");
#endif
// The request was not (valid) RTSP, but check for a special case: HTTP commands (for setting up RTSP-over-HTTP tunneling):
char sessionCookie[RTSP_PARAM_STRING_MAX];
char acceptStr[RTSP_PARAM_STRING_MAX];
*fLastCRLF = '\0'; // temporarily, for parsing
parseSucceeded = parseHTTPRequestString(cmdName, sizeof cmdName,
urlSuffix, sizeof urlPreSuffix,
sessionCookie, sizeof sessionCookie,
acceptStr, sizeof acceptStr);
*fLastCRLF = '\r';
if (parseSucceeded) {
#ifdef DEBUG
fprintf(stderr, "parseHTTPRequestString() succeeded, returning cmdName \"%s\", urlSuffix \"%s\", sessionCookie \"%s\", acceptStr \"%s\"\n", cmdName, urlSuffix, sessionCookie, acceptStr);
#endif
// Check that the HTTP command is valid for RTSP-over-HTTP tunneling: There must be a 'session cookie'.
Boolean isValidHTTPCmd = True;
if (strcmp(cmdName, "OPTIONS") == 0) {
handleHTTPCmd_OPTIONS();
} else if (sessionCookie[0] == '\0') {
// There was no "x-sessioncookie:" header. If there was an "Accept: application/x-rtsp-tunnelled" header,
// then this is a bad tunneling request. Otherwise, assume that it's an attempt to access the stream via HTTP.
if (strcmp(acceptStr, "application/x-rtsp-tunnelled") == 0) {
isValidHTTPCmd = False;
} else {
handleHTTPCmd_StreamingGET(urlSuffix, (char const*)fRequestBuffer);
}
} else if (strcmp(cmdName, "GET") == 0) {
handleHTTPCmd_TunnelingGET(sessionCookie);
} else if (strcmp(cmdName, "POST") == 0) {
// We might have received additional data following the HTTP "POST" command - i.e., the first Base64-encoded RTSP command.
// Check for this, and handle it if it exists:
unsigned char const* extraData = fLastCRLF+4;
unsigned extraDataSize = &fRequestBuffer[fRequestBytesAlreadySeen] - extraData;
if (handleHTTPCmd_TunnelingPOST(sessionCookie, extraData, extraDataSize)) {
// We don't respond to the "POST" command, and we go away:
fIsActive = False;
break;
}
} else {
isValidHTTPCmd = False;
}
if (!isValidHTTPCmd) {
handleHTTPCmd_notSupported();
}
} else {
#ifdef DEBUG
fprintf(stderr, "parseHTTPRequestString() failed!\n");
#endif
handleCmd_bad();
}
}
#ifdef DEBUG
fprintf(stderr, "sending response: %s", fResponseBuffer);
#endif
send(fClientOutputSocket, (char const*)fResponseBuffer, strlen((char*)fResponseBuffer), 0);
if (playAfterSetup) {
// The client has asked for streaming to commence now, rather than after a
// subsequent "PLAY" command. So, simulate the effect of a "PLAY" command:
clientSession->handleCmd_withinSession(this, "PLAY", urlPreSuffix, urlSuffix, (char const*)fRequestBuffer);
}
// Check whether there are extra bytes remaining in the buffer, after the end of the request (a rare case).
// If so, move them to the front of our buffer, and keep processing it, because it might be a following, pipelined request.
unsigned requestSize = (fLastCRLF+4-fRequestBuffer) + contentLength;
numBytesRemaining = fRequestBytesAlreadySeen - requestSize;
resetRequestBuffer(); // to prepare for any subsequent request
if (numBytesRemaining > 0) {
memmove(fRequestBuffer, &fRequestBuffer[requestSize], numBytesRemaining);
newBytesRead = numBytesRemaining;
}
} while (numBytesRemaining > 0);
--fRecursionCount;
if (!fIsActive) {
if (fRecursionCount > 0) closeSockets(); else delete this;
// Note: The "fRecursionCount" test is for a pathological situation where we reenter the event loop and get called recursively
// while handling a command (e.g., while handling a "DESCRIBE", to get a SDP description).
// In such a case we don't want to actually delete ourself until we leave the outermost call.
}
}
static Boolean parseAuthorizationHeader(char const* buf,
char const*& username,
char const*& realm,
char const*& nonce, char const*& uri,
char const*& response) {
// Initialize the result parameters to default values:
username = realm = nonce = uri = response = NULL;
// First, find "Authorization:"
while (1) {
if (*buf == '\0') return False; // not found
if (_strncasecmp(buf, "Authorization: Digest ", 22) == 0) break;
++buf;
}
// Then, run through each of the fields, looking for ones we handle:
char const* fields = buf + 22;
while (*fields == ' ') ++fields;
char* parameter = strDupSize(fields);
char* value = strDupSize(fields);
while (1) {
value[0] = '\0';
if (sscanf(fields, "%[^=]=\"%[^\"]\"", parameter, value) != 2 &&
sscanf(fields, "%[^=]=\"\"", parameter) != 1) {
break;
}
if (strcmp(parameter, "username") == 0) {
username = strDup(value);
} else if (strcmp(parameter, "realm") == 0) {
realm = strDup(value);
} else if (strcmp(parameter, "nonce") == 0) {
nonce = strDup(value);
} else if (strcmp(parameter, "uri") == 0) {
uri = strDup(value);
} else if (strcmp(parameter, "response") == 0) {
response = strDup(value);
}
fields += strlen(parameter) + 2 /*="*/ + strlen(value) + 1 /*"*/;
while (*fields == ',' || *fields == ' ') ++fields;
// skip over any separating ',' and ' ' chars
if (*fields == '\0' || *fields == '\r' || *fields == '\n') break;
}
delete[] parameter; delete[] value;
return True;
}
Boolean RTSPServer::RTSPClientConnection
::authenticationOK(char const* cmdName, char const* urlSuffix, char const* fullRequestStr) {
if (!fOurRTSPServer.specialClientAccessCheck(fClientInputSocket, fClientAddr, urlSuffix)) {
setRTSPResponse("401 Unauthorized");
return False;
}
// If we weren't set up with an authentication database, we're OK:
UserAuthenticationDatabase* authDB = fOurRTSPServer.getAuthenticationDatabaseForCommand(cmdName);
if (authDB == NULL) return True;
char const* username = NULL; char const* realm = NULL; char const* nonce = NULL;
char const* uri = NULL; char const* response = NULL;
Boolean success = False;
do {
// To authenticate, we first need to have a nonce set up
// from a previous attempt:
if (fCurrentAuthenticator.nonce() == NULL) break;
// Next, the request needs to contain an "Authorization:" header,
// containing a username, (our) realm, (our) nonce, uri,
// and response string:
if (!parseAuthorizationHeader(fullRequestStr,
username, realm, nonce, uri, response)
|| username == NULL
|| realm == NULL || strcmp(realm, fCurrentAuthenticator.realm()) != 0
|| nonce == NULL || strcmp(nonce, fCurrentAuthenticator.nonce()) != 0
|| uri == NULL || response == NULL) {
break;
}
// Next, the username has to be known to us:
char const* password = authDB->lookupPassword(username);
#ifdef DEBUG
fprintf(stderr, "lookupPassword(%s) returned password %s\n", username, password);
#endif
if (password == NULL) break;
fCurrentAuthenticator.setUsernameAndPassword(username, password, authDB->passwordsAreMD5());
// Finally, compute a digest response from the information that we have,
// and compare it to the one that we were given:
char const* ourResponse
= fCurrentAuthenticator.computeDigestResponse(cmdName, uri);
success = (strcmp(ourResponse, response) == 0);
fCurrentAuthenticator.reclaimDigestResponse(ourResponse);
} while (0);
delete[] (char*)realm; delete[] (char*)nonce;
delete[] (char*)uri; delete[] (char*)response;
if (success) {
// The user has been authenticated.
// Now allow subclasses a chance to validate the user against the IP address and/or URL suffix.
if (!fOurRTSPServer.specialClientUserAccessCheck(fClientInputSocket, fClientAddr, urlSuffix, username)) {
// Note: We don't return a "WWW-Authenticate" header here, because the user is valid,
// even though the server has decided that they should not have access.
setRTSPResponse("401 Unauthorized");
delete[] (char*)username;
return False;
}
}
delete[] (char*)username;
if (success) return True;
// If we get here, we failed to authenticate the user.
// Send back a "401 Unauthorized" response, with a new random nonce:
fCurrentAuthenticator.setRealmAndRandomNonce(authDB->realm());
snprintf((char*)fResponseBuffer, sizeof fResponseBuffer,
"RTSP/1.0 401 Unauthorized\r\n"
"CSeq: %s\r\n"
"%s"
"WWW-Authenticate: Digest realm=\"%s\", nonce=\"%s\"\r\n\r\n",
fCurrentCSeq,
dateHeader(),
fCurrentAuthenticator.realm(), fCurrentAuthenticator.nonce());
return False;
}
void RTSPServer::RTSPClientConnection
::setRTSPResponse(char const* responseStr) {
snprintf((char*)fResponseBuffer, sizeof fResponseBuffer,
"RTSP/1.0 %s\r\n"
"CSeq: %s\r\n"
"%s\r\n",
responseStr,
fCurrentCSeq,
dateHeader());
}
void RTSPServer::RTSPClientConnection
::setRTSPResponse(char const* responseStr, u_int32_t sessionId) {
snprintf((char*)fResponseBuffer, sizeof fResponseBuffer,
"RTSP/1.0 %s\r\n"
"CSeq: %s\r\n"
"%s"
"Session: %08X\r\n\r\n",
responseStr,
fCurrentCSeq,
dateHeader(),
sessionId);
}
void RTSPServer::RTSPClientConnection
::setRTSPResponse(char const* responseStr, char const* contentStr) {
if (contentStr == NULL) contentStr = "";
unsigned const contentLen = strlen(contentStr);
snprintf((char*)fResponseBuffer, sizeof fResponseBuffer,
"RTSP/1.0 %s\r\n"
"CSeq: %s\r\n"
"%s"
"Content-Length: %d\r\n\r\n"
"%s",
responseStr,
fCurrentCSeq,
dateHeader(),
contentLen,
contentStr);
}
void RTSPServer::RTSPClientConnection
::setRTSPResponse(char const* responseStr, u_int32_t sessionId, char const* contentStr) {
if (contentStr == NULL) contentStr = "";
unsigned const contentLen = strlen(contentStr);
snprintf((char*)fResponseBuffer, sizeof fResponseBuffer,
"RTSP/1.0 %s\r\n"
"CSeq: %s\r\n"
"%s"
"Session: %08X\r\n"
"Content-Length: %d\r\n\r\n"
"%s",
responseStr,
fCurrentCSeq,
dateHeader(),
sessionId,
contentLen,
contentStr);
}
void RTSPServer::RTSPClientConnection
::changeClientInputSocket(int newSocketNum, unsigned char const* extraData, unsigned extraDataSize) {
envir().taskScheduler().disableBackgroundHandling(fClientInputSocket);
fClientInputSocket = newSocketNum;
envir().taskScheduler().setBackgroundHandling(fClientInputSocket, SOCKET_READABLE|SOCKET_EXCEPTION,
incomingRequestHandler, this);
// Also write any extra data to our buffer, and handle it:
if (extraDataSize > 0 && extraDataSize <= fRequestBufferBytesLeft/*sanity check; should always be true*/) {
unsigned char* ptr = &fRequestBuffer[fRequestBytesAlreadySeen];
for (unsigned i = 0; i < extraDataSize; ++i) {
ptr[i] = extraData[i];
}
handleRequestBytes(extraDataSize);
}
}
void RTSPServer::RTSPClientConnection::continueHandlingREGISTER(ParamsForREGISTER* params) {
params->fOurConnection->continueHandlingREGISTER1(params);
}
void RTSPServer::RTSPClientConnection::continueHandlingREGISTER1(ParamsForREGISTER* params) {
// Reuse our socket if requested:
int socketNumToBackEndServer = params->fReuseConnection ? fClientOutputSocket : -1;
RTSPServer* ourServer = &fOurRTSPServer; // copy the pointer now, in case we "delete this" below
if (socketNumToBackEndServer >= 0) {
// Because our socket will no longer be used by the server to handle incoming requests, we can now delete this
// "RTSPClientConnection" object. We do this now, in case the "implementCmd_REGISTER()" call below would also end up
// deleting this.
fClientInputSocket = fClientOutputSocket = -1; // so the socket doesn't get closed when we get deleted
delete this;
}
ourServer->implementCmd_REGISTER(params->fURL, params->fURLSuffix, socketNumToBackEndServer,
params->fDeliverViaTCP, params->fProxyURLSuffix);
delete params;
}
////////// RTSPServer::RTSPClientSession implementation //////////
RTSPServer::RTSPClientSession
::RTSPClientSession(RTSPServer& ourServer, u_int32_t sessionId)
: GenericMediaServer::ClientSession(ourServer, sessionId),
fOurRTSPServer(ourServer), fIsMulticast(False), fStreamAfterSETUP(False),
fTCPStreamIdCount(0), fNumStreamStates(0), fStreamStates(NULL) {
}
RTSPServer::RTSPClientSession::~RTSPClientSession() {
reclaimStreamStates();
}
void RTSPServer::RTSPClientSession::deleteStreamByTrack(unsigned trackNum) {
if (trackNum >= fNumStreamStates) return; // sanity check; shouldn't happen
if (fStreamStates[trackNum].subsession != NULL) {
fStreamStates[trackNum].subsession->deleteStream(fOurSessionId, fStreamStates[trackNum].streamToken);
fStreamStates[trackNum].subsession = NULL;
}
// Optimization: If all subsessions have now been deleted, then we can delete ourself now:
Boolean noSubsessionsRemain = True;
for (unsigned i = 0; i < fNumStreamStates; ++i) {
if (fStreamStates[i].subsession != NULL) {
noSubsessionsRemain = False;
break;
}
}
if (noSubsessionsRemain) delete this;
}
void RTSPServer::RTSPClientSession::reclaimStreamStates() {
for (unsigned i = 0; i < fNumStreamStates; ++i) {
if (fStreamStates[i].subsession != NULL) {
fOurRTSPServer.unnoteTCPStreamingOnSocket(fStreamStates[i].tcpSocketNum, this, i);
fStreamStates[i].subsession->deleteStream(fOurSessionId, fStreamStates[i].streamToken);
}
}
delete[] fStreamStates; fStreamStates = NULL;
fNumStreamStates = 0;
}
typedef enum StreamingMode {
RTP_UDP,
RTP_TCP,
RAW_UDP
} StreamingMode;
static void parseTransportHeader(char const* buf,
StreamingMode& streamingMode,
char*& streamingModeString,
char*& destinationAddressStr,
u_int8_t& destinationTTL,
portNumBits& clientRTPPortNum, // if UDP
portNumBits& clientRTCPPortNum, // if UDP
unsigned char& rtpChannelId, // if TCP
unsigned char& rtcpChannelId // if TCP
) {
// Initialize the result parameters to default values:
streamingMode = RTP_UDP;
streamingModeString = NULL;
destinationAddressStr = NULL;
destinationTTL = 255;
clientRTPPortNum = 0;
clientRTCPPortNum = 1;
rtpChannelId = rtcpChannelId = 0xFF;
portNumBits p1, p2;
unsigned ttl, rtpCid, rtcpCid;
// First, find "Transport:"
while (1) {
if (*buf == '\0') return; // not found
if (*buf == '\r' && *(buf+1) == '\n' && *(buf+2) == '\r') return; // end of the headers => not found
if (_strncasecmp(buf, "Transport:", 10) == 0) break;
++buf;
}
// Then, run through each of the fields, looking for ones we handle:
char const* fields = buf + 10;
while (*fields == ' ') ++fields;
char* field = strDupSize(fields);
while (sscanf(fields, "%[^;\r\n]", field) == 1) {
if (strcmp(field, "RTP/AVP/TCP") == 0) {
streamingMode = RTP_TCP;
} else if (strcmp(field, "RAW/RAW/UDP") == 0 ||
strcmp(field, "MP2T/H2221/UDP") == 0) {
streamingMode = RAW_UDP;
streamingModeString = strDup(field);
} else if (_strncasecmp(field, "destination=", 12) == 0) {
delete[] destinationAddressStr;
destinationAddressStr = strDup(field+12);
} else if (sscanf(field, "ttl%u", &ttl) == 1) {
destinationTTL = (u_int8_t)ttl;
} else if (sscanf(field, "client_port=%hu-%hu", &p1, &p2) == 2) {
clientRTPPortNum = p1;
clientRTCPPortNum = streamingMode == RAW_UDP ? 0 : p2; // ignore the second port number if the client asked for raw UDP
} else if (sscanf(field, "client_port=%hu", &p1) == 1) {
clientRTPPortNum = p1;
clientRTCPPortNum = streamingMode == RAW_UDP ? 0 : p1 + 1;
} else if (sscanf(field, "interleaved=%u-%u", &rtpCid, &rtcpCid) == 2) {
rtpChannelId = (unsigned char)rtpCid;
rtcpChannelId = (unsigned char)rtcpCid;
}
fields += strlen(field);
while (*fields == ';' || *fields == ' ' || *fields == '\t') ++fields; // skip over separating ';' chars or whitespace
if (*fields == '\0' || *fields == '\r' || *fields == '\n') break;
}
delete[] field;
}
static Boolean parsePlayNowHeader(char const* buf) {
// Find "x-playNow:" header, if present
while (1) {
if (*buf == '\0') return False; // not found
if (_strncasecmp(buf, "x-playNow:", 10) == 0) break;
++buf;
}
return True;
}
void RTSPServer::RTSPClientSession
::handleCmd_SETUP(RTSPServer::RTSPClientConnection* ourClientConnection,
char const* urlPreSuffix, char const* urlSuffix, char const* fullRequestStr) {
// Normally, "urlPreSuffix" should be the session (stream) name, and "urlSuffix" should be the subsession (track) name.
// However (being "liberal in what we accept"), we also handle 'aggregate' SETUP requests (i.e., without a track name),
// in the special case where we have only a single track. I.e., in this case, we also handle:
// "urlPreSuffix" is empty and "urlSuffix" is the session (stream) name, or
// "urlPreSuffix" concatenated with "urlSuffix" (with "/" inbetween) is the session (stream) name.
char const* streamName = urlPreSuffix; // in the normal case
char const* trackId = urlSuffix; // in the normal case
char* concatenatedStreamName = NULL; // in the normal case
do {
// First, make sure the specified stream name exists:
ServerMediaSession* sms
= fOurServer.lookupServerMediaSession(streamName, fOurServerMediaSession == NULL);
if (sms == NULL) {
// Check for the special case (noted above), before we give up:
if (urlPreSuffix[0] == '\0') {
streamName = urlSuffix;
} else {
concatenatedStreamName = new char[strlen(urlPreSuffix) + strlen(urlSuffix) + 2]; // allow for the "/" and the trailing '\0'
sprintf(concatenatedStreamName, "%s/%s", urlPreSuffix, urlSuffix);
streamName = concatenatedStreamName;
}
trackId = NULL;
// Check again:
sms = fOurServer.lookupServerMediaSession(streamName, fOurServerMediaSession == NULL);
}
if (sms == NULL) {
if (fOurServerMediaSession == NULL) {
// The client asked for a stream that doesn't exist (and this session descriptor has not been used before):
ourClientConnection->handleCmd_notFound();
} else {
// The client asked for a stream that doesn't exist, but using a stream id for a stream that does exist. Bad request:
ourClientConnection->handleCmd_bad();
}
break;
} else {
if (fOurServerMediaSession == NULL) {
// We're accessing the "ServerMediaSession" for the first time.
fOurServerMediaSession = sms;
fOurServerMediaSession->incrementReferenceCount();
} else if (sms != fOurServerMediaSession) {
// The client asked for a stream that's different from the one originally requested for this stream id. Bad request:
ourClientConnection->handleCmd_bad();
break;
}
}
if (fStreamStates == NULL) {
// This is the first "SETUP" for this session. Set up our array of states for all of this session's subsessions (tracks):
ServerMediaSubsessionIterator iter(*fOurServerMediaSession);
for (fNumStreamStates = 0; iter.next() != NULL; ++fNumStreamStates) {} // begin by counting the number of subsessions (tracks)
fStreamStates = new struct streamState[fNumStreamStates];
iter.reset();
ServerMediaSubsession* subsession;
for (unsigned i = 0; i < fNumStreamStates; ++i) {
subsession = iter.next();
fStreamStates[i].subsession = subsession;
fStreamStates[i].tcpSocketNum = -1; // for now; may get set for RTP-over-TCP streaming
fStreamStates[i].streamToken = NULL; // for now; it may be changed by the "getStreamParameters()" call that comes later
}
}
// Look up information for the specified subsession (track):
ServerMediaSubsession* subsession = NULL;
unsigned trackNum;
if (trackId != NULL && trackId[0] != '\0') { // normal case
for (trackNum = 0; trackNum < fNumStreamStates; ++trackNum) {
subsession = fStreamStates[trackNum].subsession;
if (subsession != NULL && strcmp(trackId, subsession->trackId()) == 0) break;
}
if (trackNum >= fNumStreamStates) {
// The specified track id doesn't exist, so this request fails:
ourClientConnection->handleCmd_notFound();
break;
}
} else {
// Weird case: there was no track id in the URL.
// This works only if we have only one subsession:
if (fNumStreamStates != 1 || fStreamStates[0].subsession == NULL) {
ourClientConnection->handleCmd_bad();
break;
}
trackNum = 0;
subsession = fStreamStates[trackNum].subsession;
}
// ASSERT: subsession != NULL
void*& token = fStreamStates[trackNum].streamToken; // alias
if (token != NULL) {
// We already handled a "SETUP" for this track (to the same client),
// so stop any existing streaming of it, before we set it up again:
subsession->pauseStream(fOurSessionId, token);
fOurRTSPServer.unnoteTCPStreamingOnSocket(fStreamStates[trackNum].tcpSocketNum, this, trackNum);
subsession->deleteStream(fOurSessionId, token);
}
// Look for a "Transport:" header in the request string, to extract client parameters:
StreamingMode streamingMode;
char* streamingModeString = NULL; // set when RAW_UDP streaming is specified
char* clientsDestinationAddressStr;
u_int8_t clientsDestinationTTL;
portNumBits clientRTPPortNum, clientRTCPPortNum;
unsigned char rtpChannelId, rtcpChannelId;
parseTransportHeader(fullRequestStr, streamingMode, streamingModeString,
clientsDestinationAddressStr, clientsDestinationTTL,
clientRTPPortNum, clientRTCPPortNum,
rtpChannelId, rtcpChannelId);
if ((streamingMode == RTP_TCP && rtpChannelId == 0xFF) ||
(streamingMode != RTP_TCP && ourClientConnection->fClientOutputSocket != ourClientConnection->fClientInputSocket)) {
// An anomolous situation, caused by a buggy client. Either:
// 1/ TCP streaming was requested, but with no "interleaving=" fields. (QuickTime Player sometimes does this.), or
// 2/ TCP streaming was not requested, but we're doing RTSP-over-HTTP tunneling (which implies TCP streaming).
// In either case, we assume TCP streaming, and set the RTP and RTCP channel ids to proper values:
streamingMode = RTP_TCP;
rtpChannelId = fTCPStreamIdCount; rtcpChannelId = fTCPStreamIdCount+1;
}
if (streamingMode == RTP_TCP) fTCPStreamIdCount += 2;
Port clientRTPPort(clientRTPPortNum);
Port clientRTCPPort(clientRTCPPortNum);
// Next, check whether a "Range:" or "x-playNow:" header is present in the request.
// This isn't legal, but some clients do this to combine "SETUP" and "PLAY":
double rangeStart = 0.0, rangeEnd = 0.0;
char* absStart = NULL; char* absEnd = NULL;
Boolean startTimeIsNow;
if (parseRangeHeader(fullRequestStr, rangeStart, rangeEnd, absStart, absEnd, startTimeIsNow)) {
delete[] absStart; delete[] absEnd;
fStreamAfterSETUP = True;
} else if (parsePlayNowHeader(fullRequestStr)) {
fStreamAfterSETUP = True;
} else {
fStreamAfterSETUP = False;
}
// Then, get server parameters from the 'subsession':
if (streamingMode == RTP_TCP) {
// Note that we'll be streaming over the RTSP TCP connection:
fStreamStates[trackNum].tcpSocketNum = ourClientConnection->fClientOutputSocket;
fOurRTSPServer.noteTCPStreamingOnSocket(fStreamStates[trackNum].tcpSocketNum, this, trackNum);
}
netAddressBits destinationAddress = 0;
u_int8_t destinationTTL = 255;
#ifdef RTSP_ALLOW_CLIENT_DESTINATION_SETTING
if (clientsDestinationAddressStr != NULL) {
// Use the client-provided "destination" address.
// Note: This potentially allows the server to be used in denial-of-service
// attacks, so don't enable this code unless you're sure that clients are
// trusted.
destinationAddress = our_inet_addr(clientsDestinationAddressStr);
}
// Also use the client-provided TTL.
destinationTTL = clientsDestinationTTL;
#endif
delete[] clientsDestinationAddressStr;
Port serverRTPPort(0);
Port serverRTCPPort(0);
// Make sure that we transmit on the same interface that's used by the client (in case we're a multi-homed server):
struct sockaddr_in sourceAddr; SOCKLEN_T namelen = sizeof sourceAddr;
getsockname(ourClientConnection->fClientInputSocket, (struct sockaddr*)&sourceAddr, &namelen);
netAddressBits origSendingInterfaceAddr = SendingInterfaceAddr;
netAddressBits origReceivingInterfaceAddr = ReceivingInterfaceAddr;
// NOTE: The following might not work properly, so we ifdef it out for now:
#ifdef HACK_FOR_MULTIHOMED_SERVERS
ReceivingInterfaceAddr = SendingInterfaceAddr = sourceAddr.sin_addr.s_addr;
#endif
subsession->getStreamParameters(fOurSessionId, ourClientConnection->fClientAddr.sin_addr.s_addr,
clientRTPPort, clientRTCPPort,
fStreamStates[trackNum].tcpSocketNum, rtpChannelId, rtcpChannelId,
destinationAddress, destinationTTL, fIsMulticast,
serverRTPPort, serverRTCPPort,
fStreamStates[trackNum].streamToken);
SendingInterfaceAddr = origSendingInterfaceAddr;
ReceivingInterfaceAddr = origReceivingInterfaceAddr;
AddressString destAddrStr(destinationAddress);
AddressString sourceAddrStr(sourceAddr);
char timeoutParameterString[100];
if (fOurRTSPServer.fReclamationSeconds > 0) {
sprintf(timeoutParameterString, ";timeout=%u", fOurRTSPServer.fReclamationSeconds);
} else {
timeoutParameterString[0] = '\0';
}
if (fIsMulticast) {
switch (streamingMode) {
case RTP_UDP: {
snprintf((char*)ourClientConnection->fResponseBuffer, sizeof ourClientConnection->fResponseBuffer,
"RTSP/1.0 200 OK\r\n"
"CSeq: %s\r\n"
"%s"
"Transport: RTP/AVP;multicast;destination=%s;source=%s;port=%d-%d;ttl=%d\r\n"
"Session: %08X%s\r\n\r\n",
ourClientConnection->fCurrentCSeq,
dateHeader(),
destAddrStr.val(), sourceAddrStr.val(), ntohs(serverRTPPort.num()), ntohs(serverRTCPPort.num()), destinationTTL,
fOurSessionId, timeoutParameterString);
break;
}
case RTP_TCP: {
// multicast streams can't be sent via TCP
ourClientConnection->handleCmd_unsupportedTransport();
break;
}
case RAW_UDP: {
snprintf((char*)ourClientConnection->fResponseBuffer, sizeof ourClientConnection->fResponseBuffer,
"RTSP/1.0 200 OK\r\n"
"CSeq: %s\r\n"
"%s"
"Transport: %s;multicast;destination=%s;source=%s;port=%d;ttl=%d\r\n"
"Session: %08X%s\r\n\r\n",
ourClientConnection->fCurrentCSeq,
dateHeader(),
streamingModeString, destAddrStr.val(), sourceAddrStr.val(), ntohs(serverRTPPort.num()), destinationTTL,
fOurSessionId, timeoutParameterString);
break;
}
}
} else {
switch (streamingMode) {
case RTP_UDP: {
snprintf((char*)ourClientConnection->fResponseBuffer, sizeof ourClientConnection->fResponseBuffer,
"RTSP/1.0 200 OK\r\n"
"CSeq: %s\r\n"
"%s"
"Transport: RTP/AVP;unicast;destination=%s;source=%s;client_port=%d-%d;server_port=%d-%d\r\n"
"Session: %08X%s\r\n\r\n",
ourClientConnection->fCurrentCSeq,
dateHeader(),
destAddrStr.val(), sourceAddrStr.val(), ntohs(clientRTPPort.num()), ntohs(clientRTCPPort.num()), ntohs(serverRTPPort.num()), ntohs(serverRTCPPort.num()),
fOurSessionId, timeoutParameterString);
break;
}
case RTP_TCP: {
if (!fOurRTSPServer.fAllowStreamingRTPOverTCP) {
ourClientConnection->handleCmd_unsupportedTransport();
} else {
snprintf((char*)ourClientConnection->fResponseBuffer, sizeof ourClientConnection->fResponseBuffer,
"RTSP/1.0 200 OK\r\n"
"CSeq: %s\r\n"
"%s"
"Transport: RTP/AVP/TCP;unicast;destination=%s;source=%s;interleaved=%d-%d\r\n"
"Session: %08X%s\r\n\r\n",
ourClientConnection->fCurrentCSeq,
dateHeader(),
destAddrStr.val(), sourceAddrStr.val(), rtpChannelId, rtcpChannelId,
fOurSessionId, timeoutParameterString);
}
break;
}
case RAW_UDP: {
snprintf((char*)ourClientConnection->fResponseBuffer, sizeof ourClientConnection->fResponseBuffer,
"RTSP/1.0 200 OK\r\n"
"CSeq: %s\r\n"
"%s"
"Transport: %s;unicast;destination=%s;source=%s;client_port=%d;server_port=%d\r\n"
"Session: %08X%s\r\n\r\n",
ourClientConnection->fCurrentCSeq,
dateHeader(),
streamingModeString, destAddrStr.val(), sourceAddrStr.val(), ntohs(clientRTPPort.num()), ntohs(serverRTPPort.num()),
fOurSessionId, timeoutParameterString);
break;
}
}
}
delete[] streamingModeString;
} while (0);
delete[] concatenatedStreamName;
}
void RTSPServer::RTSPClientSession
::handleCmd_withinSession(RTSPServer::RTSPClientConnection* ourClientConnection,
char const* cmdName,
char const* urlPreSuffix, char const* urlSuffix,
char const* fullRequestStr) {
// This will either be:
// - a non-aggregated operation, if "urlPreSuffix" is the session (stream)
// name and "urlSuffix" is the subsession (track) name, or
// - an aggregated operation, if "urlSuffix" is the session (stream) name,
// or "urlPreSuffix" is the session (stream) name, and "urlSuffix" is empty,
// or "urlPreSuffix" and "urlSuffix" are both nonempty, but when concatenated, (with "/") form the session (stream) name.
// Begin by figuring out which of these it is:
ServerMediaSubsession* subsession;
if (fOurServerMediaSession == NULL) { // There wasn't a previous SETUP!
ourClientConnection->handleCmd_notSupported();
return;
} else if (urlSuffix[0] != '\0' && strcmp(fOurServerMediaSession->streamName(), urlPreSuffix) == 0) {
// Non-aggregated operation.
// Look up the media subsession whose track id is "urlSuffix":
ServerMediaSubsessionIterator iter(*fOurServerMediaSession);
while ((subsession = iter.next()) != NULL) {
if (strcmp(subsession->trackId(), urlSuffix) == 0) break; // success
}
if (subsession == NULL) { // no such track!
ourClientConnection->handleCmd_notFound();
return;
}
} else if (strcmp(fOurServerMediaSession->streamName(), urlSuffix) == 0 ||
(urlSuffix[0] == '\0' && strcmp(fOurServerMediaSession->streamName(), urlPreSuffix) == 0)) {
// Aggregated operation
subsession = NULL;
} else if (urlPreSuffix[0] != '\0' && urlSuffix[0] != '\0') {
// Aggregated operation, if <urlPreSuffix>/<urlSuffix> is the session (stream) name:
unsigned const urlPreSuffixLen = strlen(urlPreSuffix);
if (strncmp(fOurServerMediaSession->streamName(), urlPreSuffix, urlPreSuffixLen) == 0 &&
fOurServerMediaSession->streamName()[urlPreSuffixLen] == '/' &&
strcmp(&(fOurServerMediaSession->streamName())[urlPreSuffixLen+1], urlSuffix) == 0) {
subsession = NULL;
} else {
ourClientConnection->handleCmd_notFound();
return;
}
} else { // the request doesn't match a known stream and/or track at all!
ourClientConnection->handleCmd_notFound();
return;
}
if (strcmp(cmdName, "TEARDOWN") == 0) {
handleCmd_TEARDOWN(ourClientConnection, subsession);
} else if (strcmp(cmdName, "PLAY") == 0) {
handleCmd_PLAY(ourClientConnection, subsession, fullRequestStr);
} else if (strcmp(cmdName, "PAUSE") == 0) {
handleCmd_PAUSE(ourClientConnection, subsession);
} else if (strcmp(cmdName, "GET_PARAMETER") == 0) {
handleCmd_GET_PARAMETER(ourClientConnection, subsession, fullRequestStr);
} else if (strcmp(cmdName, "SET_PARAMETER") == 0) {
handleCmd_SET_PARAMETER(ourClientConnection, subsession, fullRequestStr);
}
}
void RTSPServer::RTSPClientSession
::handleCmd_TEARDOWN(RTSPServer::RTSPClientConnection* ourClientConnection,
ServerMediaSubsession* subsession) {
unsigned i;
for (i = 0; i < fNumStreamStates; ++i) {
if (subsession == NULL /* means: aggregated operation */
|| subsession == fStreamStates[i].subsession) {
if (fStreamStates[i].subsession != NULL) {
fOurRTSPServer.unnoteTCPStreamingOnSocket(fStreamStates[i].tcpSocketNum, this, i);
fStreamStates[i].subsession->deleteStream(fOurSessionId, fStreamStates[i].streamToken);
fStreamStates[i].subsession = NULL;
}
}
}
setRTSPResponse(ourClientConnection, "200 OK");
// Optimization: If all subsessions have now been torn down, then we know that we can reclaim our object now.
// (Without this optimization, however, this object would still get reclaimed later, as a result of a 'liveness' timeout.)
Boolean noSubsessionsRemain = True;
for (i = 0; i < fNumStreamStates; ++i) {
if (fStreamStates[i].subsession != NULL) {
noSubsessionsRemain = False;
break;
}
}
if (noSubsessionsRemain) delete this;
}
void RTSPServer::RTSPClientSession
::handleCmd_PLAY(RTSPServer::RTSPClientConnection* ourClientConnection,
ServerMediaSubsession* subsession, char const* fullRequestStr) {
char* rtspURL
= fOurRTSPServer.rtspURL(fOurServerMediaSession, ourClientConnection->fClientInputSocket);
unsigned rtspURLSize = strlen(rtspURL);
// Parse the client's "Scale:" header, if any:
float scale;
Boolean sawScaleHeader = parseScaleHeader(fullRequestStr, scale);
// Try to set the stream's scale factor to this value:
if (subsession == NULL /*aggregate op*/) {
fOurServerMediaSession->testScaleFactor(scale);
} else {
subsession->testScaleFactor(scale);
}
char buf[100];
char* scaleHeader;
if (!sawScaleHeader) {
buf[0] = '\0'; // Because we didn't see a Scale: header, don't send one back
} else {
sprintf(buf, "Scale: %f\r\n", scale);
}
scaleHeader = strDup(buf);
// Parse the client's "Range:" header, if any:
float duration = 0.0;
double rangeStart = 0.0, rangeEnd = 0.0;
char* absStart = NULL; char* absEnd = NULL;
Boolean startTimeIsNow;
Boolean sawRangeHeader
= parseRangeHeader(fullRequestStr, rangeStart, rangeEnd, absStart, absEnd, startTimeIsNow);
if (sawRangeHeader && absStart == NULL/*not seeking by 'absolute' time*/) {
// Use this information, plus the stream's duration (if known), to create our own "Range:" header, for the response:
duration = subsession == NULL /*aggregate op*/
? fOurServerMediaSession->duration() : subsession->duration();
if (duration < 0.0) {
// We're an aggregate PLAY, but the subsessions have different durations.
// Use the largest of these durations in our header
duration = -duration;
}
// Make sure that "rangeStart" and "rangeEnd" (from the client's "Range:" header)
// have sane values, before we send back our own "Range:" header in our response:
if (rangeStart < 0.0) rangeStart = 0.0;
else if (rangeStart > duration) rangeStart = duration;
if (rangeEnd < 0.0) rangeEnd = 0.0;
else if (rangeEnd > duration) rangeEnd = duration;
if ((scale > 0.0 && rangeStart > rangeEnd && rangeEnd > 0.0) ||
(scale < 0.0 && rangeStart < rangeEnd)) {
// "rangeStart" and "rangeEnd" were the wrong way around; swap them:
double tmp = rangeStart;
rangeStart = rangeEnd;
rangeEnd = tmp;
}
}
// Create a "RTP-Info:" line. It will get filled in from each subsession's state:
char const* rtpInfoFmt =
"%s" // "RTP-Info:", plus any preceding rtpInfo items
"%s" // comma separator, if needed
"url=%s/%s"
";seq=%d"
";rtptime=%u"
;
unsigned rtpInfoFmtSize = strlen(rtpInfoFmt);
char* rtpInfo = strDup("RTP-Info: ");
unsigned i, numRTPInfoItems = 0;
// Do any required seeking/scaling on each subsession, before starting streaming.
// (However, we don't do this if the "PLAY" request was for just a single subsession
// of a multiple-subsession stream; for such streams, seeking/scaling can be done
// only with an aggregate "PLAY".)
for (i = 0; i < fNumStreamStates; ++i) {
if (subsession == NULL /* means: aggregated operation */ || fNumStreamStates == 1) {
if (fStreamStates[i].subsession != NULL) {
if (sawScaleHeader) {
fStreamStates[i].subsession->setStreamScale(fOurSessionId, fStreamStates[i].streamToken, scale);
}
if (absStart != NULL) {
// Special case handling for seeking by 'absolute' time:
fStreamStates[i].subsession->seekStream(fOurSessionId, fStreamStates[i].streamToken, absStart, absEnd);
} else {
// Seeking by relative (NPT) time:
u_int64_t numBytes;
if (!sawRangeHeader || startTimeIsNow) {
// We're resuming streaming without seeking, so we just do a 'null' seek
// (to get our NPT, and to specify when to end streaming):
fStreamStates[i].subsession->nullSeekStream(fOurSessionId, fStreamStates[i].streamToken,
rangeEnd, numBytes);
} else {
// We do a real 'seek':
double streamDuration = 0.0; // by default; means: stream until the end of the media
if (rangeEnd > 0.0 && (rangeEnd+0.001) < duration) {
// the 0.001 is because we limited the values to 3 decimal places
// We want the stream to end early. Set the duration we want:
streamDuration = rangeEnd - rangeStart;
if (streamDuration < 0.0) streamDuration = -streamDuration;
// should happen only if scale < 0.0
}
fStreamStates[i].subsession->seekStream(fOurSessionId, fStreamStates[i].streamToken,
rangeStart, streamDuration, numBytes);
}
}
}
}
}
// Create the "Range:" header that we'll send back in our response.
// (Note that we do this after seeking, in case the seeking operation changed the range start time.)
if (absStart != NULL) {
// We're seeking by 'absolute' time:
if (absEnd == NULL) {
sprintf(buf, "Range: clock=%s-\r\n", absStart);
} else {
sprintf(buf, "Range: clock=%s-%s\r\n", absStart, absEnd);
}
delete[] absStart; delete[] absEnd;
} else {
// We're seeking by relative (NPT) time:
if (!sawRangeHeader || startTimeIsNow) {
// We didn't seek, so in our response, begin the range with the current NPT (normal play time):
float curNPT = 0.0;
for (i = 0; i < fNumStreamStates; ++i) {
if (subsession == NULL /* means: aggregated operation */
|| subsession == fStreamStates[i].subsession) {
if (fStreamStates[i].subsession == NULL) continue;
float npt = fStreamStates[i].subsession->getCurrentNPT(fStreamStates[i].streamToken);
if (npt > curNPT) curNPT = npt;
// Note: If this is an aggregate "PLAY" on a multi-subsession stream,
// then it's conceivable that the NPTs of each subsession may differ
// (if there has been a previous seek on just one subsession).
// In this (unusual) case, we just return the largest NPT; I hope that turns out OK...
}
}
rangeStart = curNPT;
}
if (rangeEnd == 0.0 && scale >= 0.0) {
sprintf(buf, "Range: npt=%.3f-\r\n", rangeStart);
} else {
sprintf(buf, "Range: npt=%.3f-%.3f\r\n", rangeStart, rangeEnd);
}
}
char* rangeHeader = strDup(buf);
// Now, start streaming:
for (i = 0; i < fNumStreamStates; ++i) {
if (subsession == NULL /* means: aggregated operation */
|| subsession == fStreamStates[i].subsession) {
unsigned short rtpSeqNum = 0;
unsigned rtpTimestamp = 0;
if (fStreamStates[i].subsession == NULL) continue;
fStreamStates[i].subsession->startStream(fOurSessionId,
fStreamStates[i].streamToken,
(TaskFunc*)noteClientLiveness, this,
rtpSeqNum, rtpTimestamp,
RTSPServer::RTSPClientConnection::handleAlternativeRequestByte, ourClientConnection);
const char *urlSuffix = fStreamStates[i].subsession->trackId();
char* prevRTPInfo = rtpInfo;
unsigned rtpInfoSize = rtpInfoFmtSize
+ strlen(prevRTPInfo)
+ 1
+ rtspURLSize + strlen(urlSuffix)
+ 5 /*max unsigned short len*/
+ 10 /*max unsigned (32-bit) len*/
+ 2 /*allows for trailing \r\n at final end of string*/;
rtpInfo = new char[rtpInfoSize];
sprintf(rtpInfo, rtpInfoFmt,
prevRTPInfo,
numRTPInfoItems++ == 0 ? "" : ",",
rtspURL, urlSuffix,
rtpSeqNum,
rtpTimestamp
);
delete[] prevRTPInfo;
}
}
if (numRTPInfoItems == 0) {
rtpInfo[0] = '\0';
} else {
unsigned rtpInfoLen = strlen(rtpInfo);
rtpInfo[rtpInfoLen] = '\r';
rtpInfo[rtpInfoLen+1] = '\n';
rtpInfo[rtpInfoLen+2] = '\0';
}
// Fill in the response:
snprintf((char*)ourClientConnection->fResponseBuffer, sizeof ourClientConnection->fResponseBuffer,
"RTSP/1.0 200 OK\r\n"
"CSeq: %s\r\n"
"%s"
"%s"
"%s"
"Session: %08X\r\n"
"%s\r\n",
ourClientConnection->fCurrentCSeq,
dateHeader(),
scaleHeader,
rangeHeader,
fOurSessionId,
rtpInfo);
delete[] rtpInfo; delete[] rangeHeader;
delete[] scaleHeader; delete[] rtspURL;
}
void RTSPServer::RTSPClientSession
::handleCmd_PAUSE(RTSPServer::RTSPClientConnection* ourClientConnection,
ServerMediaSubsession* subsession) {
for (unsigned i = 0; i < fNumStreamStates; ++i) {
if (subsession == NULL /* means: aggregated operation */
|| subsession == fStreamStates[i].subsession) {
if (fStreamStates[i].subsession != NULL) {
fStreamStates[i].subsession->pauseStream(fOurSessionId, fStreamStates[i].streamToken);
}
}
}
setRTSPResponse(ourClientConnection, "200 OK", fOurSessionId);
}
void RTSPServer::RTSPClientSession
::handleCmd_GET_PARAMETER(RTSPServer::RTSPClientConnection* ourClientConnection,
ServerMediaSubsession* /*subsession*/, char const* /*fullRequestStr*/) {
// By default, we implement "GET_PARAMETER" just as a 'keep alive', and send back a dummy response.
// (If you want to handle "GET_PARAMETER" properly, you can do so by defining a subclass of "RTSPServer"
// and "RTSPServer::RTSPClientSession", and then reimplement this virtual function in your subclass.)
setRTSPResponse(ourClientConnection, "200 OK", fOurSessionId, LIVEMEDIA_LIBRARY_VERSION_STRING);
}
void RTSPServer::RTSPClientSession
::handleCmd_SET_PARAMETER(RTSPServer::RTSPClientConnection* ourClientConnection,
ServerMediaSubsession* /*subsession*/, char const* /*fullRequestStr*/) {
// By default, we implement "SET_PARAMETER" just as a 'keep alive', and send back an empty response.
// (If you want to handle "SET_PARAMETER" properly, you can do so by defining a subclass of "RTSPServer"
// and "RTSPServer::RTSPClientSession", and then reimplement this virtual function in your subclass.)
setRTSPResponse(ourClientConnection, "200 OK", fOurSessionId);
}
GenericMediaServer::ClientConnection*
RTSPServer::createNewClientConnection(int clientSocket, struct sockaddr_in clientAddr) {
return new RTSPClientConnection(*this, clientSocket, clientAddr);
}
GenericMediaServer::ClientSession*
RTSPServer::createNewClientSession(u_int32_t sessionId) {
return new RTSPClientSession(*this, sessionId);
}
////////// ServerMediaSessionIterator implementation //////////
RTSPServer::ServerMediaSessionIterator
::ServerMediaSessionIterator(RTSPServer& server)
: fOurIterator((server.fServerMediaSessions == NULL)
? NULL : HashTable::Iterator::create(*server.fServerMediaSessions)) {
}
RTSPServer::ServerMediaSessionIterator::~ServerMediaSessionIterator() {
delete fOurIterator;
}
ServerMediaSession* RTSPServer::ServerMediaSessionIterator::next() {
if (fOurIterator == NULL) return NULL;
char const* key; // dummy
return (ServerMediaSession*)(fOurIterator->next(key));
}
////////// UserAuthenticationDatabase implementation //////////
UserAuthenticationDatabase::UserAuthenticationDatabase(char const* realm,
Boolean passwordsAreMD5)
: fTable(HashTable::create(STRING_HASH_KEYS)),
fRealm(strDup(realm == NULL ? "LIVE555 Streaming Media" : realm)),
fPasswordsAreMD5(passwordsAreMD5) {
}
UserAuthenticationDatabase::~UserAuthenticationDatabase() {
delete[] fRealm;
// Delete the allocated 'password' strings that we stored in the table, and then the table itself:
char* password;
while ((password = (char*)fTable->RemoveNext()) != NULL) {
delete[] password;
}
delete fTable;
}
void UserAuthenticationDatabase::addUserRecord(char const* username,
char const* password) {
fTable->Add(username, (void*)(strDup(password)));
}
void UserAuthenticationDatabase::removeUserRecord(char const* username) {
char* password = (char*)(fTable->Lookup(username));
fTable->Remove(username);
delete[] password;
}
char const* UserAuthenticationDatabase::lookupPassword(char const* username) {
return (char const*)(fTable->Lookup(username));
}
///////// RTSPServerWithREGISTERProxying implementation /////////
RTSPServerWithREGISTERProxying* RTSPServerWithREGISTERProxying
::createNew(UsageEnvironment& env, Port ourPort,
UserAuthenticationDatabase* authDatabase, UserAuthenticationDatabase* authDatabaseForREGISTER,
unsigned reclamationSeconds,
Boolean streamRTPOverTCP, int verbosityLevelForProxying) {
int ourSocket = setUpOurSocket(env, ourPort);
if (ourSocket == -1) return NULL;
return new RTSPServerWithREGISTERProxying(env, ourSocket, ourPort, authDatabase, authDatabaseForREGISTER, reclamationSeconds,
streamRTPOverTCP, verbosityLevelForProxying);
}
RTSPServerWithREGISTERProxying
::RTSPServerWithREGISTERProxying(UsageEnvironment& env, int ourSocket, Port ourPort,
UserAuthenticationDatabase* authDatabase, UserAuthenticationDatabase* authDatabaseForREGISTER,
unsigned reclamationSeconds,
Boolean streamRTPOverTCP, int verbosityLevelForProxying)
: RTSPServer(env, ourSocket, ourPort, authDatabase, reclamationSeconds),
fStreamRTPOverTCP(streamRTPOverTCP), fVerbosityLevelForProxying(verbosityLevelForProxying),
fRegisteredProxyCounter(0), fAllowedCommandNames(NULL), fAuthDBForREGISTER(authDatabaseForREGISTER) {
}
RTSPServerWithREGISTERProxying::~RTSPServerWithREGISTERProxying() {
delete[] fAllowedCommandNames;
}
char const* RTSPServerWithREGISTERProxying::allowedCommandNames() {
if (fAllowedCommandNames == NULL) {
char const* baseAllowedCommandNames = RTSPServer::allowedCommandNames();
char const* newAllowedCommandName = ", REGISTER";
fAllowedCommandNames = new char[strlen(baseAllowedCommandNames) + strlen(newAllowedCommandName) + 1/* for '\0' */];
sprintf(fAllowedCommandNames, "%s%s", baseAllowedCommandNames, newAllowedCommandName);
}
return fAllowedCommandNames;
}
Boolean RTSPServerWithREGISTERProxying::weImplementREGISTER(char const* proxyURLSuffix, char*& responseStr) {
// First, check whether we have already proxied a stream as "proxyURLSuffix":
if (proxyURLSuffix != NULL && lookupServerMediaSession(proxyURLSuffix) != NULL) {
responseStr = strDup("451 Invalid parameter");
return False;
}
// Otherwise, we will implement it:
responseStr = NULL;
return True;
}
void RTSPServerWithREGISTERProxying::implementCmd_REGISTER(char const* url, char const* /*urlSuffix*/, int socketToRemoteServer,
Boolean deliverViaTCP, char const* proxyURLSuffix) {
// Continue setting up proxying for the specified URL.
// By default:
// - We use "registeredProxyStream-N" as the (front-end) stream name (ignoring the back-end stream's 'urlSuffix'),
// unless "proxyURLSuffix" is non-NULL (in which case we use that)
// - There is no 'username' and 'password' for the back-end stream. (Thus, access-controlled back-end streams will fail.)
// - If "fStreamRTPOverTCP" is True, then we request delivery over TCP, regardless of the value of "deliverViaTCP".
// (Otherwise, if "fStreamRTPOverTCP" is False, we use the value of "deliverViaTCP" to decide this.)
// To change this default behavior, you will need to subclass "RTSPServerWithREGISTERProxying", and reimplement this function.
char const* proxyStreamName;
char proxyStreamNameBuf[100];
if (proxyURLSuffix == NULL) {
sprintf(proxyStreamNameBuf, "registeredProxyStream-%u", ++fRegisteredProxyCounter);
proxyStreamName = proxyStreamNameBuf;
} else {
proxyStreamName = proxyURLSuffix;
}
if (fStreamRTPOverTCP) deliverViaTCP = True;
portNumBits tunnelOverHTTPPortNum = deliverViaTCP ? (portNumBits)(~0) : 0;
// We don't support streaming from the back-end via RTSP/RTP/RTCP-over-HTTP; only via RTP/RTCP-over-TCP or RTP/RTCP-over-UDP
ServerMediaSession* sms
= ProxyServerMediaSession::createNew(envir(), this, url, proxyStreamName, NULL, NULL,
tunnelOverHTTPPortNum, fVerbosityLevelForProxying, socketToRemoteServer);
addServerMediaSession(sms);
// (Regardless of the verbosity level) announce the fact that we're proxying this new stream, and the URL to use to access it:
char* proxyStreamURL = rtspURL(sms);
envir() << "Proxying the registered back-end stream \"" << url << "\".\n";
envir() << "\tPlay this stream using the URL: " << proxyStreamURL << "\n";
delete[] proxyStreamURL;
}
UserAuthenticationDatabase* RTSPServerWithREGISTERProxying::getAuthenticationDatabaseForCommand(char const* cmdName) {
if (strcmp(cmdName, "REGISTER") == 0) return fAuthDBForREGISTER;
return RTSPServer::getAuthenticationDatabaseForCommand(cmdName);
}
|
dubhexu/live555
|
liveMedia/RTSPServer.cpp
|
C++
|
lgpl-2.1
| 90,036
|
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
QString tr(const char *text)
{
return QApplication::translate(text, text);
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTextEdit *editor = new QTextEdit();
QTextCursor cursor(editor->textCursor());
cursor.movePosition(QTextCursor::Start);
QTextCharFormat plainFormat(cursor.charFormat());
QTextCharFormat colorFormat = plainFormat;
colorFormat.setForeground(Qt::red);
cursor.insertText(tr("Text can be displayed in a variety of "
"different character "
"formats. "), plainFormat);
cursor.insertText(tr("We can emphasize text by making it "));
cursor.insertText(tr("italic, give it a different color "));
cursor.insertText(tr("to the default text color, underline it, "));
cursor.insertText(tr("and use many other effects."));
QString searchString = tr("text");
QTextDocument *document = editor->document();
//! [0]
QTextCursor newCursor(document);
while (!newCursor.isNull() && !newCursor.atEnd()) {
newCursor = document->find(searchString, newCursor);
if (!newCursor.isNull()) {
newCursor.movePosition(QTextCursor::WordRight,
QTextCursor::KeepAnchor);
newCursor.mergeCharFormat(colorFormat);
}
//! [0] //! [1]
}
//! [1]
editor->setWindowTitle(tr("Text Document Find"));
editor->resize(320, 480);
editor->show();
return app.exec();
}
|
RLovelett/qt
|
doc/src/snippets/textdocument-find/main.cpp
|
C++
|
lgpl-2.1
| 3,493
|
##
# Hash
#
# ISO 15.2.13
class Hash
##
# Equality---Two hashes are equal if they each contain the same number
# of keys and if each key-value pair is equal to (according to
# <code>Object#==</code>) the corresponding elements in the other
# hash.
#
# ISO 15.2.13.4.1
def ==(hash)
return true if self.equal?(hash)
begin
hash = hash.to_hash
rescue NoMethodError
return false
end
return false if self.size != hash.size
self.each do |k,v|
return false unless hash.key?(k)
return false unless self[k] == hash[k]
end
return true
end
##
# Returns <code>true</code> if <i>hash</i> and <i>other</i> are
# both hashes with the same content compared by eql?.
#
# ISO 15.2.13.4.32 (x)
def eql?(hash)
return true if self.equal?(hash)
begin
hash = hash.to_hash
rescue NoMethodError
return false
end
return false if self.size != hash.size
self.each do |k,v|
return false unless hash.key?(k)
return false unless self[k].eql?(hash[k])
end
return true
end
##
# Delete the element with the key +key+.
# Return the value of the element if +key+
# was found. Return nil if nothing was
# found. If a block is given, call the
# block with the value of the element.
#
# ISO 15.2.13.4.8
def delete(key, &block)
if block && !self.has_key?(key)
block.call(key)
else
self.__delete(key)
end
end
##
# Calls the given block for each element of +self+
# and pass the key and value of each element.
#
# call-seq:
# hsh.each {| key, value | block } -> hsh
# hsh.each_pair {| key, value | block } -> hsh
# hsh.each -> an_enumerator
# hsh.each_pair -> an_enumerator
#
#
# If no block is given, an enumerator is returned instead.
#
# h = { "a" => 100, "b" => 200 }
# h.each {|key, value| puts "#{key} is #{value}" }
#
# <em>produces:</em>
#
# a is 100
# b is 200
#
# ISO 15.2.13.4.9
def each(&block)
return to_enum :each unless block_given?
keys = self.keys
vals = self.values
len = self.size
i = 0
while i < len
block.call [keys[i], vals[i]]
i += 1
end
self
end
##
# Calls the given block for each element of +self+
# and pass the key of each element.
#
# call-seq:
# hsh.each_key {| key | block } -> hsh
# hsh.each_key -> an_enumerator
#
# If no block is given, an enumerator is returned instead.
#
# h = { "a" => 100, "b" => 200 }
# h.each_key {|key| puts key }
#
# <em>produces:</em>
#
# a
# b
#
# ISO 15.2.13.4.10
def each_key(&block)
return to_enum :each_key unless block_given?
self.keys.each{|k| block.call(k)}
self
end
##
# Calls the given block for each element of +self+
# and pass the value of each element.
#
# call-seq:
# hsh.each_value {| value | block } -> hsh
# hsh.each_value -> an_enumerator
#
# If no block is given, an enumerator is returned instead.
#
# h = { "a" => 100, "b" => 200 }
# h.each_value {|value| puts value }
#
# <em>produces:</em>
#
# 100
# 200
#
# ISO 15.2.13.4.11
def each_value(&block)
return to_enum :each_value unless block_given?
self.keys.each{|k| block.call(self[k])}
self
end
##
# Replaces the contents of <i>hsh</i> with the contents of other hash
#
# ISO 15.2.13.4.23
def replace(hash)
raise TypeError, "can't convert argument into Hash" unless hash.respond_to?(:to_hash)
self.clear
hash = hash.to_hash
hash.each_key{|k|
self[k] = hash[k]
}
if hash.default_proc
self.default_proc = hash.default_proc
else
self.default = hash.default
end
self
end
# ISO 15.2.13.4.17
alias initialize_copy replace
##
# Return a hash which contains the content of
# +self+ and +other+. If a block is given
# it will be called for each element with
# a duplicate key. The value of the block
# will be the final value of this element.
#
# ISO 15.2.13.4.22
def merge(other, &block)
h = {}
raise TypeError, "can't convert argument into Hash" unless other.respond_to?(:to_hash)
other = other.to_hash
self.each_key{|k| h[k] = self[k]}
if block
other.each_key{|k|
h[k] = (self.has_key?(k))? block.call(k, self[k], other[k]): other[k]
}
else
other.each_key{|k| h[k] = other[k]}
end
h
end
# internal method for Hash inspection
def _inspect
return "{}" if self.size == 0
"{"+self.map {|k,v|
k._inspect + "=>" + v._inspect
}.join(", ")+"}"
end
##
# Return the contents of this hash as a string.
#
# ISO 15.2.13.4.30 (x)
def inspect
begin
self._inspect
rescue SystemStackError
"{...}"
end
end
# ISO 15.2.13.4.31 (x)
alias to_s inspect
##
# call-seq:
# hsh.reject! {| key, value | block } -> hsh or nil
# hsh.reject! -> an_enumerator
#
# Equivalent to <code>Hash#delete_if</code>, but returns
# <code>nil</code> if no changes were made.
#
# 1.8/1.9 Hash#reject! returns Hash; ISO says nothing.
#
def reject!(&b)
return to_enum :reject! unless block_given?
keys = []
self.each{|k,v|
if b.call([k, v])
keys.push(k)
end
}
return nil if keys.size == 0
keys.each{|k|
self.delete(k)
}
self
end
##
# call-seq:
# hsh.reject {|key, value| block} -> a_hash
# hsh.reject -> an_enumerator
#
# Returns a new hash consisting of entries for which the block returns false.
#
# If no block is given, an enumerator is returned instead.
#
# h = { "a" => 100, "b" => 200, "c" => 300 }
# h.reject {|k,v| k < "b"} #=> {"b" => 200, "c" => 300}
# h.reject {|k,v| v > 100} #=> {"a" => 100}
#
# 1.8/1.9 Hash#reject returns Hash; ISO says nothing.
#
def reject(&b)
return to_enum :reject unless block_given?
h = {}
self.each{|k,v|
unless b.call([k, v])
h[k] = v
end
}
h
end
##
# call-seq:
# hsh.select! {| key, value | block } -> hsh or nil
# hsh.select! -> an_enumerator
#
# Equivalent to <code>Hash#keep_if</code>, but returns
# <code>nil</code> if no changes were made.
#
# 1.9 Hash#select! returns Hash; ISO says nothing.
#
def select!(&b)
return to_enum :select! unless block_given?
keys = []
self.each{|k,v|
unless b.call([k, v])
keys.push(k)
end
}
return nil if keys.size == 0
keys.each{|k|
self.delete(k)
}
self
end
##
# call-seq:
# hsh.select {|key, value| block} -> a_hash
# hsh.select -> an_enumerator
#
# Returns a new hash consisting of entries for which the block returns true.
#
# If no block is given, an enumerator is returned instead.
#
# h = { "a" => 100, "b" => 200, "c" => 300 }
# h.select {|k,v| k > "a"} #=> {"b" => 200, "c" => 300}
# h.select {|k,v| v < 200} #=> {"a" => 100}
#
# 1.9 Hash#select returns Hash; ISO says nothing
#
def select(&b)
return to_enum :select unless block_given?
h = {}
self.each{|k,v|
if b.call([k, v])
h[k] = v
end
}
h
end
##
# call-seq:
# hsh.rehash -> hsh
#
# Rebuilds the hash based on the current hash values for each key. If
# values of key objects have changed since they were inserted, this
# method will reindex <i>hsh</i>.
#
# h = {"AAA" => "b"}
# h.keys[0].chop!
# h #=> {"AA"=>"b"}
# h["AA"] #=> nil
# h.rehash #=> {"AA"=>"b"}
# h["AA"] #=> "b"
#
def rehash
h = {}
self.each{|k,v|
h[k] = v
}
self.replace(h)
end
def __update(h)
h.each_key{|k| self[k] = h[k]}
self
end
end
##
# Hash is enumerable
#
# ISO 15.2.13.3
class Hash
include Enumerable
end
|
kenhys/debian-groonga
|
vendor/ngx_mruby-source/mruby_test/mrblib/hash.rb
|
Ruby
|
lgpl-2.1
| 8,122
|
/*
* testutils.c: basic test utils
*
* Copyright (C) 2005-2012 Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* <http://www.gnu.org/licenses/>.
*
* Karel Zak <kzak@redhat.com>
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifndef WIN32
# include <sys/wait.h>
#endif
#ifdef HAVE_REGEX_H
# include <regex.h>
#endif
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <limits.h>
#include "testutils.h"
#include "internal.h"
#include "memory.h"
#include "util.h"
#include "threads.h"
#include "virterror_internal.h"
#include "buf.h"
#include "logging.h"
#include "command.h"
#include "virrandom.h"
#include "dirname.h"
#include "virprocess.h"
#if TEST_OOM_TRACE
# include <execinfo.h>
#endif
#ifdef HAVE_PATHS_H
# include <paths.h>
#endif
#define VIR_FROM_THIS VIR_FROM_NONE
#define GETTIMEOFDAY(T) gettimeofday(T, NULL)
#define DIFF_MSEC(T, U) \
((((int) ((T)->tv_sec - (U)->tv_sec)) * 1000000.0 + \
((int) ((T)->tv_usec - (U)->tv_usec))) / 1000.0)
#include "virfile.h"
static unsigned int testDebug = -1;
static unsigned int testVerbose = -1;
static unsigned int testOOM = 0;
static unsigned int testCounter = 0;
char *progname;
char *abs_srcdir;
double
virtTestCountAverage(double *items, int nitems)
{
long double sum = 0;
int i;
for (i=1; i < nitems; i++)
sum += items[i];
return (double) (sum / nitems);
}
void virtTestResult(const char *name, int ret, const char *msg, ...)
{
va_list vargs;
va_start(vargs, msg);
if (testCounter == 0 && !virTestGetVerbose())
fprintf(stderr, " ");
testCounter++;
if (virTestGetVerbose()) {
fprintf(stderr, "%3d) %-60s ", testCounter, name);
if (ret == 0)
fprintf(stderr, "OK\n");
else {
fprintf(stderr, "FAILED\n");
if (msg) {
char *str;
if (virVasprintf(&str, msg, vargs) == 0) {
fprintf(stderr, "%s", str);
VIR_FREE(str);
}
}
}
} else {
if (testCounter != 1 &&
!((testCounter-1) % 40)) {
fprintf(stderr, " %-3d\n", (testCounter-1));
fprintf(stderr, " ");
}
if (ret == 0)
fprintf(stderr, ".");
else
fprintf(stderr, "!");
}
va_end(vargs);
}
/*
* Runs test and count average time (if the nloops is grater than 1)
*
* returns: -1 = error, 0 = success
*/
int
virtTestRun(const char *title, int nloops, int (*body)(const void *data), const void *data)
{
int i, ret = 0;
double *ts = NULL;
if (testCounter == 0 && !virTestGetVerbose())
fprintf(stderr, " ");
testCounter++;
if (testOOM < 2) {
if (virTestGetVerbose())
fprintf(stderr, "%2d) %-65s ... ", testCounter, title);
}
if (nloops > 1 && (VIR_ALLOC_N(ts, nloops) < 0))
return -1;
for (i=0; i < nloops; i++) {
struct timeval before, after;
if (ts)
GETTIMEOFDAY(&before);
virResetLastError();
ret = body(data);
virErrorPtr err = virGetLastError();
if (err) {
if (virTestGetVerbose() || virTestGetDebug())
virDispatchError(NULL);
}
if (ret != 0) {
break;
}
if (ts) {
GETTIMEOFDAY(&after);
ts[i] = DIFF_MSEC(&after, &before);
}
}
if (testOOM < 2) {
if (virTestGetVerbose()) {
if (ret == 0 && ts)
fprintf(stderr, "OK [%.5f ms]\n",
virtTestCountAverage(ts, nloops));
else if (ret == 0)
fprintf(stderr, "OK\n");
else if (ret == EXIT_AM_SKIP)
fprintf(stderr, "SKIP\n");
else
fprintf(stderr, "FAILED\n");
} else {
if (testCounter != 1 &&
!((testCounter-1) % 40)) {
fprintf(stderr, " %-3d\n", (testCounter-1));
fprintf(stderr, " ");
}
if (ret == 0)
fprintf(stderr, ".");
else if (ret == EXIT_AM_SKIP)
fprintf(stderr, "_");
else
fprintf(stderr, "!");
}
}
VIR_FREE(ts);
return ret;
}
/* Allocate BUF to the size of FILE. Read FILE into buffer BUF.
Upon any failure, diagnose it and return -1, but don't bother trying
to preserve errno. Otherwise, return the number of bytes copied into BUF. */
int
virtTestLoadFile(const char *file, char **buf)
{
FILE *fp = fopen(file, "r");
struct stat st;
char *tmp;
int len, tmplen, buflen;
if (!fp) {
fprintf(stderr, "%s: failed to open: %s\n", file, strerror(errno));
return -1;
}
if (fstat(fileno(fp), &st) < 0) {
fprintf(stderr, "%s: failed to fstat: %s\n", file, strerror(errno));
VIR_FORCE_FCLOSE(fp);
return -1;
}
tmplen = buflen = st.st_size + 1;
if (VIR_ALLOC_N(*buf, buflen) < 0) {
fprintf(stderr, "%s: larger than available memory (> %d)\n", file, buflen);
VIR_FORCE_FCLOSE(fp);
return -1;
}
tmp = *buf;
(*buf)[0] = '\0';
if (st.st_size) {
/* read the file line by line */
while (fgets(tmp, tmplen, fp) != NULL) {
len = strlen(tmp);
/* stop on an empty line */
if (len == 0)
break;
/* remove trailing backslash-newline pair */
if (len >= 2 && tmp[len-2] == '\\' && tmp[len-1] == '\n') {
len -= 2;
tmp[len] = '\0';
}
/* advance the temporary buffer pointer */
tmp += len;
tmplen -= len;
}
if (ferror(fp)) {
fprintf(stderr, "%s: read failed: %s\n", file, strerror(errno));
VIR_FORCE_FCLOSE(fp);
VIR_FREE(*buf);
return -1;
}
}
VIR_FORCE_FCLOSE(fp);
return strlen(*buf);
}
#ifndef WIN32
static
void virtTestCaptureProgramExecChild(const char *const argv[],
int pipefd) {
int i;
int open_max;
int stdinfd = -1;
const char *const env[] = {
"LANG=C",
# if WITH_DRIVER_MODULES
"LIBVIRT_DRIVER_DIR=" TEST_DRIVER_DIR,
# endif
NULL
};
if ((stdinfd = open("/dev/null", O_RDONLY)) < 0)
goto cleanup;
open_max = sysconf(_SC_OPEN_MAX);
for (i = 0; i < open_max; i++) {
if (i != stdinfd &&
i != pipefd) {
int tmpfd = i;
VIR_FORCE_CLOSE(tmpfd);
}
}
if (dup2(stdinfd, STDIN_FILENO) != STDIN_FILENO)
goto cleanup;
if (dup2(pipefd, STDOUT_FILENO) != STDOUT_FILENO)
goto cleanup;
if (dup2(pipefd, STDERR_FILENO) != STDERR_FILENO)
goto cleanup;
/* SUS is crazy here, hence the cast */
execve(argv[0], (char *const*)argv, (char *const*)env);
cleanup:
VIR_FORCE_CLOSE(stdinfd);
}
int
virtTestCaptureProgramOutput(const char *const argv[], char **buf, int maxlen)
{
int pipefd[2];
int len;
if (pipe(pipefd) < 0)
return -1;
pid_t pid = fork();
switch (pid) {
case 0:
VIR_FORCE_CLOSE(pipefd[0]);
virtTestCaptureProgramExecChild(argv, pipefd[1]);
VIR_FORCE_CLOSE(pipefd[1]);
_exit(1);
case -1:
return -1;
default:
VIR_FORCE_CLOSE(pipefd[1]);
len = virFileReadLimFD(pipefd[0], maxlen, buf);
VIR_FORCE_CLOSE(pipefd[0]);
if (virProcessWait(pid, NULL) < 0)
return -1;
return len;
}
}
#else /* !WIN32 */
int
virtTestCaptureProgramOutput(const char *const argv[] ATTRIBUTE_UNUSED,
char **buf ATTRIBUTE_UNUSED,
int maxlen ATTRIBUTE_UNUSED)
{
return -1;
}
#endif /* !WIN32 */
/**
* @param stream: output stream write to differences to
* @param expect: expected output text
* @param actual: actual output text
*
* Display expected and actual output text, trimmed to
* first and last characters at which differences occur
*/
int virtTestDifference(FILE *stream,
const char *expect,
const char *actual)
{
const char *expectStart = expect;
const char *expectEnd = expect + (strlen(expect)-1);
const char *actualStart = actual;
const char *actualEnd = actual + (strlen(actual)-1);
if (!virTestGetDebug())
return 0;
if (virTestGetDebug() < 2) {
/* Skip to first character where they differ */
while (*expectStart && *actualStart &&
*actualStart == *expectStart) {
actualStart++;
expectStart++;
}
/* Work backwards to last character where they differ */
while (actualEnd > actualStart &&
expectEnd > expectStart &&
*actualEnd == *expectEnd) {
actualEnd--;
expectEnd--;
}
}
/* Show the trimmed differences */
fprintf(stream, "\nOffset %d\nExpect [", (int) (expectStart - expect));
if ((expectEnd - expectStart + 1) &&
fwrite(expectStart, (expectEnd-expectStart+1), 1, stream) != 1)
return -1;
fprintf(stream, "]\n");
fprintf(stream, "Actual [");
if ((actualEnd - actualStart + 1) &&
fwrite(actualStart, (actualEnd-actualStart+1), 1, stream) != 1)
return -1;
fprintf(stream, "]\n");
/* Pad to line up with test name ... in virTestRun */
fprintf(stream, " ... ");
return 0;
}
/**
* @param stream: output stream write to differences to
* @param expect: expected output text
* @param actual: actual output text
*
* Display expected and actual output text, trimmed to
* first and last characters at which differences occur
*/
int virtTestDifferenceBin(FILE *stream,
const char *expect,
const char *actual,
size_t length)
{
size_t start = 0, end = length;
ssize_t i;
if (!virTestGetDebug())
return 0;
if (virTestGetDebug() < 2) {
/* Skip to first character where they differ */
for (i = 0 ; i < length ; i++) {
if (expect[i] != actual[i]) {
start = i;
break;
}
}
/* Work backwards to last character where they differ */
for (i = (length -1) ; i >= 0 ; i--) {
if (expect[i] != actual[i]) {
end = i;
break;
}
}
}
/* Round to nearest boundary of 4, except that last word can be short */
start -= (start % 4);
end += 4 - (end % 4);
if (end >= length)
end = length - 1;
/* Show the trimmed differences */
fprintf(stream, "\nExpect [ Region %d-%d", (int)start, (int)end);
for (i = start; i < end ; i++) {
if ((i % 4) == 0)
fprintf(stream, "\n ");
fprintf(stream, "0x%02x, ", ((int)expect[i])&0xff);
}
fprintf(stream, "]\n");
fprintf(stream, "Actual [ Region %d-%d", (int)start, (int)end);
for (i = start; i < end ; i++) {
if ((i % 4) == 0)
fprintf(stream, "\n ");
fprintf(stream, "0x%02x, ", ((int)actual[i])&0xff);
}
fprintf(stream, "]\n");
/* Pad to line up with test name ... in virTestRun */
fprintf(stream, " ... ");
return 0;
}
#if TEST_OOM
static void
virtTestErrorFuncQuiet(void *data ATTRIBUTE_UNUSED,
virErrorPtr err ATTRIBUTE_UNUSED)
{ }
#endif
struct virtTestLogData {
virBuffer buf;
};
static struct virtTestLogData testLog = { VIR_BUFFER_INITIALIZER };
static void
virtTestLogOutput(virLogSource source ATTRIBUTE_UNUSED,
virLogPriority priority ATTRIBUTE_UNUSED,
const char *filename ATTRIBUTE_UNUSED,
int lineno ATTRIBUTE_UNUSED,
const char *funcname ATTRIBUTE_UNUSED,
const char *timestamp,
virLogMetadataPtr metadata ATTRIBUTE_UNUSED,
unsigned int flags,
const char *rawstr ATTRIBUTE_UNUSED,
const char *str,
void *data)
{
struct virtTestLogData *log = data;
virCheckFlags(VIR_LOG_STACK_TRACE,);
virBufferAsprintf(&log->buf, "%s: %s", timestamp, str);
}
static void
virtTestLogClose(void *data)
{
struct virtTestLogData *log = data;
virBufferFreeAndReset(&log->buf);
}
/* Return a malloc'd string (possibly with strlen of 0) of all data
* logged since the last call to this function, or NULL on failure. */
char *
virtTestLogContentAndReset(void)
{
char *ret;
if (virBufferError(&testLog.buf))
return NULL;
ret = virBufferContentAndReset(&testLog.buf);
return ret ? ret : strdup("");
}
#if TEST_OOM_TRACE
static void
virtTestErrorHook(int n, void *data ATTRIBUTE_UNUSED)
{
void *trace[30];
int ntrace = ARRAY_CARDINALITY(trace);
int i;
char **symbols = NULL;
ntrace = backtrace(trace, ntrace);
symbols = backtrace_symbols(trace, ntrace);
if (symbols) {
fprintf(stderr, "Failing allocation %d at:\n", n);
for (i = 0 ; i < ntrace ; i++) {
if (symbols[i])
fprintf(stderr, " TRACE: %s\n", symbols[i]);
}
VIR_FREE(symbols);
}
}
#endif
static unsigned int
virTestGetFlag(const char *name) {
char *flagStr;
unsigned int flag;
if ((flagStr = getenv(name)) == NULL)
return 0;
if (virStrToLong_ui(flagStr, NULL, 10, &flag) < 0)
return 0;
return flag;
}
unsigned int
virTestGetDebug(void) {
if (testDebug == -1)
testDebug = virTestGetFlag("VIR_TEST_DEBUG");
return testDebug;
}
unsigned int
virTestGetVerbose(void) {
if (testVerbose == -1)
testVerbose = virTestGetFlag("VIR_TEST_VERBOSE");
return testVerbose || virTestGetDebug();
}
int virtTestMain(int argc,
char **argv,
int (*func)(void))
{
int ret;
bool abs_srcdir_cleanup = false;
#if TEST_OOM
int approxAlloc = 0;
int n;
char *oomStr = NULL;
int oomCount;
int mp = 0;
pid_t *workers;
int worker = 0;
#endif
abs_srcdir = getenv("abs_srcdir");
if (!abs_srcdir) {
abs_srcdir = getcwd(NULL, 0);
abs_srcdir_cleanup = true;
}
if (!abs_srcdir)
exit(EXIT_AM_HARDFAIL);
progname = last_component(argv[0]);
if (STRPREFIX(progname, "lt-"))
progname += 3;
if (argc > 1) {
fprintf(stderr, "Usage: %s\n", argv[0]);
fputs("effective environment variables:\n"
"VIR_TEST_VERBOSE set to show names of individual tests\n"
"VIR_TEST_DEBUG set to show information for debugging failures\n",
stderr);
return EXIT_FAILURE;
}
fprintf(stderr, "TEST: %s\n", progname);
if (virThreadInitialize() < 0 ||
virErrorInitialize() < 0)
return 1;
virLogSetFromEnv();
if (!getenv("LIBVIRT_DEBUG") && !virLogGetNbOutputs()) {
if (virLogDefineOutput(virtTestLogOutput, virtTestLogClose, &testLog,
VIR_LOG_DEBUG, VIR_LOG_TO_STDERR, NULL, 0) < 0)
return 1;
}
#if TEST_OOM
if ((oomStr = getenv("VIR_TEST_OOM")) != NULL) {
if (virStrToLong_i(oomStr, NULL, 10, &oomCount) < 0)
oomCount = 0;
if (oomCount < 0)
oomCount = 0;
if (oomCount)
testOOM = 1;
}
if (getenv("VIR_TEST_MP") != NULL) {
mp = sysconf(_SC_NPROCESSORS_ONLN);
fprintf(stderr, "Using %d worker processes\n", mp);
if (VIR_ALLOC_N(workers, mp) < 0) {
ret = EXIT_FAILURE;
goto cleanup;
}
}
/* Run once to prime any static allocations & ensure it passes */
ret = (func)();
if (ret != EXIT_SUCCESS)
goto cleanup;
# if TEST_OOM_TRACE
if (virTestGetDebug())
virAllocTestHook(virtTestErrorHook, NULL);
# endif
if (testOOM) {
/* Makes next test runs quiet... */
testOOM++;
virSetErrorFunc(NULL, virtTestErrorFuncQuiet);
virAllocTestInit();
/* Run again to count allocs, and ensure it passes :-) */
ret = (func)();
if (ret != EXIT_SUCCESS)
goto cleanup;
approxAlloc = virAllocTestCount();
testCounter++;
if (virTestGetDebug())
fprintf(stderr, "%d) OOM...\n", testCounter);
else
fprintf(stderr, "%d) OOM of %d allocs ", testCounter, approxAlloc);
if (mp) {
int i;
for (i = 0 ; i < mp ; i++) {
workers[i] = fork();
if (workers[i] == 0) {
worker = i + 1;
break;
}
}
}
/* Run once for each alloc, failing a different one
and validating that the test case failed */
for (n = 0; n < approxAlloc && (!mp || worker) ; n++) {
if (mp &&
(n % mp) != (worker - 1))
continue;
if (!virTestGetDebug()) {
if (mp)
fprintf(stderr, "%d", worker);
else
fprintf(stderr, ".");
fflush(stderr);
}
virAllocTestOOM(n+1, oomCount);
if (((func)()) != EXIT_FAILURE) {
ret = EXIT_FAILURE;
break;
}
}
if (mp) {
if (worker) {
_exit(ret);
} else {
int i, status;
for (i = 0 ; i < mp ; i++) {
if (virProcessWait(workers[i], NULL) < 0)
ret = EXIT_FAILURE;
}
VIR_FREE(workers);
}
}
if (virTestGetDebug())
fprintf(stderr, " ... OOM of %d allocs", approxAlloc);
if (ret == EXIT_SUCCESS)
fprintf(stderr, " OK\n");
else
fprintf(stderr, " FAILED\n");
}
cleanup:
#else
ret = (func)();
#endif
if (abs_srcdir_cleanup)
VIR_FREE(abs_srcdir);
virResetLastError();
if (!virTestGetVerbose() && ret != EXIT_AM_SKIP) {
if (testCounter == 0 || testCounter % 40)
fprintf(stderr, "%*s", 40 - (testCounter % 40), "");
fprintf(stderr, " %-3d %s\n", testCounter, ret == 0 ? "OK" : "FAIL");
}
return ret;
}
#ifdef HAVE_REGEX_H
int virtTestClearLineRegex(const char *pattern,
char *str)
{
regex_t reg;
char *lineStart = str;
char *lineEnd = strchr(str, '\n');
if (regcomp(®, pattern, REG_EXTENDED | REG_NOSUB) != 0)
return -1;
while (lineStart) {
int ret;
if (lineEnd)
*lineEnd = '\0';
ret = regexec(®, lineStart, 0, NULL, 0);
//fprintf(stderr, "Match %d '%s' '%s'\n", ret, lineStart, pattern);
if (ret == 0) {
if (lineEnd) {
memmove(lineStart, lineEnd + 1, strlen(lineEnd+1) + 1);
/* Don't update lineStart - just iterate again on this
location */
lineEnd = strchr(lineStart, '\n');
} else {
*lineStart = '\0';
lineStart = NULL;
}
} else {
if (lineEnd) {
*lineEnd = '\n';
lineStart = lineEnd + 1;
lineEnd = strchr(lineStart, '\n');
} else {
lineStart = NULL;
}
}
}
regfree(®);
return 0;
}
#else
int virtTestClearLineRegex(const char *pattern ATTRIBUTE_UNUSED,
char *str ATTRIBUTE_UNUSED)
{
return 0;
}
#endif
|
jeckersb/libvirt
|
tests/testutils.c
|
C
|
lgpl-2.1
| 20,810
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>CQRS.NET: Cqrs.EventStore.Bus.EventConverter.GetEventFromData< TEvent ></title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">CQRS.NET
 <span id="projectnumber">2.0</span>
</div>
<div id="projectbrief">A lightweight enterprise framework to write CQRS, event-sourced and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('classCqrs_1_1EventStore_1_1Bus_1_1EventConverter_a22d7d8455731564574dc9684c272e6d2.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="contents">
<a id="a22d7d8455731564574dc9684c272e6d2"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a22d7d8455731564574dc9684c272e6d2">◆ </a></span>GetEventFromData< TEvent >()</h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">static TEvent Cqrs.EventStore.Bus.EventConverter.GetEventFromData< TEvent > </td>
<td>(</td>
<td class="paramtype">byte [] </td>
<td class="paramname"><em>eventData</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">string </td>
<td class="paramname"><em>typeName</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="namespaceCqrs.html">Cqrs</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1EventStore.html">EventStore</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1EventStore_1_1Bus.html">Bus</a></li><li class="navelem"><a class="el" href="classCqrs_1_1EventStore_1_1Bus_1_1EventConverter.html">EventConverter</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li>
</ul>
</div>
</body>
</html>
|
Chinchilla-Software-Com/CQRS
|
wiki/docs/2.0/html/classCqrs_1_1EventStore_1_1Bus_1_1EventConverter_a22d7d8455731564574dc9684c272e6d2.html
|
HTML
|
lgpl-2.1
| 5,431
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_15) on Tue Sep 29 11:26:47 CEST 2009 -->
<TITLE>
peersim.transport
</TITLE>
<META NAME="date" CONTENT="2009-09-29">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="peersim.transport";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../peersim/reports/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../peersim/util/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../index.html?peersim/transport/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<H2>
Package peersim.transport
</H2>
Classes and interfaces for simulating transport-level communication
in overlay networks.
<P>
<B>See:</B>
<BR>
<A HREF="#package_description"><B>Description</B></A>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Interface Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../peersim/transport/RouterInfo.html" title="interface in peersim.transport">RouterInfo</A></B></TD>
<TD>Generic interface to be implemented by protocols that need to be assigned to
routers.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../peersim/transport/Transport.html" title="interface in peersim.transport">Transport</A></B></TD>
<TD>This interface represents a generic transport protocol, used to
send messages through the underlying network.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Class Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../peersim/transport/E2ENetwork.html" title="class in peersim.transport">E2ENetwork</A></B></TD>
<TD>This static singleton emulates an underlying router network
of fixed size, and stores the latency measurements for all pairs
of routers.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../peersim/transport/E2ETransport.html" title="class in peersim.transport">E2ETransport</A></B></TD>
<TD>This transport protocol is based on the <A HREF="../../peersim/transport/E2ENetwork.html" title="class in peersim.transport"><CODE>E2ENetwork</CODE></A> class.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../peersim/transport/KingParser.html" title="class in peersim.transport">KingParser</A></B></TD>
<TD>Initializes static singleton <A HREF="../../peersim/transport/E2ENetwork.html" title="class in peersim.transport"><CODE>E2ENetwork</CODE></A> by reading a king data set.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../peersim/transport/TriangularMatrixParser.html" title="class in peersim.transport">TriangularMatrixParser</A></B></TD>
<TD>Initializes static singleton <A HREF="../../peersim/transport/E2ENetwork.html" title="class in peersim.transport"><CODE>E2ENetwork</CODE></A> by reading a trace
file containing the latency distance measured between a set of
"virtual" routers.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../peersim/transport/UniformRandomTransport.html" title="class in peersim.transport">UniformRandomTransport</A></B></TD>
<TD>Implement a transport layer that reliably delivers messages with a random
delay, that is drawn from the configured interval according to the uniform
distribution.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../peersim/transport/UniformRouterAssignment.html" title="class in peersim.transport">UniformRouterAssignment</A></B></TD>
<TD>Initializes <A HREF="../../peersim/transport/RouterInfo.html" title="interface in peersim.transport"><CODE>RouterInfo</CODE></A> protocols by assigning routers to them.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../peersim/transport/UnreliableTransport.html" title="class in peersim.transport">UnreliableTransport</A></B></TD>
<TD>This transport protocol can be combined with other transports
to simulate message losses.</TD>
</TR>
</TABLE>
<P>
<A NAME="package_description"><!-- --></A><H2>
Package peersim.transport Description
</H2>
<P>
Classes and interfaces for simulating transport-level communication
in overlay networks.
This is achieved by classes implementing the interface
<A HREF="../../peersim/transport/Transport.html" title="interface in peersim.transport"><CODE>Transport</CODE></A>, that are repsonsible for modeling
message delay, message omissions, etc
<p>
It is also possible to use models of the underlying router network
to determine latency (<A HREF="../../peersim/transport/E2ETransport.html" title="class in peersim.transport"><CODE>E2ETransport</CODE></A>).
This model is stored in static singleton <A HREF="../../peersim/transport/E2ENetwork.html" title="class in peersim.transport"><CODE>E2ENetwork</CODE></A>.
This class can be initialized by controls using eg measurement data
(<A HREF="../../peersim/transport/KingParser.html" title="class in peersim.transport"><CODE>KingParser</CODE></A>). To be usable, nodes must be assigned
to routers. An example control that does that is
<A HREF="../../peersim/transport/UniformRouterAssignment.html" title="class in peersim.transport"><CODE>UniformRouterAssignment</CODE></A>.
<P>
<P>
<DL>
</DL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../peersim/reports/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../peersim/util/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../index.html?peersim/transport/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
|
rbraeunlich/ReliableADGSASimulation
|
target/classes/lib/peersim-1.0.5/doc/peersim/transport/package-summary.html
|
HTML
|
lgpl-2.1
| 10,349
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtDebug>
#include "ExpressionInfo.h"
using namespace QPatternistSDK;
ExpressionInfo::ExpressionInfo(const QString &name,
const QString &details) : QPair<QString, QString>(name, details)
{
}
// vim: et:ts=4:sw=4:sts=4
|
CodeDJ/qt5-hidpi
|
qt/qtxmlpatterns/tests/auto/xmlpatternssdk/ExpressionInfo.cpp
|
C++
|
lgpl-2.1
| 2,229
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LCOV - doc-coverage.info - Cqrs/Entities/Range.cs</title>
<link rel="stylesheet" type="text/css" href="../../gcov.css">
</head>
<body>
<table width="100%" border=0 cellspacing=0 cellpadding=0>
<tr><td class="title">Documentation Coverage Report</td></tr>
<tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr>
<tr>
<td width="100%">
<table cellpadding=1 border=0 width="100%">
<tr>
<td width="10%" class="headerItem">Current view:</td>
<td width="35%" class="headerValue"><a href="../../index.html">top level</a> - <a href="index.html">Cqrs/Entities</a> - Range.cs</td>
<td width="5%"></td>
<td width="15%"></td>
<td width="10%" class="headerCovTableHead">Hit</td>
<td width="10%" class="headerCovTableHead">Total</td>
<td width="15%" class="headerCovTableHead">Coverage</td>
</tr>
<tr>
<td class="headerItem">Version:</td>
<td class="headerValue">4.0</td>
<td></td>
<td class="headerItem">Artefacts:</td>
<td class="headerCovTableEntry">1</td>
<td class="headerCovTableEntry">1</td>
<td class="headerCovTableEntryHi">100.0 %</td>
</tr>
<tr>
<td class="headerItem">Date:</td>
<td class="headerValue">2019-11-25 19:57:53</td>
<td></td>
</tr>
<tr><td><img src="../../glass.png" width=3 height=3 alt=""></td></tr>
</table>
</td>
</tr>
<tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr>
</table>
<table cellpadding=0 cellspacing=0 border=0>
<tr>
<td><br></td>
</tr>
<tr>
<td>
<pre class="sourceHeading"> Line data Source code</pre>
<pre class="source">
<span class="lineNum"> 1 </span> : #region Copyright
<span class="lineNum"> 2 </span> : // // -----------------------------------------------------------------------
<span class="lineNum"> 3 </span> : // // <copyright company="Chinchilla Software Limited">
<span class="lineNum"> 4 </span> : // // Copyright Chinchilla Software Limited. All rights reserved.
<span class="lineNum"> 5 </span> : // // </copyright>
<span class="lineNum"> 6 </span> : // // -----------------------------------------------------------------------
<span class="lineNum"> 7 </span> : #endregion
<span class="lineNum"> 8 </span> :
<span class="lineNum"> 9 </span> : using System;
<span class="lineNum"> 10 </span> :
<span class="lineNum"> 11 </span> : namespace Cqrs.Entities
<span class="lineNum"> 12 </span> : {
<span class="lineNum"> 13 </span> : /// <summary>
<span class="lineNum"> 14 </span> : /// A range object for collecting a lower and upper limit, such as a number or date range.
<span class="lineNum"> 15 </span> : /// </summary>
<span class="lineNum"> 16 </span> : public class Range<TPrimitive>
<span class="lineNum"> 17 </span> : where TPrimitive : struct
<span class="lineNum"> 18 </span><span class="lineCov"> 1 : {</span>
<span class="lineNum"> 19 </span> : /// <summary>
<span class="lineNum"> 20 </span> : /// The lower limit such as a from <see cref="DateTime"/>.
<span class="lineNum"> 21 </span> : /// </summary>
<span class="lineNum"> 22 </span> : public TPrimitive? From { get; set; }
<span class="lineNum"> 23 </span> :
<span class="lineNum"> 24 </span> : /// <summary>
<span class="lineNum"> 25 </span> : /// The upper limit such as a to <see cref="DateTime"/>.
<span class="lineNum"> 26 </span> : /// </summary>
<span class="lineNum"> 27 </span> : public TPrimitive? To { get; set; }
<span class="lineNum"> 28 </span> :
<span class="lineNum"> 29 </span> : /// <summary>
<span class="lineNum"> 30 </span> : /// Is the value of <see cref="From"/> inclusive or not. Defaults to true.
<span class="lineNum"> 31 </span> : /// </summary>
<span class="lineNum"> 32 </span> : public bool IsFromInclusive { get; set; }
<span class="lineNum"> 33 </span> :
<span class="lineNum"> 34 </span> : /// <summary>
<span class="lineNum"> 35 </span> : /// Is the value of <see cref="To"/> inclusive or not. Defaults to true.
<span class="lineNum"> 36 </span> : /// </summary>
<span class="lineNum"> 37 </span> : public bool IsToInclusive { get; set; }
<span class="lineNum"> 38 </span> : }
<span class="lineNum"> 39 </span> : }
</pre>
</td>
</tr>
</table>
<br>
<table width="100%" border=0 cellspacing=0 cellpadding=0>
<tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr>
<tr><td class="versionInfo">Generated by: <a href="http://ltp.sourceforge.net/coverage/lcov.php" target="_parent">LCOV version 1.13</a></td></tr>
</table>
<br>
</body>
</html>
|
cdmdotnet/CQRS
|
wiki/docs/4.1/coverage-report/Cqrs/Entities/Range.cs.gcov.html
|
HTML
|
lgpl-2.1
| 6,056
|
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Kcov(CMakePackage):
"""Code coverage tool for compiled programs, Python and Bash which uses
debugging information to collect and report data without special
compilation options"""
homepage = "http://simonkagstrom.github.io/kcov/index.html"
url = "https://github.com/SimonKagstrom/kcov/archive/38.tar.gz"
version('38', sha256='b37af60d81a9b1e3b140f9473bdcb7975af12040feb24cc666f9bb2bb0be68b4')
depends_on('cmake@2.8.4:', type='build')
depends_on('zlib')
depends_on('curl')
def cmake_args(self):
# Necessary at least on macOS, fixes linking error to LLDB
# https://github.com/Homebrew/homebrew-core/blob/master/Formula/kcov.rb
return ['-DSPECIFY_RPATH=ON']
@run_after('install')
@on_package_attributes(run_tests=True)
def test_install(self):
# The help message exits with an exit code of 1
kcov = Executable(self.prefix.bin.kcov)
kcov('-h', ignore_errors=1)
|
iulian787/spack
|
var/spack/repos/builtin/packages/kcov/package.py
|
Python
|
lgpl-2.1
| 1,192
|
#!/usr/bin/python2
# -*- coding: utf-8 -*-
#
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2016 Marek Marczykowski-Górecki
# <marmarek@invisiblethingslab.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, see <https://www.gnu.org/licenses/>.
#
#
import os
import qubes.tests
import time
import subprocess
from unittest import expectedFailure
class TC_00_HVM(qubes.tests.SystemTestsMixin, qubes.tests.QubesTestCase):
def setUp(self):
super(TC_00_HVM, self).setUp()
self.vm = self.qc.add_new_vm("QubesHVm",
name=self.make_vm_name('vm1'))
self.vm.create_on_disk(verbose=False)
@expectedFailure
def test_000_pci_passthrough_presence(self):
pcidev = os.environ.get('QUBES_TEST_PCIDEV', None)
if pcidev is None:
self.skipTest('Specify PCI device with QUBES_TEST_PCIDEV '
'environment variable')
self.vm.pcidevs = [pcidev]
self.vm.pci_strictreset = False
self.qc.save()
self.qc.unlock_db()
init_script = (
"#!/bin/sh\n"
"set -e\n"
"lspci -n > /dev/xvdb\n"
"poweroff\n"
)
self.prepare_hvm_system_linux(self.vm, init_script,
['/usr/sbin/lspci'])
self.vm.start()
timeout = 60
while timeout > 0:
if not self.vm.is_running():
break
time.sleep(1)
timeout -= 1
if self.vm.is_running():
self.fail("Timeout while waiting for VM shutdown")
with open(self.vm.storage.private_img, 'r') as f:
lspci_vm = f.read(512).strip('\0')
p = subprocess.Popen(['lspci', '-ns', pcidev], stdout=subprocess.PIPE)
(lspci_host, _) = p.communicate()
# strip BDF, as it is different in VM
pcidev_desc = ' '.join(lspci_host.strip().split(' ')[1:])
self.assertIn(pcidev_desc, lspci_vm)
|
woju/qubes-core-admin
|
tests/hardware.py
|
Python
|
lgpl-2.1
| 2,564
|
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#ifndef SOFA_COMPONENT_PROJECTIVECONSTRAINTSET_AFFINEMOVEMENTCONSTRAINT_H
#define SOFA_COMPONENT_PROJECTIVECONSTRAINTSET_AFFINEMOVEMENTCONSTRAINT_H
#include "config.h"
#include <sofa/core/behavior/ProjectiveConstraintSet.h>
#include <sofa/core/behavior/MechanicalState.h>
#include <sofa/core/topology/BaseMeshTopology.h>
#include <sofa/core/objectmodel/Event.h>
#include <sofa/defaulttype/Mat.h>
#include <sofa/helper/vector.h>
#include <sofa/helper/Quater.h>
#include <SofaBaseTopology/TopologySubsetData.h>
#include <sofa/defaulttype/VecTypes.h>
#include <sofa/defaulttype/RigidTypes.h>
#include <type_traits>
#include <set>
namespace sofa
{
namespace component
{
namespace projectiveconstraintset
{
template<class DataTypes>
class AffineMovementConstraintInternalData
{
};
/**
Impose a motion to all the boundary points of a mesh. The motion of the 4 corners are given in the data m_cornerMovements and the movements of the edge points are computed by linear interpolation.
*/
template <class TDataTypes>
class AffineMovementConstraint : public core::behavior::ProjectiveConstraintSet<TDataTypes>
{
public:
SOFA_CLASS(SOFA_TEMPLATE(AffineMovementConstraint,TDataTypes),SOFA_TEMPLATE(sofa::core::behavior::ProjectiveConstraintSet, TDataTypes));
typedef TDataTypes DataTypes;
typedef typename DataTypes::VecCoord VecCoord;
typedef typename DataTypes::VecDeriv VecDeriv;
typedef typename DataTypes::Coord Coord;
typedef typename DataTypes::CPos CPos;
typedef typename DataTypes::Deriv Deriv;
typedef typename DataTypes::Real Real;
typedef Data<VecCoord> DataVecCoord;
typedef Data<VecDeriv> DataVecDeriv;
typedef helper::vector<unsigned int> SetIndexArray;
typedef sofa::component::topology::PointSubsetData< SetIndexArray > SetIndex;
typedef defaulttype::Quat Quat;
typedef defaulttype::Vector3 Vector3;
typedef typename DataTypes::MatrixDeriv MatrixDeriv;
typedef core::objectmodel::Data<MatrixDeriv> DataMatrixDeriv;
static const unsigned int CoordSize = Coord::total_size;
typedef defaulttype::Mat<3,3,Real> RotationMatrix;
protected:
AffineMovementConstraintInternalData<DataTypes> *data;
friend class AffineMovementConstraintInternalData<DataTypes>;
public :
/// indices of the DOFs of the mesh
SetIndex m_meshIndices;
/// indices of the DOFs the constraint is applied to
SetIndex m_indices;
/// data begin time when the constraint is applied
Data <SReal> m_beginConstraintTime;
/// data end time when the constraint is applied
Data <SReal> m_endConstraintTime;
/// Rotation Matrix of affine transformation
Data<RotationMatrix> m_rotation;
/// Quaternion of affine transformation (for rigid)
Data<Quat> m_quaternion;
/// Translation Matrix of affine transformation
Data<Vector3> m_translation;
/// Draw constrained points
Data <bool> m_drawConstrainedPoints;
/// initial constrained DOFs position
VecCoord x0;
/// final constrained DOFs position
VecCoord xf;
/// initial mesh DOFs position
VecCoord meshPointsX0;
/// final mesh DOFs position
VecCoord meshPointsXf;
protected:
AffineMovementConstraint();
virtual ~AffineMovementConstraint();
public:
//Add or clear constraints
void clearConstraints();
void addConstraint(unsigned int index);
void removeConstraint(unsigned int index);
/// -- Constraint interface
void init();
/// Cancel the possible forces
void projectResponse(const core::MechanicalParams* mparams, DataVecDeriv& resData);
/// Cancel the possible velocities
void projectVelocity(const core::MechanicalParams* mparams, DataVecDeriv& vData);
/// Apply the computed movements to the border mesh points between beginConstraintTime and endConstraintTime
void projectPosition(const core::MechanicalParams* mparams, DataVecCoord& xData);
void projectJacobianMatrix(const core::MechanicalParams* /*mparams*/, DataMatrixDeriv& /* cData */)
{
serr << "projectJacobianMatrix not implemented" << sendl;
}
/// Compute the theoretical final positions
void getFinalPositions (VecCoord& finalPos, DataVecCoord& xData);
// Implement projectMatrix for assembled solver of compliant
virtual void projectMatrix( sofa::defaulttype::BaseMatrix* /*M*/, unsigned /*offset*/ );
/// Draw the constrained points (= border mesh points)
virtual void draw(const core::visual::VisualParams* vparams);
class FCPointHandler : public component::topology::TopologySubsetDataHandler<core::topology::BaseMeshTopology::Point, SetIndexArray >
{
public:
typedef typename AffineMovementConstraint<DataTypes>::SetIndexArray SetIndexArray;
FCPointHandler(AffineMovementConstraint<DataTypes>* _fc, component::topology::PointSubsetData<SetIndexArray>* _data)
: sofa::component::topology::TopologySubsetDataHandler<core::topology::BaseMeshTopology::Point, SetIndexArray >(_data), fc(_fc) {}
using component::topology::TopologySubsetDataHandler<core::topology::BaseMeshTopology::Point, SetIndexArray >::applyDestroyFunction;
void applyDestroyFunction(unsigned int /*index*/, core::objectmodel::Data<value_type>& /*T*/);
bool applyTestCreateFunction(unsigned int /*index*/,
const sofa::helper::vector< unsigned int > & /*ancestors*/,
const sofa::helper::vector< double > & /*coefs*/);
protected:
AffineMovementConstraint<DataTypes> *fc;
};
protected:
/// Pointer to the current topology
sofa::core::topology::BaseMeshTopology* topology;
template <class DataDeriv>
void projectResponseT(const core::MechanicalParams* mparams, DataDeriv& dx);
private:
/// Handler for subset Data
FCPointHandler* pointHandler;
/// Initialize initial positions
void initializeInitialPositions (const SetIndexArray & indices, DataVecCoord& xData, VecCoord& x0);
/// Initialize final positions
void initializeFinalPositions (const SetIndexArray & indices, DataVecCoord& xData, VecCoord& x0 , VecCoord& xf);
/// Apply affine transform
void transform(const SetIndexArray & indices, VecCoord& x0 , VecCoord& xf);
};
#if defined(SOFA_EXTERN_TEMPLATE) && !defined(SOFA_COMPONENT_PROJECTIVECONSTRAINTSET_AFFINEMOVEMENTCONSTRAINT_CPP)
#ifndef SOFA_FLOAT
extern template class SOFA_BOUNDARY_CONDITION_API AffineMovementConstraint<defaulttype::Vec3dTypes>;
extern template class SOFA_BOUNDARY_CONDITION_API AffineMovementConstraint<defaulttype::Rigid3dTypes>;
#endif
#ifndef SOFA_DOUBLE
extern template class SOFA_BOUNDARY_CONDITION_API AffineMovementConstraint<defaulttype::Vec3fTypes>;
extern template class SOFA_BOUNDARY_CONDITION_API AffineMovementConstraint<defaulttype::Rigid3fTypes>;
#endif
#endif
} // namespace projectiveconstraintset
} // namespace component
} // namespace sofa
#endif
|
Anatoscope/sofa
|
modules/SofaBoundaryCondition/AffineMovementConstraint.h
|
C
|
lgpl-2.1
| 8,622
|
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#ifndef GRADIENTMODEL_H
#define GRADIENTMODEL_H
#include <qmlitemnode.h>
#include <QAbstractListModel>
#include <QColor>
#include <QtQml>
class GradientModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(QVariant anchorBackendProperty READ anchorBackend WRITE setAnchorBackend NOTIFY anchorBackendChanged)
Q_PROPERTY(QString gradientPropertyName READ gradientPropertyName WRITE setGradientPropertyName)
Q_PROPERTY(int count READ rowCount)
Q_PROPERTY(bool hasGradient READ hasGradient NOTIFY anchorBackendChanged)
public:
explicit GradientModel(QObject *parent = 0);
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QHash<int, QByteArray> roleNames() const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
Q_INVOKABLE void addStop(qreal position, const QColor &color);
Q_INVOKABLE void addGradient();
Q_INVOKABLE void setColor(int index, const QColor &color);
Q_INVOKABLE void setPosition(int index, qreal positition);
Q_INVOKABLE QColor getColor(int index) const;
Q_INVOKABLE qreal getPosition(int index) const;
Q_INVOKABLE void removeStop(int index);
Q_INVOKABLE void deleteGradient();
static void registerDeclarativeType();
signals:
void anchorBackendChanged();
public slots:
private:
void setupModel();
void setAnchorBackend(const QVariant anchorBackend);
QVariant anchorBackend() const {return QVariant(); }
QString gradientPropertyName() const;
void setGradientPropertyName(const QString &name);
bool hasGradient() const;
private:
QmlDesigner::QmlItemNode m_itemNode;
QString m_gradientPropertyName;
bool m_lock;
};
QML_DECLARE_TYPE(GradientModel)
#endif // GRADIENTMODEL_H
|
omniacreator/qtcreator
|
src/plugins/qmldesigner/components/propertyeditor/gradientmodel.h
|
C
|
lgpl-2.1
| 3,209
|
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** 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 Digia Plc 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 <QtGui>
#include "adddialog.h"
//! [0]
AddDialog::AddDialog(QWidget *parent)
: QDialog(parent)
{
nameLabel = new QLabel("Name");
addressLabel = new QLabel("Address");
okButton = new QPushButton("OK");
cancelButton = new QPushButton("Cancel");
nameText = new QLineEdit;
addressText = new QTextEdit;
QGridLayout *gLayout = new QGridLayout;
gLayout->setColumnStretch(1, 2);
gLayout->addWidget(nameLabel, 0, 0);
gLayout->addWidget(nameText, 0, 1);
gLayout->addWidget(addressLabel, 1, 0, Qt::AlignLeft|Qt::AlignTop);
gLayout->addWidget(addressText, 1, 1, Qt::AlignLeft);
QHBoxLayout *buttonLayout = new QHBoxLayout;
buttonLayout->addWidget(okButton);
buttonLayout->addWidget(cancelButton);
gLayout->addLayout(buttonLayout, 2, 1, Qt::AlignRight);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addLayout(gLayout);
setLayout(mainLayout);
connect(okButton, SIGNAL(clicked()),
this, SLOT(accept()));
connect(cancelButton, SIGNAL(clicked()),
this, SLOT(reject()));
setWindowTitle(tr("Add a Contact"));
}
//! [0]
|
eric100lin/Qt-4.8.6
|
examples/itemviews/addressbook/adddialog.cpp
|
C++
|
lgpl-2.1
| 3,192
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "breakhandler.h"
#include "debuggerinternalconstants.h"
#include "breakpointmarker.h"
#include "debuggeractions.h"
#include "debuggercore.h"
#include "debuggerengine.h"
#include "debuggerstringutils.h"
#include "stackframe.h"
#include <utils/qtcassert.h>
#if USE_BREAK_MODEL_TEST
#include "modeltest.h"
#endif
#include <QDir>
#include <QFileInfo>
#include <QTimerEvent>
#define BREAK_ASSERT(cond, action) if (cond) {} else { action; }
//#define BREAK_ASSERT(cond, action) QTC_ASSERT(cond, action)
//////////////////////////////////////////////////////////////////
//
// BreakHandler
//
//////////////////////////////////////////////////////////////////
namespace Debugger {
namespace Internal {
static QString stateToString(BreakpointState state)
{
switch (state) {
case BreakpointNew:
return BreakHandler::tr("New");
case BreakpointInsertRequested:
return BreakHandler::tr("Insertion requested");
case BreakpointInsertProceeding:
return BreakHandler::tr("Insertion proceeding");
case BreakpointChangeRequested:
return BreakHandler::tr("Change requested");
case BreakpointChangeProceeding:
return BreakHandler::tr("Change proceeding");
case BreakpointInserted:
return BreakHandler::tr("Breakpoint inserted");
case BreakpointRemoveRequested:
return BreakHandler::tr("Removal requested");
case BreakpointRemoveProceeding:
return BreakHandler::tr("Removal proceeding");
case BreakpointDead:
return BreakHandler::tr("Dead");
default:
break;
}
//: Invalid breakpoint state.
return BreakHandler::tr("<invalid state>");
}
static QString msgBreakpointAtSpecialFunc(const char *func)
{
return BreakHandler::tr("Breakpoint at \"%1\"").arg(QString::fromLatin1(func));
}
static QString typeToString(BreakpointType type)
{
switch (type) {
case BreakpointByFileAndLine:
return BreakHandler::tr("Breakpoint by File and Line");
case BreakpointByFunction:
return BreakHandler::tr("Breakpoint by Function");
case BreakpointByAddress:
return BreakHandler::tr("Breakpoint by Address");
case BreakpointAtThrow:
return msgBreakpointAtSpecialFunc("throw");
case BreakpointAtCatch:
return msgBreakpointAtSpecialFunc("catch");
case BreakpointAtFork:
return msgBreakpointAtSpecialFunc("fork");
case BreakpointAtExec:
return msgBreakpointAtSpecialFunc("exec");
//case BreakpointAtVFork:
// return msgBreakpointAtSpecialFunc("vfork");
case BreakpointAtSysCall:
return msgBreakpointAtSpecialFunc("syscall");
case BreakpointAtMain:
return BreakHandler::tr("Breakpoint at Function \"main()\"");
case WatchpointAtAddress:
return BreakHandler::tr("Watchpoint at Address");
case WatchpointAtExpression:
return BreakHandler::tr("Watchpoint at Expression");
case BreakpointOnQmlSignalHandler:
return BreakHandler::tr("Breakpoint on QML Signal Handler");
case BreakpointAtJavaScriptThrow:
return BreakHandler::tr("Breakpoint at JavaScript throw");
case UnknownType:
break;
}
return BreakHandler::tr("Unknown Breakpoint Type");
}
BreakHandler::BreakHandler()
: m_syncTimerId(-1)
{
#if USE_BREAK_MODEL_TEST
new ModelTest(this, 0);
#endif
}
BreakHandler::~BreakHandler()
{}
QIcon BreakHandler::breakpointIcon()
{
static QIcon icon(_(":/debugger/images/breakpoint_16.png"));
return icon;
}
QIcon BreakHandler::disabledBreakpointIcon()
{
static QIcon icon(_(":/debugger/images/breakpoint_disabled_16.png"));
return icon;
}
QIcon BreakHandler::pendingBreakpointIcon()
{
static QIcon icon(_(":/debugger/images/breakpoint_pending_16.png"));
return icon;
}
QIcon BreakHandler::watchpointIcon()
{
static QIcon icon(_(":/debugger/images/watchpoint.png"));
return icon;
}
QIcon BreakHandler::tracepointIcon()
{
static QIcon icon(_(":/debugger/images/tracepoint.png"));
return icon;
}
QIcon BreakHandler::emptyIcon()
{
static QIcon icon(_(":/debugger/images/breakpoint_pending_16.png"));
//static QIcon icon(_(":/debugger/images/watchpoint.png"));
//static QIcon icon(_(":/debugger/images/debugger_empty_14.png"));
return icon;
}
static inline bool fileNameMatch(const QString &f1, const QString &f2)
{
#ifdef Q_OS_WIN
return f1.compare(f2, Qt::CaseInsensitive) == 0;
#else
return f1 == f2;
#endif
}
static bool isSimilarTo(const BreakpointParameters &data, const BreakpointResponse &needle)
{
// Clear hit.
// Clear miss.
if (needle.type != UnknownType && data.type != UnknownType
&& data.type != needle.type)
return false;
// Clear hit.
if (data.address && data.address == needle.address)
return true;
// At least at a position we were looking for.
// FIXME: breaks multiple breakpoints at the same location
if (!data.fileName.isEmpty()
&& fileNameMatch(data.fileName, needle.fileName)
&& data.lineNumber == needle.lineNumber)
return true;
// At least at a position we were looking for.
// FIXME: breaks multiple breakpoints at the same location
if (!data.fileName.isEmpty()
&& fileNameMatch(data.fileName, needle.fileName)
&& data.lineNumber == needle.lineNumber)
return true;
return false;
}
BreakpointModelId BreakHandler::findSimilarBreakpoint(const BreakpointResponse &needle) const
{
// Search a breakpoint we might refer to.
ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
for ( ; it != et; ++it) {
const BreakpointModelId id = it.key();
const BreakpointParameters &data = it->data;
const BreakpointResponse &response = it->response;
//qDebug() << "COMPARING " << data.toString() << " WITH " << needle.toString();
if (response.id.isValid() && response.id.majorPart() == needle.id.majorPart())
return id;
if (isSimilarTo(data, needle))
return id;
}
return BreakpointModelId();
}
BreakpointModelId BreakHandler::findBreakpointByResponseId(const BreakpointResponseId &id) const
{
ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
for ( ; it != et; ++it)
if (it->response.id.majorPart() == id.majorPart())
return it.key();
return BreakpointModelId();
}
BreakpointModelId BreakHandler::findBreakpointByFunction(const QString &functionName) const
{
ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
for ( ; it != et; ++it)
if (it->data.functionName == functionName)
return it.key();
return BreakpointModelId();
}
BreakpointModelId BreakHandler::findBreakpointByAddress(quint64 address) const
{
ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
for ( ; it != et; ++it)
if (it->data.address == address || it->response.address == address)
return it.key();
return BreakpointModelId();
}
BreakpointModelId BreakHandler::findBreakpointByFileAndLine(const QString &fileName,
int lineNumber, bool useMarkerPosition)
{
ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
for ( ; it != et; ++it)
if (it->isLocatedAt(fileName, lineNumber, useMarkerPosition))
return it.key();
return BreakpointModelId();
}
const BreakpointParameters &BreakHandler::breakpointData(BreakpointModelId id) const
{
static BreakpointParameters dummy;
ConstIterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return dummy);
return it->data;
}
BreakpointModelId BreakHandler::findWatchpoint(const BreakpointParameters &data) const
{
ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
for ( ; it != et; ++it)
if (it->data.isWatchpoint()
&& it->data.address == data.address
&& it->data.size == data.size
&& it->data.expression == data.expression
&& it->data.bitpos == data.bitpos)
return it.key();
return BreakpointModelId();
}
void BreakHandler::saveBreakpoints()
{
const QString one = _("1");
//qDebug() << "SAVING BREAKPOINTS...";
QTC_ASSERT(debuggerCore(), return);
QList<QVariant> list;
ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
for ( ; it != et; ++it) {
const BreakpointParameters &data = it->data;
QMap<QString, QVariant> map;
if (data.type != BreakpointByFileAndLine)
map.insert(_("type"), data.type);
if (!data.fileName.isEmpty())
map.insert(_("filename"), data.fileName);
if (data.lineNumber)
map.insert(_("linenumber"), data.lineNumber);
if (!data.functionName.isEmpty())
map.insert(_("funcname"), data.functionName);
if (data.address)
map.insert(_("address"), data.address);
if (!data.condition.isEmpty())
map.insert(_("condition"), data.condition);
if (data.ignoreCount)
map.insert(_("ignorecount"), data.ignoreCount);
if (data.threadSpec >= 0)
map.insert(_("threadspec"), data.threadSpec);
if (!data.enabled)
map.insert(_("disabled"), one);
if (data.pathUsage != BreakpointPathUsageEngineDefault)
map.insert(_("usefullpath"), QString::number(data.pathUsage));
if (data.tracepoint)
map.insert(_("tracepoint"), one);
if (!data.module.isEmpty())
map.insert(_("module"), data.module);
if (!data.command.isEmpty())
map.insert(_("command"), data.command);
if (!data.expression.isEmpty())
map.insert(_("expression"), data.expression);
if (!data.message.isEmpty())
map.insert(_("message"), data.message);
list.append(map);
}
debuggerCore()->setSessionValue(QLatin1String("Breakpoints"), list);
//qDebug() << "SAVED BREAKPOINTS" << this << list.size();
}
void BreakHandler::loadBreakpoints()
{
QTC_ASSERT(debuggerCore(), return);
//qDebug() << "LOADING BREAKPOINTS...";
QVariant value = debuggerCore()->sessionValue(QLatin1String("Breakpoints"));
QList<QVariant> list = value.toList();
//clear();
foreach (const QVariant &var, list) {
const QMap<QString, QVariant> map = var.toMap();
BreakpointParameters data(BreakpointByFileAndLine);
QVariant v = map.value(_("filename"));
if (v.isValid())
data.fileName = v.toString();
v = map.value(_("linenumber"));
if (v.isValid())
data.lineNumber = v.toString().toInt();
v = map.value(_("condition"));
if (v.isValid())
data.condition = v.toString().toLatin1();
v = map.value(_("address"));
if (v.isValid())
data.address = v.toString().toULongLong();
v = map.value(_("ignorecount"));
if (v.isValid())
data.ignoreCount = v.toString().toInt();
v = map.value(_("threadspec"));
if (v.isValid())
data.threadSpec = v.toString().toInt();
v = map.value(_("funcname"));
if (v.isValid())
data.functionName = v.toString();
v = map.value(_("disabled"));
if (v.isValid())
data.enabled = !v.toInt();
v = map.value(_("usefullpath"));
if (v.isValid())
data.pathUsage = static_cast<BreakpointPathUsage>(v.toInt());
v = map.value(_("tracepoint"));
if (v.isValid())
data.tracepoint = bool(v.toInt());
v = map.value(_("type"));
if (v.isValid() && v.toInt() != UnknownType)
data.type = BreakpointType(v.toInt());
v = map.value(_("module"));
if (v.isValid())
data.module = v.toString();
v = map.value(_("command"));
if (v.isValid())
data.command = v.toString();
v = map.value(_("expression"));
if (v.isValid())
data.expression = v.toString();
v = map.value(_("message"));
if (v.isValid())
data.message = v.toString();
if (data.isValid()) {
appendBreakpoint(data);
} else {
qWarning("Not restoring invalid breakpoint: %s", qPrintable(data.toString()));
}
}
//qDebug() << "LOADED BREAKPOINTS" << this << list.size();
}
void BreakHandler::updateMarkers()
{
Iterator it = m_storage.begin(), et = m_storage.end();
for ( ; it != et; ++it)
it->updateMarker(it.key());
}
QVariant BreakHandler::headerData(int section,
Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
static QString headers[] = {
tr("Number"), tr("Function"), tr("File"), tr("Line"),
tr("Address"), tr("Condition"), tr("Ignore"), tr("Threads")
};
return headers[section];
}
return QVariant();
}
BreakpointModelId BreakHandler::findBreakpointByIndex(const QModelIndex &index) const
{
//qDebug() << "FIND: " << index <<
// BreakpointId::fromInternalId(index.internalId());
return BreakpointModelId::fromInternalId(index.internalId());
}
BreakpointModelIds BreakHandler::findBreakpointsByIndex(const QList<QModelIndex> &list) const
{
QSet<BreakpointModelId> ids;
foreach (const QModelIndex &index, list)
ids.insert(findBreakpointByIndex(index));
return ids.toList();
}
Qt::ItemFlags BreakHandler::flags(const QModelIndex &index) const
{
// switch (index.column()) {
// //case 0:
// // return Qt::ItemIsUserCheckable | Qt::ItemIsEnabled;
// default:
return QAbstractItemModel::flags(index);
// }
}
QString BreakHandler::displayFromThreadSpec(int spec)
{
return spec == -1 ? BreakHandler::tr("(all)") : QString::number(spec);
}
int BreakHandler::threadSpecFromDisplay(const QString &str)
{
bool ok = false;
int result = str.toInt(&ok);
return ok ? result : -1;
}
QModelIndex BreakHandler::createIndex(int row, int column, quint32 id) const
{
return QAbstractItemModel::createIndex(row, column, id);
}
QModelIndex BreakHandler::createIndex(int row, int column, void *ptr) const
{
QTC_CHECK(false); // This function is not used.
return QAbstractItemModel::createIndex(row, column, ptr);
}
int BreakHandler::columnCount(const QModelIndex &idx) const
{
if (idx.column() > 0)
return 0;
const BreakpointModelId id = findBreakpointByIndex(idx);
return id.isMinor() ? 0 : 8;
}
int BreakHandler::rowCount(const QModelIndex &idx) const
{
if (idx.column() > 0)
return 0;
if (!idx.isValid())
return m_storage.size();
const BreakpointModelId id = findBreakpointByIndex(idx);
if (id.isMajor())
return m_storage.value(id).subItems.size();
return 0;
}
QModelIndex BreakHandler::index(int row, int col, const QModelIndex &parent) const
{
if (row < 0 || col < 0)
return QModelIndex();
if (parent.column() > 0)
return QModelIndex();
BreakpointModelId id = findBreakpointByIndex(parent);
if (id.isMajor()) {
ConstIterator it = m_storage.find(id);
if (row >= it->subItems.size())
return QModelIndex();
BreakpointModelId sub = id.child(row);
return createIndex(row, col, sub.toInternalId());
}
if (id.isMinor())
return QModelIndex();
QTC_ASSERT(!id.isValid(), return QModelIndex());
if (row >= m_storage.size())
return QModelIndex();
id = at(row);
return createIndex(row, col, id.toInternalId());
}
QModelIndex BreakHandler::parent(const QModelIndex &idx) const
{
if (!idx.isValid())
return QModelIndex();
BreakpointModelId id = findBreakpointByIndex(idx);
if (id.isMajor())
return QModelIndex();
if (id.isMinor()) {
BreakpointModelId pid = id.parent();
int row = indexOf(pid);
return createIndex(row, 0, pid.toInternalId());
}
return QModelIndex();
}
QVariant BreakHandler::data(const QModelIndex &mi, int role) const
{
static const QString empty = QString(QLatin1Char('-'));
if (!mi.isValid())
return QVariant();
BreakpointModelId id = findBreakpointByIndex(mi);
BreakpointModelId pid = id;
if (id.isMinor())
pid = id.parent();
ConstIterator it = m_storage.find(pid);
QTC_ASSERT(it != m_storage.end(), return QVariant());
const BreakpointParameters &data = it->data;
const BreakpointResponse &response = it->response;
bool orig = false;
switch (it->state) {
case BreakpointInsertRequested:
case BreakpointInsertProceeding:
case BreakpointChangeRequested:
case BreakpointChangeProceeding:
case BreakpointInserted:
case BreakpointRemoveRequested:
case BreakpointRemoveProceeding:
break;
case BreakpointNew:
case BreakpointDead:
orig = true;
break;
};
if (id.isMinor()) {
QTC_ASSERT(id.minorPart() <= it->subItems.size(), return QVariant());
const BreakpointResponse &res = it->subItems.at(id.minorPart() - 1);
switch (mi.column()) {
case 0:
if (role == Qt::DisplayRole)
return id.toString();
case 1:
if (role == Qt::DisplayRole)
return res.functionName;
case 4:
if (role == Qt::DisplayRole)
if (res.address)
return QString::fromLatin1("0x%1").arg(res.address, 0, 16);
}
return QVariant();
}
switch (mi.column()) {
case 0:
if (role == Qt::DisplayRole)
return id.toString();
if (role == Qt::DecorationRole)
return it->icon();
break;
case 1:
if (role == Qt::DisplayRole) {
if (!response.functionName.isEmpty())
return response.functionName;
if (!data.functionName.isEmpty())
return data.functionName;
if (data.type == BreakpointAtMain
|| data.type == BreakpointAtThrow
|| data.type == BreakpointAtCatch
|| data.type == BreakpointAtFork
|| data.type == BreakpointAtExec
//|| data.type == BreakpointAtVFork
|| data.type == BreakpointAtSysCall)
return typeToString(data.type);
if (data.type == WatchpointAtAddress) {
quint64 address = response.address ? response.address : data.address;
return tr("Data at 0x%1").arg(address, 0, 16);
}
if (data.type == WatchpointAtExpression) {
QString expression = !response.expression.isEmpty()
? response.expression : data.expression;
return tr("Data at %1").arg(expression);
}
return empty;
}
break;
case 2:
if (role == Qt::DisplayRole) {
QString str;
if (!response.fileName.isEmpty())
str = response.fileName;
if (str.isEmpty() && !data.fileName.isEmpty())
str = data.fileName;
if (str.isEmpty()) {
QString s = QFileInfo(str).fileName();
if (!s.isEmpty())
str = s;
}
// FIXME: better?
//if (data.multiple && str.isEmpty() && !response.fileName.isEmpty())
// str = response.fileName;
if (!str.isEmpty())
return QDir::toNativeSeparators(str);
return empty;
}
break;
case 3:
if (role == Qt::DisplayRole) {
if (response.lineNumber > 0)
return response.lineNumber;
if (data.lineNumber > 0)
return data.lineNumber;
return empty;
}
if (role == Qt::UserRole + 1)
return data.lineNumber;
break;
case 4:
if (role == Qt::DisplayRole) {
const quint64 address = orig ? data.address : response.address;
if (address)
return QString::fromLatin1("0x%1").arg(address, 0, 16);
return QVariant();
}
break;
case 5:
if (role == Qt::DisplayRole)
return orig ? data.condition : response.condition;
if (role == Qt::ToolTipRole)
return tr("Breakpoint will only be hit if this condition is met.");
if (role == Qt::UserRole + 1)
return data.condition;
break;
case 6:
if (role == Qt::DisplayRole) {
const int ignoreCount =
orig ? data.ignoreCount : response.ignoreCount;
return ignoreCount ? QVariant(ignoreCount) : QVariant(QString());
}
if (role == Qt::ToolTipRole)
return tr("Breakpoint will only be hit after being ignored so many times.");
if (role == Qt::UserRole + 1)
return data.ignoreCount;
break;
case 7:
if (role == Qt::DisplayRole)
return displayFromThreadSpec(orig ? data.threadSpec : response.threadSpec);
if (role == Qt::ToolTipRole)
return tr("Breakpoint will only be hit in the specified thread(s).");
if (role == Qt::UserRole + 1)
return displayFromThreadSpec(data.threadSpec);
break;
}
switch (role) {
case Qt::ToolTipRole:
if (debuggerCore()->boolSetting(UseToolTipsInBreakpointsView))
return QVariant(it->toToolTip());
break;
}
return QVariant();
}
#define GETTER(type, getter) \
type BreakHandler::getter(BreakpointModelId id) const \
{ \
ConstIterator it = m_storage.find(id); \
BREAK_ASSERT(it != m_storage.end(), \
qDebug() << "ID" << id << "NOT KNOWN"; \
return type()); \
return it->data.getter; \
}
#define SETTER(type, getter, setter) \
void BreakHandler::setter(BreakpointModelId id, const type &value) \
{ \
Iterator it = m_storage.find(id); \
BREAK_ASSERT(it != m_storage.end(), \
qDebug() << "ID" << id << "NOT KNOWN"; return); \
if (it->data.getter == value) \
return; \
it->data.getter = value; \
if (it->state != BreakpointNew) { \
it->state = BreakpointChangeRequested; \
scheduleSynchronization(); \
} \
}
#define PROPERTY(type, getter, setter) \
GETTER(type, getter) \
SETTER(type, getter, setter)
PROPERTY(BreakpointPathUsage, pathUsage, setPathUsage)
PROPERTY(QString, fileName, setFileName)
PROPERTY(QString, functionName, setFunctionName)
PROPERTY(BreakpointType, type, setType)
PROPERTY(int, threadSpec, setThreadSpec)
PROPERTY(QByteArray, condition, setCondition)
GETTER(int, lineNumber)
PROPERTY(quint64, address, setAddress)
PROPERTY(QString, expression, setExpression)
PROPERTY(QString, message, setMessage)
PROPERTY(int, ignoreCount, setIgnoreCount)
bool BreakHandler::isEnabled(BreakpointModelId id) const
{
ConstIterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return false);
return it->data.enabled;
}
void BreakHandler::setEnabled(BreakpointModelId id, bool on)
{
Iterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return);
//qDebug() << "SET ENABLED: " << id << it->data.isEnabled() << on;
if (it->data.enabled == on)
return;
it->data.enabled = on;
it->updateMarkerIcon();
if (it->engine) {
it->state = BreakpointChangeRequested;
scheduleSynchronization();
}
}
bool BreakHandler::isWatchpoint(BreakpointModelId id) const
{
ConstIterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return false);
return it->data.isWatchpoint();
}
bool BreakHandler::isTracepoint(BreakpointModelId id) const
{
ConstIterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return false);
return it->data.tracepoint;
}
bool BreakHandler::needsChildren(BreakpointModelId id) const
{
ConstIterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return false);
return it->response.multiple && it->subItems.isEmpty();
}
void BreakHandler::setTracepoint(BreakpointModelId id, bool on)
{
Iterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return);
if (it->data.tracepoint == on)
return;
it->data.tracepoint = on;
it->updateMarkerIcon();
if (it->engine) {
it->state = BreakpointChangeRequested;
scheduleSynchronization();
}
}
void BreakHandler::setMarkerFileAndLine(BreakpointModelId id,
const QString &fileName, int lineNumber)
{
Iterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(),
qDebug() << "MARKER_FILE_AND_LINE: " << id; return);
if (it->response.fileName == fileName && it->response.lineNumber == lineNumber)
return;
it->response.fileName = fileName;
it->response.lineNumber = lineNumber;
it->destroyMarker();
it->updateMarker(id);
emit layoutChanged();
}
BreakpointState BreakHandler::state(BreakpointModelId id) const
{
ConstIterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(),
qDebug() << "STATE: " << id; return BreakpointDead);
return it->state;
}
DebuggerEngine *BreakHandler::engine(BreakpointModelId id) const
{
ConstIterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), qDebug() << id; return 0);
return it->engine;
}
void BreakHandler::setEngine(BreakpointModelId id, DebuggerEngine *value)
{
Iterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), qDebug() << "SET ENGINE" << id; return);
QTC_ASSERT(it->state == BreakpointNew, qDebug() << "STATE: " << it->state <<id);
QTC_ASSERT(!it->engine, qDebug() << "NO ENGINE" << id; return);
it->engine = value;
it->state = BreakpointInsertRequested;
it->response = BreakpointResponse();
it->updateMarker(id);
scheduleSynchronization();
}
static bool isAllowedTransition(BreakpointState from, BreakpointState to)
{
switch (from) {
case BreakpointNew:
return to == BreakpointInsertRequested;
case BreakpointInsertRequested:
return to == BreakpointInsertProceeding;
case BreakpointInsertProceeding:
return to == BreakpointInserted
|| to == BreakpointDead
|| to == BreakpointChangeRequested
|| to == BreakpointRemoveRequested;
case BreakpointChangeRequested:
return to == BreakpointChangeProceeding;
case BreakpointChangeProceeding:
return to == BreakpointInserted
|| to == BreakpointDead;
case BreakpointInserted:
return to == BreakpointChangeRequested
|| to == BreakpointRemoveRequested;
case BreakpointRemoveRequested:
return to == BreakpointRemoveProceeding;
case BreakpointRemoveProceeding:
return to == BreakpointDead;
case BreakpointDead:
return false;
}
qDebug() << "UNKNOWN BREAKPOINT STATE:" << from;
return false;
}
bool BreakHandler::isEngineRunning(BreakpointModelId id) const
{
if (const DebuggerEngine *e = engine(id)) {
const DebuggerState state = e->state();
return state != DebuggerFinished && state != DebuggerNotReady;
}
return false;
}
void BreakHandler::setState(BreakpointModelId id, BreakpointState state)
{
Iterator it = m_storage.find(id);
//qDebug() << "BREAKPOINT STATE TRANSITION, ID: " << id
// << " FROM: " << it->state << " TO: " << state;
BREAK_ASSERT(it != m_storage.end(), qDebug() << id; return);
QTC_ASSERT(isAllowedTransition(it->state, state),
qDebug() << "UNEXPECTED BREAKPOINT STATE TRANSITION"
<< it->state << state);
if (it->state == state) {
qDebug() << "STATE UNCHANGED: " << id << state;
return;
}
it->state = state;
// FIXME: updateMarker() should recognize the need for icon changes.
if (state == BreakpointInserted) {
it->destroyMarker();
it->updateMarker(id);
}
layoutChanged();
}
void BreakHandler::notifyBreakpointChangeAfterInsertNeeded(BreakpointModelId id)
{
QTC_ASSERT(state(id) == BreakpointInsertProceeding, qDebug() << state(id));
setState(id, BreakpointChangeRequested);
}
void BreakHandler::notifyBreakpointInsertProceeding(BreakpointModelId id)
{
QTC_ASSERT(state(id) == BreakpointInsertRequested, qDebug() << state(id));
setState(id, BreakpointInsertProceeding);
}
void BreakHandler::notifyBreakpointInsertOk(BreakpointModelId id)
{
QTC_ASSERT(state(id) == BreakpointInsertProceeding, qDebug() << state(id));
setState(id, BreakpointInserted);
ConstIterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return);
}
void BreakHandler::notifyBreakpointInsertFailed(BreakpointModelId id)
{
QTC_ASSERT(state(id) == BreakpointInsertProceeding, qDebug() << state(id));
setState(id, BreakpointDead);
}
void BreakHandler::notifyBreakpointRemoveProceeding(BreakpointModelId id)
{
QTC_ASSERT(state(id) == BreakpointRemoveRequested, qDebug() << state(id));
setState(id, BreakpointRemoveProceeding);
}
void BreakHandler::notifyBreakpointRemoveOk(BreakpointModelId id)
{
QTC_ASSERT(state(id) == BreakpointRemoveProceeding, qDebug() << state(id));
setState(id, BreakpointDead);
cleanupBreakpoint(id);
}
void BreakHandler::notifyBreakpointRemoveFailed(BreakpointModelId id)
{
QTC_ASSERT(state(id) == BreakpointRemoveProceeding, qDebug() << state(id));
setState(id, BreakpointDead);
cleanupBreakpoint(id);
}
void BreakHandler::notifyBreakpointChangeProceeding(BreakpointModelId id)
{
QTC_ASSERT(state(id) == BreakpointChangeRequested, qDebug() << state(id));
setState(id, BreakpointChangeProceeding);
}
void BreakHandler::notifyBreakpointChangeOk(BreakpointModelId id)
{
QTC_ASSERT(state(id) == BreakpointChangeProceeding, qDebug() << state(id));
setState(id, BreakpointInserted);
}
void BreakHandler::notifyBreakpointChangeFailed(BreakpointModelId id)
{
QTC_ASSERT(state(id) == BreakpointChangeProceeding, qDebug() << state(id));
setState(id, BreakpointDead);
}
void BreakHandler::notifyBreakpointReleased(BreakpointModelId id)
{
//QTC_ASSERT(state(id) == BreakpointChangeProceeding, qDebug() << state(id));
Iterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return);
it->state = BreakpointNew;
it->engine = 0;
it->response = BreakpointResponse();
it->subItems.clear();
it->destroyMarker();
it->updateMarker(id);
if (it->data.type == WatchpointAtAddress
|| it->data.type == WatchpointAtExpression
|| it->data.type == BreakpointByAddress)
it->data.enabled = false;
layoutChanged();
}
void BreakHandler::notifyBreakpointAdjusted(BreakpointModelId id,
const BreakpointParameters &data)
{
QTC_ASSERT(state(id) == BreakpointInserted, qDebug() << state(id));
Iterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return);
it->data = data;
//if (it->needsChange())
// setState(id, BreakpointChangeRequested);
}
void BreakHandler::notifyBreakpointNeedsReinsertion(BreakpointModelId id)
{
QTC_ASSERT(state(id) == BreakpointChangeProceeding, qDebug() << state(id));
Iterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return);
it->state = BreakpointInsertRequested;
}
void BreakHandler::removeAlienBreakpoint(BreakpointModelId id)
{
Iterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return);
it->state = BreakpointDead;
cleanupBreakpoint(id);
}
void BreakHandler::removeBreakpoint(BreakpointModelId id)
{
Iterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return);
switch (it->state) {
case BreakpointRemoveRequested:
break;
case BreakpointInserted:
case BreakpointInsertProceeding:
setState(id, BreakpointRemoveRequested);
scheduleSynchronization();
break;
case BreakpointNew:
it->state = BreakpointDead;
cleanupBreakpoint(id);
break;
default:
qWarning("Warning: Cannot remove breakpoint %s in state '%s'.",
qPrintable(id.toString()), qPrintable(stateToString(it->state)));
it->state = BreakpointRemoveRequested;
break;
}
}
// Ok to be not thread-safe. The order does not matter and only the gui
// produces authoritative ids.
static int currentId = 0;
void BreakHandler::appendBreakpoint(const BreakpointParameters &data)
{
if (!data.isValid()) {
qWarning("Not adding invalid breakpoint: %s", qPrintable(data.toString()));
return;
}
BreakpointModelId id(++currentId);
const int row = m_storage.size();
beginInsertRows(QModelIndex(), row, row);
Iterator it = m_storage.insert(id, BreakpointItem());
endInsertRows();
// Create marker after copy is inserted into hash.
it->data = data;
it->updateMarker(id);
scheduleSynchronization();
}
void BreakHandler::handleAlienBreakpoint(const BreakpointResponse &response, DebuggerEngine *engine)
{
BreakpointModelId id = findSimilarBreakpoint(response);
if (id.isValid()) {
if (response.id.isMinor())
insertSubBreakpoint(id, response);
else
setResponse(id, response);
} else {
BreakpointModelId id(++currentId);
const int row = m_storage.size();
beginInsertRows(QModelIndex(), row, row);
Iterator it = m_storage.insert(id, BreakpointItem());
endInsertRows();
it->data = response;
it->response = response;
it->state = BreakpointInserted;
it->engine = engine;
it->updateMarker(id);
layoutChanged();
scheduleSynchronization();
}
}
BreakpointModelId BreakHandler::at(int n) const
{
if (n < 0 || n >= m_storage.size())
return BreakpointModelId();
ConstIterator it = m_storage.constBegin();
for ( ; --n >= 0; ++it)
;
return it.key();
}
int BreakHandler::indexOf(BreakpointModelId id) const
{
int row = 0;
ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
for ( ; it != et; ++it, ++row)
if (it.key() == id)
return row;
return -1;
}
void BreakHandler::insertSubBreakpoint(BreakpointModelId id,
const BreakpointResponse &data)
{
QTC_ASSERT(data.id.isMinor(), return);
QTC_ASSERT(id.isMajor(), return);
Iterator it = m_storage.find(id);
if (it == m_storage.end()) {
qDebug() << "FAILED: " << id.toString();
for (ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
it != et; ++it) {
qDebug() << " ID: " << it->response.id.toString();
qDebug() << " DATA: " << it->data.toString();
qDebug() << " RESP: " << it->response.toString();
}
}
QTC_ASSERT(it != m_storage.end(), return);
int minorPart = data.id.minorPart();
int pos = -1;
for (int i = 0; i != it->subItems.size(); ++i) {
if (it->subItems.at(i).id.minorPart() == minorPart) {
pos = i;
break;
}
}
if (pos == -1) {
// This is a new sub-breakpoint.
//qDebug() << "NEW ID" << id;
int row = indexOf(id);
QTC_ASSERT(row != -1, return);
QModelIndex idx = createIndex(row, 0, id.toInternalId());
beginInsertRows(idx, it->subItems.size(), it->subItems.size());
it->subItems.append(data);
endInsertRows();
} else {
// This modifies an existing sub-breakpoint.
//qDebug() << "EXISTING ID" << id;
it->subItems[pos] = data;
layoutChanged();
}
}
void BreakHandler::saveSessionData()
{
saveBreakpoints();
}
void BreakHandler::loadSessionData()
{
m_storage.clear();
reset();
loadBreakpoints();
}
void BreakHandler::removeSessionData()
{
Iterator it = m_storage.begin(), et = m_storage.end();
for ( ; it != et; ++it)
it->destroyMarker();
m_storage.clear();
reset();
}
void BreakHandler::breakByFunction(const QString &functionName)
{
// One breakpoint per function is enough for now. This does not handle
// combinations of multiple conditions and ignore counts, though.
ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
for ( ; it != et; ++it) {
const BreakpointParameters &data = it->data;
if (data.functionName == functionName
&& data.condition.isEmpty()
&& data.ignoreCount == 0)
return;
}
BreakpointParameters data(BreakpointByFunction);
data.functionName = functionName;
appendBreakpoint(data);
}
QIcon BreakHandler::icon(BreakpointModelId id) const
{
ConstIterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), qDebug() << "NO ICON FOR ID" << id;
return pendingBreakpointIcon());
return it->icon();
}
void BreakHandler::scheduleSynchronization()
{
if (m_syncTimerId == -1)
m_syncTimerId = startTimer(10);
}
void BreakHandler::timerEvent(QTimerEvent *event)
{
QTC_ASSERT(event->timerId() == m_syncTimerId, return);
killTimer(m_syncTimerId);
m_syncTimerId = -1;
saveBreakpoints(); // FIXME: remove?
debuggerCore()->synchronizeBreakpoints();
}
void BreakHandler::gotoLocation(BreakpointModelId id) const
{
ConstIterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return);
DebuggerEngine *engine = debuggerCore()->currentEngine();
if (it->data.type == BreakpointByAddress) {
if (engine)
engine->gotoLocation(it->data.address);
} else {
if (engine)
engine->gotoLocation(
Location(it->markerFileName(), it->markerLineNumber(), false));
}
}
void BreakHandler::updateFileNameFromMarker(BreakpointModelId id, const QString &fileName)
{
Iterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return);
it->data.fileName = fileName;
emit layoutChanged();
}
void BreakHandler::updateLineNumberFromMarker(BreakpointModelId id, int lineNumber)
{
Iterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return);
// Ignore updates to the "real" line number while the debugger is
// running, as this can be triggered by moving the breakpoint to
// the next line that generated code.
if (it->data.lineNumber == lineNumber)
; // Nothing
else if (isEngineRunning(id))
it->data.lineNumber += lineNumber - it->response.lineNumber;
else
it->data.lineNumber = lineNumber;
it->updateMarker(id);
emit layoutChanged();
}
BreakpointModelIds BreakHandler::allBreakpointIds() const
{
BreakpointModelIds ids;
ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
for ( ; it != et; ++it)
ids.append(it.key());
return ids;
}
BreakpointModelIds BreakHandler::unclaimedBreakpointIds() const
{
return engineBreakpointIds(0);
}
BreakpointModelIds BreakHandler::engineBreakpointIds(DebuggerEngine *engine) const
{
BreakpointModelIds ids;
ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
for ( ; it != et; ++it)
if (it->engine == engine)
ids.append(it.key());
return ids;
}
QStringList BreakHandler::engineBreakpointPaths(DebuggerEngine *engine) const
{
QSet<QString> set;
ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
for ( ; it != et; ++it) {
if (it->engine == engine) {
if (it->data.type == BreakpointByFileAndLine)
set.insert(QFileInfo(it->data.fileName).dir().path());
}
}
return set.toList();
}
void BreakHandler::cleanupBreakpoint(BreakpointModelId id)
{
QTC_ASSERT(state(id) == BreakpointDead, qDebug() << state(id));
BreakpointItem item = m_storage.take(id);
item.destroyMarker();
layoutChanged();
}
const BreakpointResponse &BreakHandler::response(BreakpointModelId id) const
{
static BreakpointResponse dummy;
ConstIterator it = m_storage.find(id);
if (it == m_storage.end()) {
qDebug() << "NO RESPONSE FOR " << id;
return dummy;
}
return it->response;
}
bool BreakHandler::needsChange(BreakpointModelId id) const
{
ConstIterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return false);
return it->needsChange();
}
void BreakHandler::setResponse(BreakpointModelId id,
const BreakpointResponse &response)
{
Iterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return);
it->response = response;
it->destroyMarker();
it->updateMarker(id);
// Take over corrected values from response.
if ((it->data.type == BreakpointByFileAndLine
|| it->data.type == BreakpointByFunction)
&& !response.module.isEmpty())
it->data.module = response.module;
}
void BreakHandler::changeBreakpointData(BreakpointModelId id,
const BreakpointParameters &data, BreakpointParts parts)
{
Q_UNUSED(parts);
Iterator it = m_storage.find(id);
BREAK_ASSERT(it != m_storage.end(), return);
if (data == it->data)
return;
it->data = data;
it->destroyMarker();
it->updateMarker(id);
layoutChanged();
if (it->needsChange() && it->engine && it->state != BreakpointNew) {
setState(id, BreakpointChangeRequested);
scheduleSynchronization();
}
}
//////////////////////////////////////////////////////////////////
//
// Storage
//
//////////////////////////////////////////////////////////////////
BreakHandler::BreakpointItem::BreakpointItem()
: state(BreakpointNew), engine(0), marker(0)
{}
void BreakHandler::BreakpointItem::destroyMarker()
{
BreakpointMarker *m = marker;
marker = 0;
delete m;
}
QString BreakHandler::BreakpointItem::markerFileName() const
{
// Some heuristics to find a "good" file name.
if (!data.fileName.isEmpty()) {
QFileInfo fi(data.fileName);
if (fi.exists())
return fi.absoluteFilePath();
}
if (!response.fileName.isEmpty()) {
QFileInfo fi(response.fileName);
if (fi.exists())
return fi.absoluteFilePath();
}
if (response.fileName.endsWith(data.fileName))
return response.fileName;
if (data.fileName.endsWith(response.fileName))
return data.fileName;
return response.fileName.size() > data.fileName.size()
? response.fileName : data.fileName;
}
int BreakHandler::BreakpointItem::markerLineNumber() const
{
return response.lineNumber ? response.lineNumber : data.lineNumber;
}
static void formatAddress(QTextStream &str, quint64 address)
{
if (address) {
str << "0x";
str.setIntegerBase(16);
str << address;
str.setIntegerBase(10);
}
}
bool BreakHandler::BreakpointItem::needsChange() const
{
if (!data.conditionsMatch(response.condition))
return true;
if (data.ignoreCount != response.ignoreCount)
return true;
if (data.enabled != response.enabled)
return true;
if (data.threadSpec != response.threadSpec)
return true;
if (data.command != response.command)
return true;
if (data.lineNumber != response.lineNumber)
return true;
return false;
}
bool BreakHandler::BreakpointItem::isLocatedAt
(const QString &fileName, int lineNumber, bool useMarkerPosition) const
{
int line = useMarkerPosition ? response.lineNumber : data.lineNumber;
return lineNumber == line
&& (fileNameMatch(fileName, response.fileName)
|| fileNameMatch(fileName, markerFileName()));
}
void BreakHandler::BreakpointItem::updateMarkerIcon()
{
if (marker) {
marker->setIcon(icon());
marker->updateMarker();
}
}
void BreakHandler::BreakpointItem::updateMarker(BreakpointModelId id)
{
QString file = markerFileName();
int line = markerLineNumber();
if (marker && (file != marker->fileName() || line != marker->lineNumber()))
destroyMarker();
if (!marker && !file.isEmpty() && line > 0) {
marker = new BreakpointMarker(id, file, line);
marker->init();
}
}
QIcon BreakHandler::BreakpointItem::icon() const
{
// FIXME: This seems to be called on each cursor blink as soon as the
// cursor is near a line with a breakpoint marker (+/- 2 lines or so).
if (data.isTracepoint())
return BreakHandler::tracepointIcon();
if (data.type == WatchpointAtAddress)
return BreakHandler::watchpointIcon();
if (data.type == WatchpointAtExpression)
return BreakHandler::watchpointIcon();
if (!data.enabled)
return BreakHandler::disabledBreakpointIcon();
if (state == BreakpointInserted)
return BreakHandler::breakpointIcon();
return BreakHandler::pendingBreakpointIcon();
}
QString BreakHandler::BreakpointItem::toToolTip() const
{
QString rc;
QTextStream str(&rc);
str << "<html><body><table>"
//<< "<tr><td>" << tr("ID:") << "</td><td>" << m_id << "</td></tr>"
<< "<tr><td>" << tr("State:")
<< "</td><td>" << (data.enabled ? tr("Enabled") : tr("Disabled"));
if (response.pending)
str << tr(", pending");
str << ", " << state << " (" << stateToString(state) << ")</td></tr>";
if (engine) {
str << "<tr><td>" << tr("Engine:")
<< "</td><td>" << engine->objectName() << "</td></tr>";
}
if (!response.pending) {
str << "<tr><td>" << tr("Breakpoint Number:")
<< "</td><td>" << response.id.toString() << "</td></tr>";
}
str << "<tr><td>" << tr("Breakpoint Type:")
<< "</td><td>" << typeToString(data.type) << "</td></tr>"
<< "<tr><td>" << tr("Marker File:")
<< "</td><td>" << QDir::toNativeSeparators(markerFileName()) << "</td></tr>"
<< "<tr><td>" << tr("Marker Line:")
<< "</td><td>" << markerLineNumber() << "</td></tr>"
<< "</table><br><hr><table>"
<< "<tr><th>" << tr("Property")
<< "</th><th>" << tr("Requested")
<< "</th><th>" << tr("Obtained") << "</th></tr>"
<< "<tr><td>" << tr("Internal Number:")
<< "</td><td>—</td><td>" << response.id.toString() << "</td></tr>";
if (data.type == BreakpointByFunction) {
str << "<tr><td>" << tr("Function Name:")
<< "</td><td>" << data.functionName
<< "</td><td>" << response.functionName
<< "</td></tr>";
}
if (data.type == BreakpointByFileAndLine) {
str << "<tr><td>" << tr("File Name:")
<< "</td><td>" << QDir::toNativeSeparators(data.fileName)
<< "</td><td>" << QDir::toNativeSeparators(response.fileName)
<< "</td></tr>"
<< "<tr><td>" << tr("Line Number:")
<< "</td><td>" << data.lineNumber
<< "</td><td>" << response.lineNumber << "</td></tr>"
<< "<tr><td>" << tr("Corrected Line Number:")
<< "</td><td>-"
<< "</td><td>" << response.correctedLineNumber << "</td></tr>";
}
if (data.type == BreakpointByFunction || data.type == BreakpointByFileAndLine) {
str << "<tr><td>" << tr("Module:")
<< "</td><td>" << data.module
<< "</td><td>" << response.module
<< "</td></tr>";
}
str << "<tr><td>" << tr("Breakpoint Address:")
<< "</td><td>";
formatAddress(str, data.address);
str << "</td><td>";
formatAddress(str, response.address);
str << "</td></tr>";
if (response.multiple) {
str << "<tr><td>" << tr("Multiple Addresses:")
<< "</td><td>"
<< "</td></tr>";
}
if (!data.command.isEmpty() || !response.command.isEmpty()) {
str << "<tr><td>" << tr("Command:")
<< "</td><td>" << data.command
<< "</td><td>" << response.command
<< "</td></tr>";
}
if (!data.message.isEmpty() || !response.message.isEmpty()) {
str << "<tr><td>" << tr("Message:")
<< "</td><td>" << data.message
<< "</td><td>" << response.message
<< "</td></tr>";
}
if (!data.condition.isEmpty() || !response.condition.isEmpty()) {
str << "<tr><td>" << tr("Condition:")
<< "</td><td>" << data.condition
<< "</td><td>" << response.condition
<< "</td></tr>";
}
if (data.ignoreCount || response.ignoreCount) {
str << "<tr><td>" << tr("Ignore Count:") << "</td><td>";
if (data.ignoreCount)
str << data.ignoreCount;
str << "</td><td>";
if (response.ignoreCount)
str << response.ignoreCount;
str << "</td></tr>";
}
if (data.threadSpec >= 0 || response.threadSpec >= 0) {
str << "<tr><td>" << tr("Thread Specification:")
<< "</td><td>";
if (data.threadSpec >= 0)
str << data.threadSpec;
str << "</td><td>";
if (response.threadSpec >= 0)
str << response.threadSpec;
str << "</td></tr>";
}
str << "</table></body></html>";
return rc;
}
} // namespace Internal
} // namespace Debugger
|
ostash/qt-creator-i18n-uk
|
src/plugins/debugger/breakhandler.cpp
|
C++
|
lgpl-2.1
| 51,468
|
// parser_file.C
//
// Copyright 1996-2001 Per Abrahamsen and Søren Hansen
// Copyright 2000-2001 KVL.
//
// This file is part of Daisy.
//
// Daisy is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// Daisy is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser Public License for more details.
//
// You should have received a copy of the GNU Lesser Public License
// along with Daisy; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#define BUILD_DLL
#include "parser_file.h"
#include "metalib.h"
#include "library.h"
#include "block_model.h"
#include "block_top.h"
#include "lexer.h"
#include "scope.h"
#include "number.h"
#include "integer.h"
#include "plf.h"
#include "time.h"
#include "treelog_text.h"
#include "path.h"
#include "units.h"
#include "mathlib.h"
#include "memutils.h"
#include "librarian.h"
#include "frame_model.h"
#include "frame_submodel.h"
#include <set>
#include <memory>
#include <sstream>
static const symbol error_symbol ("__PARSER_FILE_ERROR_MAGIC__");
struct ParserFile::Implementation
{
// Environment.
Metalib* mutable_metalib;
const Metalib& metalib ()
{
daisy_assert (mutable_metalib);
return *mutable_metalib;
}
Treelog& msg;
// Inputs.
std::vector<boost::shared_ptr<const FrameModel>/**/> inputs;
// Lexer.
const symbol file;
std::auto_ptr<std::istream> owned_stream;
std::auto_ptr<Lexer> lexer;
std::auto_ptr<Treelog::Open> nest;
int get ()
{ return lexer->get (); }
int peek ()
{ return lexer->peek (); }
bool good ()
{ return lexer->good (); }
void error (const std::string& str)
{ lexer->error (str); }
void error (const std::string& str, const Filepos& pos)
{ lexer->error (str, pos); }
void warning (const std::string& str)
{ lexer->warning (str); }
void eof ()
{ lexer->eof (); }
// Lisp lexer.
std::string get_string ();
symbol get_symbol ()
{ return symbol (get_string ()); }
int get_integer ();
double get_number ();
symbol get_dimension ();
double get_number (const symbol dim);
bool check_dimension (const symbol syntax, const symbol read);
double convert (double value, const symbol syntax, const symbol read,
const Filepos&);
void skip (const char*);
void skip ();
void skip_to_end ();
void skip_token ();
bool looking_at (char);
class Parskip
{
ParserFile::Implementation& parser;
bool skipped;
public:
Parskip (ParserFile::Implementation& p, bool skip = true)
: parser (p),
skipped (skip)
{
if (skip)
parser.skip ("(");
}
~Parskip ()
{
if (skipped)
parser.skip (")");
}
};
// Parser.
void check_value (const Frame& syntax, const symbol name, double value);
void add_derived (Library&);
boost::shared_ptr<FrameModel> load_object (const Library& lib,
bool in_sequence,
const FrameModel* original);
void load_list (Frame&);
// Create and destroy.
void initialize ();
Implementation (const Metalib&, symbol, Treelog&);
~Implementation ();
};
std::string
ParserFile::Implementation::get_string ()
{
static const struct IdExtra : public std::set<int>
{
bool operator() (int c) const
{ return find (c) != end (); }
IdExtra ()
{
insert ('=');
insert ('<');
insert ('>');
insert ('_');
insert ('+');
insert ('-');
insert ('*');
insert ('/');
}
} id_extra;
skip ();
int c = peek ();
if (c == '"')
{
// Get a string.
std::string str ("");
skip ("\"");
for (c = get (); good () && c != '"'; c = get ())
{
if (c == '\\')
{
c = get ();
switch (c)
{
case 'n':
c = '\n';
break;
case 't':
c = '\t';
break;
case '\n':
continue;
case '\\':
case '"':
break;
default:
error (std::string ("Unknown character escape '")
+ char (c) + "'");
}
}
str += int2char (c);
}
return str;
}
else if (c == '[')
return get_dimension ().name ();
else if (!id_extra (c) && !isalpha (c))
{
error ("Identifier or string expected");
skip_to_end ();
return error_symbol.name ();
}
else
{
// Get an identifier.
std::string str ("");
do
{
str += char (c);
get ();
c = peek ();
}
while (good() && (id_extra (c) || isalnum (c)));
return str;
}
}
int
ParserFile::Implementation::get_integer ()
{
skip ();
int c = peek ();
// Check for number literals first.
if (isdigit (c) || c == '-')
{
std::string str;
while (good () && (isdigit (c) || c == '-' || c == '+'))
{
str += int2char (c);
get ();
c = peek ();
}
// Empty number?
if (str.size () < 1U)
{
error ("Integer expected");
skip_to_end ();
return -42;
}
return atoi (str.c_str ());
}
// Then try an integer object.
const Library& lib = metalib ().library (Integer::component);
boost::shared_ptr<FrameModel> frame = load_object (lib, true, NULL);
if (!frame.get ())
return -42;
const symbol obj = frame->type_name ();
// Check for completness.
TreelogString treelog;
Treelog::Open nest (treelog, obj);
if (!frame->check (metalib (), treelog))
{
error ("Bogus integer '" + obj + "'\n--- details:\n"
+ treelog.str () + "---");
return -42;
}
std::auto_ptr<Integer> integer
(Librarian::build_frame<Integer> (metalib (), treelog, *frame, "integer"));
if (!integer.get ()
|| !integer->initialize (metalib ().units (), Scope::null (), treelog)
|| !integer->check (Scope::null (), treelog))
{
error ("Bad integer '" + obj + "'\n--- details:\n"
+ treelog.str () + "---");
return -42;
}
if (treelog.str ().length () > 0)
warning ("Warning for integer '" + obj + "'\n--- details:\n"
+ treelog.str () + "---");
if (integer->missing (Scope::null ()))
{
error ("Missing integer '" + obj + "'");
return -42;
}
return integer->value (Scope::null ());
}
double
ParserFile::Implementation::get_number ()
{
skip ();
std::string str;
int c = peek ();
while (good () && (isdigit (c)
|| c == '.' || c == '-' || c == '+'
|| c == 'e' || c == 'E'))
{
str += int2char (c);
get ();
c = peek ();
}
// Empty number?
if (str.size () < 1U)
{
error ("Number expected");
skip_to_end ();
return -42.42e42;
}
const char *c_str = str.c_str ();
const char *endptr = c_str;
const double value = strtod (c_str, const_cast<char**> (&endptr));
if (*endptr != '\0')
error (std::string ("Junk at end of number '") + endptr + "'");
return value;
}
symbol
ParserFile::Implementation::get_dimension ()
{
skip ("[");
std::string str;
int c = peek ();
while (good () && c != ']' && c != '\n')
{
str += int2char (c);
get ();
c = peek ();
}
skip ("]");
if (str == "")
return Attribute::None ();
return str;
}
double
ParserFile::Implementation::get_number (const symbol syntax_dim)
{
skip ();
// Check for number literals first.
if (peek () == '.' || isdigit (peek ()) || peek () == '-')
{
double value = get_number ();
Filepos pos = lexer->position ();
if (looking_at ('['))
{
const symbol read_dim = get_dimension ();
if (check_dimension (syntax_dim, read_dim))
value = convert (value, syntax_dim, read_dim, pos);
}
return value;
}
// Then try a number object.
const Library& lib = metalib ().library (Number::component);
boost::shared_ptr<FrameModel> frame = load_object (lib, true, NULL);
if (!frame.get ())
return -42.42e42;
const symbol obj = frame->type_name ();
// Check for completness.
TreelogString treelog;
Treelog::Open nest (treelog, obj);
if (!frame->check (metalib (), treelog))
{
error ("Bogus number '" + obj + "'\n--- details:\n"
+ treelog.str () + "---");
return -42.42e42;
}
std::auto_ptr<Number> number
(Librarian::build_frame<Number> (metalib (), msg, *frame, "number"));
const Units& units = metalib ().units ();
if (!number.get ()
|| !number->initialize (units, Scope::null (), treelog)
|| !number->check (units, Scope::null (), treelog))
{
error ("Bad number '" + obj + "'\n--- details:\n"
+ treelog.str () + "---");
return -42.42e42;
}
number->tick (units, Scope::null (), treelog);
if (treelog.str ().length () > 0)
warning ("Warning for number '" + obj + "'\n--- details:\n"
+ treelog.str () + "---");
if (number->missing (Scope::null ()))
{
error ("Missing number '" + obj + "'");
return -42.42e42;
}
double value = number->value (Scope::null ());
const std::string read_dim = number->dimension (Scope::null ()).name ();
if (check_dimension (syntax_dim, read_dim))
value = convert (value, syntax_dim, read_dim, lexer->position ());
return value;
}
bool
ParserFile::Implementation::check_dimension (const symbol syntax,
const symbol read)
{
if (syntax != read)
{
if (syntax == Attribute::Unknown ())
{
if (read.name ().length () == 0 || read.name ()[0] != '?')
warning ("you must use [?<dim>] for entries with unknown syntax");
}
else if (!metalib ().units ().can_convert (symbol (read), symbol (syntax),
msg))
{
error (std::string ("expected [")
+ ((syntax == Attribute::Fraction ()
|| syntax == Attribute::None ())
? "" : syntax) + "] got [" + read + "]");
return false;
}
}
return true;
}
double
ParserFile::Implementation::convert (double value,
const symbol syntax,
const symbol read,
const Filepos& pos)
{
if (syntax == Attribute::Unknown ())
return value;
if (syntax == read)
return value;
if (syntax == Attribute::Fraction () && read == "%")
return value * 0.01;
try
{
if (syntax == Attribute::None () || syntax == Attribute::Fraction ())
{
if (read == "")
return value;
else
return metalib ().units ().convert (symbol (read), symbol (""), value);
}
return metalib ().units ().convert (symbol (read), symbol (syntax), value);
}
catch (const std::string& message)
{
error (message, pos);
return value;
}
}
void
ParserFile::Implementation::skip (const char* str)
{
skip ();
for (const char* p = str; *p; p++)
if (*p != peek ())
{
error (std::string("Expected '") + str + "'");
skip_token ();
break;
}
else
get ();
}
void
ParserFile::Implementation::skip ()
{
while (true)
if (!good ())
return;
else if (isspace (peek ()))
get ();
else if (peek () == ';')
while (good () && get () != '\n')
;
else
return;
}
void
ParserFile::Implementation::skip_token () {
if (peek () == ';' || isspace (peek ()))
skip ();
if (peek () == '"')
get_string ();
else if (peek () == '.' || isdigit (peek ()) || peek () == '-')
get_number ();
else if (peek () == '(')
{
get ();
skip_to_end ();
skip (")");
}
else if (isalnum (peek ()) || peek () == '_')
get_string ();
else if (peek () == '[')
get_dimension ();
else
get ();
}
void
ParserFile::Implementation::skip_to_end ()
{
skip ();
while (peek () != ')' && good ())
{
skip_token ();
skip ();
}
}
bool
ParserFile::Implementation::looking_at (char c)
{
skip ();
return peek () == c;
}
void
ParserFile::Implementation::check_value (const Frame& frame,
const symbol name,
const double value)
{
Treelog::Open nest (msg, name);
if (!frame.verify (name, value, msg))
error (name + ": bad value");
}
class FrameParsed : public FrameModel
{
// Content.
private:
const symbol name;
symbol type_name () const
{ return name; }
int seq_id;
const symbol file;
Filepos position_;
public:
const Filepos& own_position () const
{ return position_; }
void reposition (const Filepos& pos)
{ position_ = pos; }
int sequence_id () const
{ return seq_id; }
// Create and Destroy.
private:
FrameParsed (const FrameParsed& parent, parent_clone_t)
: FrameModel (parent, parent_clone),
name (parent.name),
seq_id (parent.seq_id),
file (parent.file),
position_ (parent.position_)
{ }
FrameParsed& clone () const
{ return *new FrameParsed (*this, parent_clone); }
public:
FrameParsed (const symbol name_, const FrameModel& model, const int seq_id_,
const Filepos pos)
: FrameModel (model, parent_link),
name (name_),
seq_id (seq_id_),
position_ (pos)
{ }
};
void
ParserFile::Implementation::add_derived (Library& lib)
{
// Get the name of the class and the existing superclass to derive from.
const symbol name = get_symbol ();
if (name == error_symbol)
{
skip_to_end ();
return;
}
// Check for duplicates.
if (lib.check (name))
{
const Frame& old = lib.model (name);
const Filepos& pos = old.own_position ();
if (pos != Filepos::none ())
warning (name + " is already defined in "
+ pos.filename () + ", overwriting");
else
warning (name + " is already defined, overwriting");
lib.remove (name);
}
static const symbol const_symbol ("const");
skip ();
int c = peek ();
Parskip skip (*this, c == '(');
const symbol super = (isdigit (c) || c == '-' || c == '.')
? const_symbol
: get_symbol ();
if (!lib.check (super))
{
if (super != error_symbol)
error (std::string ("Unknown '") + lib.name ()
+ "' model '" + super + "'");
skip_to_end ();
return;
}
daisy_assert (mutable_metalib);
boost::shared_ptr<FrameModel> frame
(new FrameParsed (name, lib.model (super), mutable_metalib->get_sequence (),
lexer->position ()));
if (!frame.get ())
throw "Failed to derive";
// Doc string.
daisy_assert (!frame->ordered ()
|| frame->order ().begin () != frame->order ().end ());
if ((!frame->ordered ()
|| (frame->lookup (*(frame->order ().begin ())) != Attribute::String
&& frame->lookup (*(frame->order ().begin ())) != Attribute::Model))
&& looking_at ('"')
&& frame->lookup ("description") == Attribute::String
&& frame->type_size ("description") == Attribute::Singleton)
{
const symbol d = get_symbol ();
if (d != error_symbol)
frame->set ("description", d);
}
// Add separate attributes for this object.
Treelog::Open nest (msg, "Defining " + lib.name () + " '" + name + "'");
load_list (*frame);
// Add new object to library.
lib.add_model (name, frame);
// Inform metalib.
daisy_assert (mutable_metalib);
mutable_metalib->added_object (lib.name (), name);
}
boost::shared_ptr<FrameModel>
ParserFile::Implementation::load_object (const Library& lib, bool in_sequence,
const FrameModel *const original)
{
boost::shared_ptr<FrameModel> result;
bool skipped = false;
static const symbol original_symbol ("original");
symbol type;
skip ();
int c = peek ();
// Handle numeric literals.
if (isdigit (c) || c == '.' || c == '-')
{
if (lib.name () == symbol (Number::component))
{
result.reset (new FrameModel (lib.model ("const"),
Frame::parent_link));
const double value = get_number ();
const symbol dim = get_dimension ();
result->set ("value", value, dim);
}
else if (lib.name () == symbol (Integer::component))
{
result.reset (new FrameModel (lib.model ("const"),
Frame::parent_link));
result->set ("value", get_integer ());
}
else
{
error ("Number not expected");
skip_to_end ();
}
return result;
}
if (c == '(' && in_sequence)
{
skip ("(");
skipped = true;
c = peek ();
}
if (original && original->used_to_be_a_submodel () && c == '(')
{
// Special hack to allow skipping the "original" keyword for
// models that used to be submodels.
const symbol original_type = original->type_name ();
daisy_assert (lib.check (original_type));
type = original_symbol;
warning ("Model specified missing, assuming 'original'");
}
else
{
if (c == '(' && !in_sequence)
{
skip ("(");
skipped = true;
}
type = get_symbol ();
if (type == error_symbol)
{
skip_to_end ();
return result;
}
}
try
{
if (type == original_symbol)
{
if (!original)
throw (std::string ("No original value"));
result.reset (&original->clone ());
type = result->type_name ();
daisy_assert (lib.check (type));
}
else if (!lib.check (type))
{
// Special hack to handle numbers in scopes.
if (lib.name () == symbol (Number::component))
{
static const symbol fetch ("fetch");
result.reset (new FrameModel (lib.model (fetch),
Frame::parent_link));
result->set ("name", type);
goto skip_it;
}
throw (std::string ("Unknown '") + lib.name () + "' model '"
+ type + "'");
}
else
{
result.reset (new FrameModel (lib.model (type), Frame::parent_link));
}
if (skipped || !in_sequence)
{
Treelog::Open nest (msg, "Deriving from '" + type + "'");
load_list (*result);
}
skip_it:;
}
catch (const std::string& wrong)
{
error (wrong);
skip_to_end ();
}
if (skipped)
skip (")");
return result;
}
void
ParserFile::Implementation::load_list (Frame& frame)
{
std::vector<symbol>::const_iterator current = frame.order ().begin ();
const std::vector<symbol>::const_iterator end = frame.order ().end ();
std::set<symbol> found;
while ( good () && !looking_at (')'))
{
bool skipped = false;
bool in_order = false;
symbol name = "";
if (current == end)
// Unordered association list, get name.
{
skip ("(");
skipped = true;
name = get_symbol ();
}
else
// Ordered tupple, name know.
{
in_order = true;
name = *current;
current++;
}
if (name == error_symbol)
continue;
// Make sure we skip the ')' afterwards.
struct RAII_skip
{
ParserFile::Implementation& outer;
const bool skipped;
RAII_skip (ParserFile::Implementation& o, const bool s)
: outer (o),
skipped (s)
{ }
~RAII_skip ()
{
if (skipped)
outer.skip (")");
outer.skip ();
}
} raii_skip (*this, skipped);
// Declarations.
if (name == "declare")
{
bool ok = true;
// Special handling of block local parameters.
const symbol var = get_symbol ();
if (var == error_symbol)
ok = false;
else if (frame.lookup (var) != Attribute::Error)
{
error ("'" + var + "' already exists");
ok = false;
}
int size = Attribute::Singleton;
if (looking_at ('['))
{
skip ("[");
if (looking_at (']'))
size = Attribute::Variable;
else
size = get_integer ();
skip ("]");
}
const symbol type_name = get_symbol ();
if (type_name == error_symbol)
ok = false;
symbol doc = "User defined " + type_name + ".";
const Attribute::type type = Attribute::type_number (type_name);
switch (type)
{
case Attribute::String:
{
if (!looking_at ('('))
doc = get_symbol ();
if (doc == error_symbol)
ok = false;
if (ok)
frame.declare_string (var, Attribute::Const, size, doc);
break;
}
case Attribute::Integer:
{
if (!looking_at ('('))
doc = get_symbol ();
if (doc == error_symbol)
ok = false;
if (ok)
frame.declare_integer (var, Attribute::Const, size, doc);
break;
}
case Attribute::Number:
{
symbol dim = Attribute::Unknown ();
if (looking_at ('['))
{
dim = get_symbol ();
if (dim == error_symbol)
dim == Attribute::Unknown ();
if (dim.name ().size () == 0)
dim = Attribute::None ();
}
if (!looking_at ('('))
doc = get_symbol ();
if (doc == error_symbol)
ok = false;
if (ok)
frame.declare (var, dim, Attribute::Const, size, doc);
break;
}
case Attribute::Error:
{
if (type_name == "fixed")
{
const symbol submodel = get_symbol ();
if (submodel == error_symbol)
ok = false;
else if (Librarian::submodel_registered (submodel))
{
if (!looking_at ('('))
doc = get_string ();
if (doc == error_symbol)
ok = false;
else if (ok)
{
const Frame::load_syntax_t load
= Librarian::submodel_load (submodel);
frame.declare_submodule (var, Attribute::Const,
doc, load);
}
break;
}
/* else fallthrough to error handling. */
}
else
{
const symbol type_symbol (type_name);
if (metalib ().exist (type_symbol))
{
if (!looking_at ('('))
doc = get_string ();
if (doc == error_symbol)
ok = false;
else if (ok)
frame.declare_object (var, type_symbol,
Attribute::Const, size, doc);
break;
}
/* else fallthrough to error handling. */
}
}
// Fallthrough
default:
if (ok)
{
error ("'" + type_name + "' unhandled type");
ok = false;
}
}
// Next attribute.
continue;
}
if (&frame == &metalib ()
&& name.name ().substr (0, 3) == "def"
&& metalib ().exist (name.name ().substr (3)))
{
const symbol lib_name = name.name ().substr (3);
// Handled specially: Put directly in global library.
add_derived (metalib ().library (lib_name));
continue;
}
// Duplicate warning.
if (found.find (name) != found.end ())
warning (name + " specified twice, last takes precedence");
else if (frame.lookup (name) != Attribute::Model // (input file )
|| frame.component (name) != Parser::component)
found.insert (name);
Attribute::type type = frame.lookup (name);
// Log variable warning.
if (type != Attribute::Error && frame.is_log (name))
warning (name + " is a log only variable, value will be ignored");
if (type == Attribute::Error)
{
error (std::string("Unknown attribute '") + name + "'");
skip_to_end ();
}
else if (looking_at ('$'))
{
skip ("$");
const symbol var = get_symbol ();
if (var == error_symbol)
/* Do nothing */;
else if (name == var)
error ("Reference $" + var + " refers to itself");
else
frame.set_reference (name, var);
}
else if (frame.type_size (name) == Attribute::Singleton)
switch (type)
{
case Attribute::Number:
{
if (frame.dimension (name) == Attribute::User ())
{
const double value = get_number ();
const symbol dim =
looking_at ('[') ? get_dimension () : Attribute::Unknown ();
check_value (frame, name, value);
frame.set (name, value, dim);
break;
}
const double value = get_number (frame.dimension (name));
check_value (frame, name, value);
frame.set (name, value);
}
break;
case Attribute::Submodel:
{
Treelog::Open nest (msg, "In submodel '" + name + "'");
bool alist_skipped = false;
if (in_order)
{
// Last element of a total order does not need '('.
if (looking_at ('(')
|| current != end
|| !frame.total_order ())
{
alist_skipped = true;
skip ("(");
}
}
if (looking_at ('&'))
skip ("&old");
boost::shared_ptr<FrameSubmodel> child (&frame.submodel (name).clone ());
load_list (*child);
frame.set (name, child);
if (alist_skipped)
skip (")");
}
break;
case Attribute::PLF:
{
Parskip skip (*this, in_order);
PLF plf;
double last_x = -42;
int count = 0;
const symbol domain = frame.domain (name);
const symbol range = frame.range (name);
bool ok = true;
while (!looking_at (')') && good ())
{
Parskip skip (*this);
double x = get_number (domain);
{
if (count > 0 && x <= last_x)
{
error ("Non increasing x value");
ok = false;
}
last_x = x;
count++;
}
const double y = get_number (range);
Treelog::Open nest (msg, name);
if (!frame.verify (name, y, msg))
{
error (name + ": bad value");
ok = false;
}
if (ok)
plf.add (x, y);
}
if (count < 2)
{
error ("Need at least 2 points");
ok = false;
}
if (ok)
frame.set (name, plf);
break;
}
case Attribute::String:
{
const symbol n = get_symbol ();
if (n == error_symbol)
break;
frame.set (name, n);
// Handle "directory" immediately.
if (&frame == &metalib () && name == "directory")
if (!metalib ().path ().set_directory (n))
error ("Could not set directory '" + n + "'");
}
break;
case Attribute::Boolean:
{
const symbol flag = get_string ();
if (flag == "true")
frame.set (name, true);
else
{
frame.set (name, false);
if (flag != "false" && flag != error_symbol)
error ("Expected 'true' or 'false'");
}
break;
}
case Attribute::Integer:
frame.set (name, get_integer ());
break;
case Attribute::Model:
{
boost::shared_ptr<FrameModel> child;
const symbol component = frame.component (name);
const Library& lib = metalib ().library (component);
if (frame.check (name))
{
Treelog::Open nest (msg, "Refining model '" + name + "'");
child = load_object (lib, in_order, &frame.model (name));
}
else
{
Treelog::Open nest (msg, "In model '" + name + "'");
child = load_object (lib, in_order, NULL);
}
if (!child.get ())
/* Do nothing */;
else if (lib.name () == symbol (Parser::component))
{
std::auto_ptr<Parser> parser
(Librarian::build_frame<Parser> (metalib (), msg, *child,
name));
if (!parser.get ())
error ("file error");
else
{
daisy_assert (mutable_metalib);
parser->initialize (*mutable_metalib);
if (parser->check ())
parser->load_nested ();
lexer->add_errors (parser->error_count ());
}
inputs.push_back (child);
}
else
frame.set (name, child);
}
break;
case Attribute::Scalar:
case Attribute::Reference:
case Attribute::Error:
error (std::string("Unknown singleton '") + name + "'");
skip_to_end ();
break;
default:
daisy_notreached ();
}
else
{
// If this is part of an order, expect parentheses arund the
// list, EXCEPT when there cannot possible be any more
// elements after this one. I.e. when the element is the
// last of a totally ordered sequence.
if (!in_order)
// Unordered, we already skipped this one
daisy_assert (skipped);
// Support for sequences not really finished yet.
switch (type)
{
case Attribute::Model:
{
const symbol component = frame.component (name);
const Library& lib = metalib ().library (component);
static const std::vector<boost::shared_ptr<const FrameModel>/**/> no_sequence;
std::vector<boost::shared_ptr<const FrameModel>/**/> sequence;
const std::vector<boost::shared_ptr<const FrameModel>/**/>& old_sequence
= frame.check (name)
? frame.model_sequence (name)
: no_sequence;
while (!looking_at (')') && good ())
{
if (frame.type_size (name) == sequence.size ())
{
std::ostringstream tmp;
tmp << "The '" << name
<< "' sequence should only contain "
<< frame.type_size (name) << " elements";
error (tmp.str ());
}
if (looking_at ('&'))
{
skip ("&old");
if (!frame.check (name))
error ("No originals available");
for (size_t i = 0; i < old_sequence.size (); i++)
sequence.push_back (old_sequence[i]);
continue;
}
const size_t element = sequence.size ();
std::ostringstream tmp;
tmp << "In '" << name << "' model #" << element + 1U;
Treelog::Open nest (msg, tmp.str ());
boost::shared_ptr<FrameModel> child;
if (old_sequence.size () > element)
{
boost::shared_ptr<const FrameModel> old_model
= old_sequence[element];
daisy_assert (old_model.get ());
child = load_object (lib, true, old_model.get ());
}
else
child = load_object (lib, true, NULL);
if (child.get ())
sequence.push_back (child);
}
frame.set (name, sequence);
}
break;
case Attribute::Submodel:
{
const size_t size = frame.type_size (name);
static const std::vector<boost::shared_ptr<const FrameSubmodel>/**/> no_sequence;
const FrameSubmodel& default_frame = *frame.default_frame (name);
const std::vector<boost::shared_ptr<const FrameSubmodel>/**/>& old_sequence
= frame.check (name)
? frame.submodel_sequence (name)
: no_sequence;
std::vector<boost::shared_ptr<const FrameSubmodel>/**/>
sequence;
bool skipped = false;
// We do not force parentheses around the alist if it
// is the last member of a fully ordered list.
if (in_order && (current != end || !frame.total_order ()))
// in order and (not the last or unordered may follow)
{
daisy_assert (!skipped);
skip ("(");
skipped = true;
}
while (!looking_at (')') && good ())
{
if (looking_at ('&'))
{
skip ("&old");
if (!frame.check (name))
error ("No originals available");
for (size_t i = 0; i < old_sequence.size (); i++)
sequence.push_back (old_sequence[i]);
continue;
}
Parskip skip (*this);
const size_t element = sequence.size ();
std::ostringstream tmp;
tmp << "In '" << name << "' submodel #" << element + 1U;
Treelog::Open nest (msg, tmp.str ());
boost::shared_ptr<FrameSubmodel> child;
if (old_sequence.size () > element)
child.reset (&old_sequence[element]->clone ());
else
child.reset (new FrameSubmodelValue (default_frame,
Frame::parent_link));
load_list (*child);
sequence.push_back (child);
}
if (skipped)
skip (")");
if (!Attribute::flexible_size (size) && sequence.size () != size)
{
std::ostringstream str;
str << "Got " << sequence.size ()
<< " array members, expected " << size;
error (str.str ());
}
frame.set (name, sequence);
}
break;
case Attribute::PLF:
{
std::vector<boost::shared_ptr<const PLF>/**/> plfs;
int total = 0;
const int size = frame.type_size (name);
while (good () && !looking_at (')'))
{
Parskip dummy (*this);
boost::shared_ptr<PLF> plf (new PLF ());
double last_x = -42;
int count = 0;
const symbol domain = frame.domain (name);
const symbol range = frame.range (name);
while (!looking_at (')') && good ())
{
if (looking_at ('&'))
{
skip ("&old");
if (!frame.check (name))
error ("No originals available");
const std::vector<boost::shared_ptr<const PLF>/**/>& old_sequence
= frame.plf_sequence (name);
for (size_t i = 0; i < old_sequence.size (); i++)
plfs.push_back (old_sequence[i]);
continue;
}
Parskip dummy2 (*this);
double x = get_number (domain);
{
if (count > 0 && x <= last_x)
error ("Non increasing x value");
last_x = x;
count++;
}
double y = get_number (range);
Treelog::Open nest (msg, name);
if (!frame.verify (name, y, msg))
error (name + ": bad value");
plf->add (x, y);
}
if (count < 2)
error ("Need at least 2 points");
total++;
plfs.push_back (plf);
}
if (!Attribute::flexible_size (size) && total != size)
{
std::ostringstream str;
str << "Got " << total
<< " array members, expected " << size;
error (str.str ());
boost::shared_ptr<PLF> empty (new PLF ());
for (;total < size; total++)
plfs.push_back (empty);
}
frame.set (name, plfs);
// sequence_delete (plfs.begin (), plfs.end ());
break;
}
case Attribute::Number:
{
std::vector<double> array;
std::vector<Filepos> positions;
int count = 0;
const int size = frame.type_size (name);
const symbol syntax_dim = frame.dimension (name);
unsigned int first_unchecked = 0;
while (good () && !looking_at (')'))
{
if (looking_at ('&'))
{
skip ("&old");
if (!frame.check (name))
error ("No originals available");
const std::vector<double>& old_sequence
= frame.number_sequence (name);
for (size_t i = 0; i < old_sequence.size (); i++)
array.push_back (old_sequence[i]);
continue;
}
if (looking_at ('*'))
{
skip ("*");
const int same = get_integer ();
if (array.size () == 0)
error ("must specify number before '*'");
else
{
// Append same - 1 copies of last value.
for (int i = 1; i < same; i++)
{
array.push_back (array.back ());
positions.push_back (Filepos::none ());
count++;
}
}
}
else if (looking_at ('['))
{
const symbol read_dim = get_dimension ();
if (check_dimension (syntax_dim, read_dim))
{
daisy_assert (positions.size () == array.size ());
for (unsigned int i = first_unchecked;
i < array.size ();
i++)
{
array[i] = convert (array[i],
syntax_dim, read_dim,
positions[i]);
}
first_unchecked = array.size ();
}
}
else
{
array.push_back (get_number ());
positions.push_back (lexer->position ());
count++;
}
}
daisy_assert (positions.size () == array.size ());
for (unsigned int i = 0; i < array.size (); i++)
{
if (positions[i] != Filepos::none ())
{
std::ostringstream tmp;
tmp << name << "[" << i << "]";
Treelog::Open nest (msg, tmp.str ());
if (!frame.verify (name, array[i], msg))
error (tmp.str () + ": bad value", positions[i]);
}
}
if (!Attribute::flexible_size (size) && count != size)
{
std::ostringstream str;
str << "Got " << count
<< " array members, expected " << size;
error (str.str ());
for (;count < size; count++)
array.push_back (-1.0);
}
frame.set (name, array);
break;
}
case Attribute::String:
{
std::vector<symbol> array;
int count = 0;
const int size = frame.type_size (name);
while (!looking_at (')') && good ())
{
if (looking_at ('&'))
{
skip ("&old");
if (!frame.check (name))
error ("No originals available");
const std::vector<symbol>& old_sequence
= frame.name_sequence (name);
for (size_t i = 0; i < old_sequence.size (); i++)
array.push_back (old_sequence[i]);
continue;
}
const symbol s = get_symbol ();
if (s != error_symbol)
array.push_back (s);
count++;
}
if (!Attribute::flexible_size (size) && count != size)
{
std::ostringstream str;
str << "Got " << count
<< " array members, expected " << size;
error (str.str ());
for (;count < size; count++)
array.push_back (symbol ("<error>"));
}
frame.set (name, array);
// Handle "path" immediately.
if (&frame == &metalib () && name == "path")
{
// Use block to get references.
BlockTop block (metalib (), msg, frame);
const std::vector<symbol>& symbols
= block.name_sequence (name);
metalib ().path ().set_path (symbols);
}
break;
}
case Attribute::Integer:
{
std::vector<int> array;
int count = 0;
const int size = frame.type_size (name);
while (!looking_at (')') && good ())
{
if (looking_at ('&'))
{
skip ("&old");
if (!frame.check (name))
error ("No originals available");
const std::vector<int>& old_sequence
= frame.integer_sequence (name);
for (size_t i = 0; i < old_sequence.size (); i++)
array.push_back (old_sequence[i]);
continue;
}
array.push_back (get_integer ());
count++;
}
if (!Attribute::flexible_size (size) && count != size)
{
std::ostringstream str;
str << "Got " << count
<< " array members, expected " << size;
error (str.str ());
for (;count < size; count++)
array.push_back (-42);
}
frame.set (name, array);
// Handle "path" immediately.
break;
}
case Attribute::Error:
if (name != error_symbol)
error (std::string("Unknown attribute '") + name + "'");
skip_to_end ();
break;
default:
if (name != error_symbol)
error (std::string("Unsupported sequence '") + name + "'");
skip_to_end ();
}
}
// Value check.
if (frame.check (name))
{
Treelog::Open nest (msg, "Checking value of '" + name + "'");
if (!frame.check (metalib (), name, msg))
error ("Invalid value");
}
}
}
void
ParserFile::Implementation::initialize ()
{
if (!nest.get ())
nest.reset (new Treelog::Open (msg, "Parsing file: '" + file + "'"));
}
ParserFile::Implementation::Implementation (const Metalib& mlib,
const symbol filename,
Treelog& treelog)
: mutable_metalib (NULL),
msg (treelog),
inputs (std::vector<boost::shared_ptr<const FrameModel>/**/> ()),
file (filename),
owned_stream (mlib.path ().open_file (filename.name ())),
lexer (new Lexer (filename.name (), *owned_stream, msg))
{ }
ParserFile::Implementation::~Implementation ()
{ }
void
ParserFile::load_nested ()
{
impl->initialize ();
impl->skip ();
daisy_assert (impl->mutable_metalib);
impl->load_list (*impl->mutable_metalib);
impl->skip ();
impl->eof ();
}
void
ParserFile::load_top ()
{
load_nested ();
// Add inputs.
daisy_assert (impl->mutable_metalib);
impl->mutable_metalib->set_parser_inputs (impl->inputs);
// sequence_delete (impl->inputs.begin (), impl->inputs.end ());
impl->inputs.erase (impl->inputs.begin (), impl->inputs.end ());
// Remember filename.
impl->mutable_metalib->add_parser_file (impl->file);
}
int
ParserFile::error_count () const
{ return impl->lexer->get_error_count (); }
void
ParserFile::initialize (Metalib& lib)
{
daisy_assert (!impl->mutable_metalib);
impl->mutable_metalib = &lib;
}
bool
ParserFile::check () const
{
daisy_assert (impl->mutable_metalib);
return impl->lexer->good ();
}
ParserFile::ParserFile (Metalib& metalib,
const std::string& filename, Treelog& msg)
: Parser (symbol ("file")),
impl (new Implementation (metalib, filename, msg))
{ }
ParserFile::ParserFile (const BlockModel& al)
: Parser (al),
impl (new Implementation (al.metalib (), al.name ("where"), al.msg ()))
{ }
ParserFile::~ParserFile ()
{ }
static struct ParserFileSyntax : public DeclareModel
{
Model* make (const BlockModel& al) const
{ return new ParserFile (al); }
ParserFileSyntax ()
: DeclareModel (Parser::component, "file",
"Read a setup file containing lots of parentheses.")
{ }
void load_frame (Frame& frame) const
{
frame.declare_string ("where", Attribute::Const,
"File to read from.");
frame.order ("where");
}
} ParserFile_syntax;
// parser_file.C ends here.
|
sativa/daisy-model
|
parser_file.C
|
C++
|
lgpl-2.1
| 45,656
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Qt 4.8: mainwindow.cpp Example File (mainwindows/application/mainwindow.cpp)</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<script src="scripts/jquery.js" type="text/javascript"></script>
<script src="scripts/functions.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style/superfish.css" />
<link rel="stylesheet" type="text/css" href="style/narrow.css" />
<!--[if IE]>
<meta name="MSSmartTagsPreventParsing" content="true">
<meta http-equiv="imagetoolbar" content="no">
<![endif]-->
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie6.css">
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie7.css">
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="style/style_ie8.css">
<![endif]-->
<script src="scripts/superfish.js" type="text/javascript"></script>
<script src="scripts/narrow.js" type="text/javascript"></script>
</head>
<body class="" onload="CheckEmptyAndLoadList();">
<div class="header" id="qtdocheader">
<div class="content">
<div id="nav-logo">
<a href="index.html">Home</a></div>
<a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a>
<div id="narrowsearch"></div>
<div id="nav-topright">
<ul>
<li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li>
<li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li>
<li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/">
DOC</a></li>
<li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li>
</ul>
</div>
<div id="shortCut">
<ul>
<li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li>
<li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li>
</ul>
</div>
<ul class="sf-menu" id="narrowmenu">
<li><a href="#">API Lookup</a>
<ul>
<li><a href="classes.html">Class index</a></li>
<li><a href="functions.html">Function index</a></li>
<li><a href="modules.html">Modules</a></li>
<li><a href="namespaces.html">Namespaces</a></li>
<li><a href="qtglobal.html">Global Declarations</a></li>
<li><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</li>
<li><a href="#">Qt Topics</a>
<ul>
<li><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li><a href="supported-platforms.html">Supported Platforms</a></li>
<li><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</li>
<li><a href="#">Examples</a>
<ul>
<li><a href="all-examples.html">Examples</a></li>
<li><a href="tutorials.html">Tutorials</a></li>
<li><a href="demos.html">Demos</a></li>
<li><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="wrapper">
<div class="hd">
<span></span>
</div>
<div class="bd group">
<div class="sidebar">
<div class="searchlabel">
Search index:</div>
<div class="search" id="sidebarsearch">
<form id="qtdocsearch" action="" onsubmit="return false;">
<fieldset>
<input type="text" name="searchstring" id="pageType" value="" />
<div id="resultdialog">
<a href="#" id="resultclose">Close</a>
<p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p>
<p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span> results:</p>
<ul id="resultlist" class="all">
</ul>
</div>
</fieldset>
</form>
</div>
<div class="box first bottombar" id="lookup">
<h2 title="API Lookup"><span></span>
API Lookup</h2>
<div id="list001" class="list">
<ul id="ul001" >
<li class="defaultLink"><a href="classes.html">Class index</a></li>
<li class="defaultLink"><a href="functions.html">Function index</a></li>
<li class="defaultLink"><a href="modules.html">Modules</a></li>
<li class="defaultLink"><a href="namespaces.html">Namespaces</a></li>
<li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li>
<li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</div>
</div>
<div class="box bottombar" id="topics">
<h2 title="Qt Topics"><span></span>
Qt Topics</h2>
<div id="list002" class="list">
<ul id="ul002" >
<li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li class="defaultLink"><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li>
<li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</div>
</div>
<div class="box" id="examples">
<h2 title="Examples"><span></span>
Examples</h2>
<div id="list003" class="list">
<ul id="ul003">
<li class="defaultLink"><a href="all-examples.html">Examples</a></li>
<li class="defaultLink"><a href="tutorials.html">Tutorials</a></li>
<li class="defaultLink"><a href="demos.html">Demos</a></li>
<li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</div>
</div>
</div>
<div class="wrap">
<div class="toolbar">
<div class="breadcrumb toolblock">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<!-- Breadcrumbs go here -->
</ul>
</div>
<div class="toolbuttons toolblock">
<ul>
<li id="smallA" class="t_button">A</li>
<li id="medA" class="t_button active">A</li>
<li id="bigA" class="t_button">A</li>
<li id="print" class="t_button"><a href="javascript:this.print();">
<span>Print</span></a></li>
</ul>
</div>
</div>
<div class="content mainContent">
<h1 class="title">mainwindow.cpp Example File</h1>
<span class="small-subtitle">mainwindows/application/mainwindow.cpp</span>
<!-- $$$mainwindows/application/mainwindow.cpp-description -->
<div class="descr"> <a name="details"></a>
<pre class="cpp"> <span class="comment">/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** 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 Digia Plc 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$
**
****************************************************************************/</span>
<span class="preprocessor">#include <QtGui></span>
<span class="preprocessor">#include "mainwindow.h"</span>
MainWindow<span class="operator">::</span>MainWindow()
{
textEdit <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qplaintextedit.html">QPlainTextEdit</a></span>;
setCentralWidget(textEdit);
createActions();
createMenus();
createToolBars();
createStatusBar();
readSettings();
connect(textEdit<span class="operator">-</span><span class="operator">></span>document()<span class="operator">,</span> SIGNAL(contentsChanged())<span class="operator">,</span>
<span class="keyword">this</span><span class="operator">,</span> SLOT(documentWasModified()));
setCurrentFile(<span class="string">""</span>);
setUnifiedTitleAndToolBarOnMac(<span class="keyword">true</span>);
}
<span class="type">void</span> MainWindow<span class="operator">::</span>closeEvent(<span class="type"><a href="qcloseevent.html">QCloseEvent</a></span> <span class="operator">*</span>event)
{
<span class="keyword">if</span> (maybeSave()) {
writeSettings();
event<span class="operator">-</span><span class="operator">></span>accept();
} <span class="keyword">else</span> {
event<span class="operator">-</span><span class="operator">></span>ignore();
}
}
<span class="type">void</span> MainWindow<span class="operator">::</span>newFile()
{
<span class="keyword">if</span> (maybeSave()) {
textEdit<span class="operator">-</span><span class="operator">></span>clear();
setCurrentFile(<span class="string">""</span>);
}
}
<span class="type">void</span> MainWindow<span class="operator">::</span>open()
{
<span class="keyword">if</span> (maybeSave()) {
<span class="type"><a href="qstring.html">QString</a></span> fileName <span class="operator">=</span> <span class="type"><a href="qfiledialog.html">QFileDialog</a></span><span class="operator">::</span>getOpenFileName(<span class="keyword">this</span>);
<span class="keyword">if</span> (<span class="operator">!</span>fileName<span class="operator">.</span>isEmpty())
loadFile(fileName);
}
}
<span class="type">bool</span> MainWindow<span class="operator">::</span>save()
{
<span class="keyword">if</span> (curFile<span class="operator">.</span>isEmpty()) {
<span class="keyword">return</span> saveAs();
} <span class="keyword">else</span> {
<span class="keyword">return</span> saveFile(curFile);
}
}
<span class="type">bool</span> MainWindow<span class="operator">::</span>saveAs()
{
<span class="type"><a href="qstring.html">QString</a></span> fileName <span class="operator">=</span> <span class="type"><a href="qfiledialog.html">QFileDialog</a></span><span class="operator">::</span>getSaveFileName(<span class="keyword">this</span>);
<span class="keyword">if</span> (fileName<span class="operator">.</span>isEmpty())
<span class="keyword">return</span> <span class="keyword">false</span>;
<span class="keyword">return</span> saveFile(fileName);
}
<span class="type">void</span> MainWindow<span class="operator">::</span>about()
{
<span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>about(<span class="keyword">this</span><span class="operator">,</span> tr(<span class="string">"About Application"</span>)<span class="operator">,</span>
tr(<span class="string">"The <b>Application</b> example demonstrates how to "</span>
<span class="string">"write modern GUI applications using Qt, with a menu bar, "</span>
<span class="string">"toolbars, and a status bar."</span>));
}
<span class="type">void</span> MainWindow<span class="operator">::</span>documentWasModified()
{
setWindowModified(textEdit<span class="operator">-</span><span class="operator">></span>document()<span class="operator">-</span><span class="operator">></span>isModified());
}
<span class="type">void</span> MainWindow<span class="operator">::</span>createActions()
{
newAct <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(<span class="type"><a href="qicon.html">QIcon</a></span>(<span class="string">":/images/new.png"</span>)<span class="operator">,</span> tr(<span class="string">"&New"</span>)<span class="operator">,</span> <span class="keyword">this</span>);
newAct<span class="operator">-</span><span class="operator">></span>setShortcuts(<span class="type"><a href="qkeysequence.html">QKeySequence</a></span><span class="operator">::</span>New);
newAct<span class="operator">-</span><span class="operator">></span>setStatusTip(tr(<span class="string">"Create a new file"</span>));
connect(newAct<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(newFile()));
openAct <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(<span class="type"><a href="qicon.html">QIcon</a></span>(<span class="string">":/images/open.png"</span>)<span class="operator">,</span> tr(<span class="string">"&Open..."</span>)<span class="operator">,</span> <span class="keyword">this</span>);
openAct<span class="operator">-</span><span class="operator">></span>setShortcuts(<span class="type"><a href="qkeysequence.html">QKeySequence</a></span><span class="operator">::</span>Open);
openAct<span class="operator">-</span><span class="operator">></span>setStatusTip(tr(<span class="string">"Open an existing file"</span>));
connect(openAct<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(open()));
saveAct <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(<span class="type"><a href="qicon.html">QIcon</a></span>(<span class="string">":/images/save.png"</span>)<span class="operator">,</span> tr(<span class="string">"&Save"</span>)<span class="operator">,</span> <span class="keyword">this</span>);
saveAct<span class="operator">-</span><span class="operator">></span>setShortcuts(<span class="type"><a href="qkeysequence.html">QKeySequence</a></span><span class="operator">::</span>Save);
saveAct<span class="operator">-</span><span class="operator">></span>setStatusTip(tr(<span class="string">"Save the document to disk"</span>));
connect(saveAct<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(save()));
saveAsAct <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(tr(<span class="string">"Save &As..."</span>)<span class="operator">,</span> <span class="keyword">this</span>);
saveAsAct<span class="operator">-</span><span class="operator">></span>setShortcuts(<span class="type"><a href="qkeysequence.html">QKeySequence</a></span><span class="operator">::</span>SaveAs);
saveAsAct<span class="operator">-</span><span class="operator">></span>setStatusTip(tr(<span class="string">"Save the document under a new name"</span>));
connect(saveAsAct<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(saveAs()));
exitAct <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(tr(<span class="string">"E&xit"</span>)<span class="operator">,</span> <span class="keyword">this</span>);
exitAct<span class="operator">-</span><span class="operator">></span>setShortcuts(<span class="type"><a href="qkeysequence.html">QKeySequence</a></span><span class="operator">::</span>Quit);
exitAct<span class="operator">-</span><span class="operator">></span>setStatusTip(tr(<span class="string">"Exit the application"</span>));
connect(exitAct<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(close()));
cutAct <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(<span class="type"><a href="qicon.html">QIcon</a></span>(<span class="string">":/images/cut.png"</span>)<span class="operator">,</span> tr(<span class="string">"Cu&t"</span>)<span class="operator">,</span> <span class="keyword">this</span>);
cutAct<span class="operator">-</span><span class="operator">></span>setShortcuts(<span class="type"><a href="qkeysequence.html">QKeySequence</a></span><span class="operator">::</span>Cut);
cutAct<span class="operator">-</span><span class="operator">></span>setStatusTip(tr(<span class="string">"Cut the current selection's contents to the "</span>
<span class="string">"clipboard"</span>));
connect(cutAct<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> textEdit<span class="operator">,</span> SLOT(cut()));
copyAct <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(<span class="type"><a href="qicon.html">QIcon</a></span>(<span class="string">":/images/copy.png"</span>)<span class="operator">,</span> tr(<span class="string">"&Copy"</span>)<span class="operator">,</span> <span class="keyword">this</span>);
copyAct<span class="operator">-</span><span class="operator">></span>setShortcuts(<span class="type"><a href="qkeysequence.html">QKeySequence</a></span><span class="operator">::</span>Copy);
copyAct<span class="operator">-</span><span class="operator">></span>setStatusTip(tr(<span class="string">"Copy the current selection's contents to the "</span>
<span class="string">"clipboard"</span>));
connect(copyAct<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> textEdit<span class="operator">,</span> SLOT(copy()));
pasteAct <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(<span class="type"><a href="qicon.html">QIcon</a></span>(<span class="string">":/images/paste.png"</span>)<span class="operator">,</span> tr(<span class="string">"&Paste"</span>)<span class="operator">,</span> <span class="keyword">this</span>);
pasteAct<span class="operator">-</span><span class="operator">></span>setShortcuts(<span class="type"><a href="qkeysequence.html">QKeySequence</a></span><span class="operator">::</span>Paste);
pasteAct<span class="operator">-</span><span class="operator">></span>setStatusTip(tr(<span class="string">"Paste the clipboard's contents into the current "</span>
<span class="string">"selection"</span>));
connect(pasteAct<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> textEdit<span class="operator">,</span> SLOT(paste()));
aboutAct <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(tr(<span class="string">"&About"</span>)<span class="operator">,</span> <span class="keyword">this</span>);
aboutAct<span class="operator">-</span><span class="operator">></span>setStatusTip(tr(<span class="string">"Show the application's About box"</span>));
connect(aboutAct<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(about()));
aboutQtAct <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(tr(<span class="string">"About &Qt"</span>)<span class="operator">,</span> <span class="keyword">this</span>);
aboutQtAct<span class="operator">-</span><span class="operator">></span>setStatusTip(tr(<span class="string">"Show the Qt library's About box"</span>));
connect(aboutQtAct<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> qApp<span class="operator">,</span> SLOT(aboutQt()));
cutAct<span class="operator">-</span><span class="operator">></span>setEnabled(<span class="keyword">false</span>);
copyAct<span class="operator">-</span><span class="operator">></span>setEnabled(<span class="keyword">false</span>);
connect(textEdit<span class="operator">,</span> SIGNAL(copyAvailable(<span class="type">bool</span>))<span class="operator">,</span>
cutAct<span class="operator">,</span> SLOT(setEnabled(<span class="type">bool</span>)));
connect(textEdit<span class="operator">,</span> SIGNAL(copyAvailable(<span class="type">bool</span>))<span class="operator">,</span>
copyAct<span class="operator">,</span> SLOT(setEnabled(<span class="type">bool</span>)));
}
<span class="type">void</span> MainWindow<span class="operator">::</span>createMenus()
{
fileMenu <span class="operator">=</span> menuBar()<span class="operator">-</span><span class="operator">></span>addMenu(tr(<span class="string">"&File"</span>));
fileMenu<span class="operator">-</span><span class="operator">></span>addAction(newAct);
fileMenu<span class="operator">-</span><span class="operator">></span>addAction(openAct);
fileMenu<span class="operator">-</span><span class="operator">></span>addAction(saveAct);
fileMenu<span class="operator">-</span><span class="operator">></span>addAction(saveAsAct);
fileMenu<span class="operator">-</span><span class="operator">></span>addSeparator();
fileMenu<span class="operator">-</span><span class="operator">></span>addAction(exitAct);
editMenu <span class="operator">=</span> menuBar()<span class="operator">-</span><span class="operator">></span>addMenu(tr(<span class="string">"&Edit"</span>));
editMenu<span class="operator">-</span><span class="operator">></span>addAction(cutAct);
editMenu<span class="operator">-</span><span class="operator">></span>addAction(copyAct);
editMenu<span class="operator">-</span><span class="operator">></span>addAction(pasteAct);
menuBar()<span class="operator">-</span><span class="operator">></span>addSeparator();
helpMenu <span class="operator">=</span> menuBar()<span class="operator">-</span><span class="operator">></span>addMenu(tr(<span class="string">"&Help"</span>));
helpMenu<span class="operator">-</span><span class="operator">></span>addAction(aboutAct);
helpMenu<span class="operator">-</span><span class="operator">></span>addAction(aboutQtAct);
}
<span class="type">void</span> MainWindow<span class="operator">::</span>createToolBars()
{
fileToolBar <span class="operator">=</span> addToolBar(tr(<span class="string">"File"</span>));
fileToolBar<span class="operator">-</span><span class="operator">></span>addAction(newAct);
fileToolBar<span class="operator">-</span><span class="operator">></span>addAction(openAct);
fileToolBar<span class="operator">-</span><span class="operator">></span>addAction(saveAct);
editToolBar <span class="operator">=</span> addToolBar(tr(<span class="string">"Edit"</span>));
editToolBar<span class="operator">-</span><span class="operator">></span>addAction(cutAct);
editToolBar<span class="operator">-</span><span class="operator">></span>addAction(copyAct);
editToolBar<span class="operator">-</span><span class="operator">></span>addAction(pasteAct);
}
<span class="type">void</span> MainWindow<span class="operator">::</span>createStatusBar()
{
statusBar()<span class="operator">-</span><span class="operator">></span>showMessage(tr(<span class="string">"Ready"</span>));
}
<span class="type">void</span> MainWindow<span class="operator">::</span>readSettings()
{
<span class="type"><a href="qsettings.html">QSettings</a></span> settings(<span class="string">"Trolltech"</span><span class="operator">,</span> <span class="string">"Application Example"</span>);
<span class="type"><a href="qpoint.html">QPoint</a></span> pos <span class="operator">=</span> settings<span class="operator">.</span>value(<span class="string">"pos"</span><span class="operator">,</span> <span class="type"><a href="qpoint.html">QPoint</a></span>(<span class="number">200</span><span class="operator">,</span> <span class="number">200</span>))<span class="operator">.</span>toPoint();
<span class="type"><a href="qsize.html">QSize</a></span> size <span class="operator">=</span> settings<span class="operator">.</span>value(<span class="string">"size"</span><span class="operator">,</span> <span class="type"><a href="qsize.html">QSize</a></span>(<span class="number">400</span><span class="operator">,</span> <span class="number">400</span>))<span class="operator">.</span>toSize();
resize(size);
move(pos);
}
<span class="type">void</span> MainWindow<span class="operator">::</span>writeSettings()
{
<span class="type"><a href="qsettings.html">QSettings</a></span> settings(<span class="string">"Trolltech"</span><span class="operator">,</span> <span class="string">"Application Example"</span>);
settings<span class="operator">.</span>setValue(<span class="string">"pos"</span><span class="operator">,</span> pos());
settings<span class="operator">.</span>setValue(<span class="string">"size"</span><span class="operator">,</span> size());
}
<span class="type">bool</span> MainWindow<span class="operator">::</span>maybeSave()
{
<span class="keyword">if</span> (textEdit<span class="operator">-</span><span class="operator">></span>document()<span class="operator">-</span><span class="operator">></span>isModified()) {
<span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>StandardButton ret;
ret <span class="operator">=</span> <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>warning(<span class="keyword">this</span><span class="operator">,</span> tr(<span class="string">"Application"</span>)<span class="operator">,</span>
tr(<span class="string">"The document has been modified.\n"</span>
<span class="string">"Do you want to save your changes?"</span>)<span class="operator">,</span>
<span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>Save <span class="operator">|</span> <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>Discard <span class="operator">|</span> <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>Cancel);
<span class="keyword">if</span> (ret <span class="operator">=</span><span class="operator">=</span> <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>Save)
<span class="keyword">return</span> save();
<span class="keyword">else</span> <span class="keyword">if</span> (ret <span class="operator">=</span><span class="operator">=</span> <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>Cancel)
<span class="keyword">return</span> <span class="keyword">false</span>;
}
<span class="keyword">return</span> <span class="keyword">true</span>;
}
<span class="type">void</span> MainWindow<span class="operator">::</span>loadFile(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&</span>fileName)
{
<span class="type"><a href="qfile.html">QFile</a></span> file(fileName);
<span class="keyword">if</span> (<span class="operator">!</span>file<span class="operator">.</span>open(<span class="type"><a href="qfile.html">QFile</a></span><span class="operator">::</span>ReadOnly <span class="operator">|</span> <span class="type"><a href="qfile.html">QFile</a></span><span class="operator">::</span>Text)) {
<span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>warning(<span class="keyword">this</span><span class="operator">,</span> tr(<span class="string">"Application"</span>)<span class="operator">,</span>
tr(<span class="string">"Cannot read file %1:\n%2."</span>)
<span class="operator">.</span>arg(fileName)
<span class="operator">.</span>arg(file<span class="operator">.</span>errorString()));
<span class="keyword">return</span>;
}
<span class="type"><a href="qtextstream.html">QTextStream</a></span> in(<span class="operator">&</span>file);
<span class="preprocessor">#ifndef QT_NO_CURSOR</span>
<span class="type"><a href="qapplication.html">QApplication</a></span><span class="operator">::</span>setOverrideCursor(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>WaitCursor);
<span class="preprocessor">#endif</span>
textEdit<span class="operator">-</span><span class="operator">></span>setPlainText(in<span class="operator">.</span>readAll());
<span class="preprocessor">#ifndef QT_NO_CURSOR</span>
<span class="type"><a href="qapplication.html">QApplication</a></span><span class="operator">::</span>restoreOverrideCursor();
<span class="preprocessor">#endif</span>
setCurrentFile(fileName);
statusBar()<span class="operator">-</span><span class="operator">></span>showMessage(tr(<span class="string">"File loaded"</span>)<span class="operator">,</span> <span class="number">2000</span>);
}
<span class="type">bool</span> MainWindow<span class="operator">::</span>saveFile(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&</span>fileName)
{
<span class="type"><a href="qfile.html">QFile</a></span> file(fileName);
<span class="keyword">if</span> (<span class="operator">!</span>file<span class="operator">.</span>open(<span class="type"><a href="qfile.html">QFile</a></span><span class="operator">::</span>WriteOnly <span class="operator">|</span> <span class="type"><a href="qfile.html">QFile</a></span><span class="operator">::</span>Text)) {
<span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>warning(<span class="keyword">this</span><span class="operator">,</span> tr(<span class="string">"Application"</span>)<span class="operator">,</span>
tr(<span class="string">"Cannot write file %1:\n%2."</span>)
<span class="operator">.</span>arg(fileName)
<span class="operator">.</span>arg(file<span class="operator">.</span>errorString()));
<span class="keyword">return</span> <span class="keyword">false</span>;
}
<span class="type"><a href="qtextstream.html">QTextStream</a></span> out(<span class="operator">&</span>file);
<span class="preprocessor">#ifndef QT_NO_CURSOR</span>
<span class="type"><a href="qapplication.html">QApplication</a></span><span class="operator">::</span>setOverrideCursor(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>WaitCursor);
<span class="preprocessor">#endif</span>
out <span class="operator"><</span><span class="operator"><</span> textEdit<span class="operator">-</span><span class="operator">></span>toPlainText();
<span class="preprocessor">#ifndef QT_NO_CURSOR</span>
<span class="type"><a href="qapplication.html">QApplication</a></span><span class="operator">::</span>restoreOverrideCursor();
<span class="preprocessor">#endif</span>
setCurrentFile(fileName);
statusBar()<span class="operator">-</span><span class="operator">></span>showMessage(tr(<span class="string">"File saved"</span>)<span class="operator">,</span> <span class="number">2000</span>);
<span class="keyword">return</span> <span class="keyword">true</span>;
}
<span class="type">void</span> MainWindow<span class="operator">::</span>setCurrentFile(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&</span>fileName)
{
curFile <span class="operator">=</span> fileName;
textEdit<span class="operator">-</span><span class="operator">></span>document()<span class="operator">-</span><span class="operator">></span>setModified(<span class="keyword">false</span>);
setWindowModified(<span class="keyword">false</span>);
<span class="type"><a href="qstring.html">QString</a></span> shownName <span class="operator">=</span> curFile;
<span class="keyword">if</span> (curFile<span class="operator">.</span>isEmpty())
shownName <span class="operator">=</span> <span class="string">"untitled.txt"</span>;
setWindowFilePath(shownName);
}
<span class="type"><a href="qstring.html">QString</a></span> MainWindow<span class="operator">::</span>strippedName(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&</span>fullFileName)
{
<span class="keyword">return</span> <span class="type"><a href="qfileinfo.html">QFileInfo</a></span>(fullFileName)<span class="operator">.</span>fileName();
}</pre>
</div>
<!-- @@@mainwindows/application/mainwindow.cpp -->
</div>
</div>
</div>
<div class="ft">
<span></span>
</div>
</div>
<div class="footer">
<p>
<acronym title="Copyright">©</acronym> 2014 Digia Plc and/or its
subsidiaries. Documentation contributions included herein are the copyrights of
their respective owners.</p>
<br />
<p>
The documentation provided herein is licensed under the terms of the
<a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation
License version 1.3</a> as published by the Free Software Foundation.</p>
<p>
Documentation sources may be obtained from <a href="http://www.qt-project.org">
www.qt-project.org</a>.</p>
<br />
<p>
Digia, Qt and their respective logos are trademarks of Digia Plc
in Finland and/or other countries worldwide. All other trademarks are property
of their respective owners. <a title="Privacy Policy"
href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p>
</div>
<script src="scripts/functions.js" type="text/javascript"></script>
</body>
</html>
|
nonrational/qt-everywhere-opensource-src-4.8.6
|
doc/html/mainwindows-application-mainwindow-cpp.html
|
HTML
|
lgpl-2.1
| 38,099
|
require 'spec_helper'
# Specs in this file have access to a helper object that includes
# the LinksHelper. For example:
#
# describe LinksHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# expect(helper.concat_strings("this","that")).to eq("this that")
# end
# end
# end
describe LinksHelper do
pending "add some examples to (or delete) #{__FILE__}"
end
|
manishchaks/OrgWerks
|
spec/helpers/links_helper_spec.rb
|
Ruby
|
lgpl-2.1
| 408
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "gitorious.h"
#include "gitorioushostwidget.h"
#include "ui_gitorioushostwidget.h"
#include <coreplugin/coreconstants.h>
#include <QtCore/QUrl>
#include <QtCore/QDebug>
#include <QtCore/QTimer>
#include <QtGui/QStandardItem>
#include <QtGui/QStandardItemModel>
#include <QtGui/QItemSelectionModel>
#include <QtGui/QDesktopServices>
#include <QtGui/QIcon>
#include <QtGui/QStyle>
enum { debug = 0 };
namespace Gitorious {
namespace Internal {
enum { HostNameColumn, ProjectCountColumn, DescriptionColumn, ColumnCount };
// Create a model row for a host. Make the host name editable as specified by
// flag.
static QList<QStandardItem *> hostEntry(const QString &host,
int projectCount,
const QString &description, bool isDummyEntry)
{
const Qt::ItemFlags nonEditableFlags = (Qt::ItemIsSelectable|Qt::ItemIsEnabled);
const Qt::ItemFlags editableFlags = nonEditableFlags|Qt::ItemIsEditable;
QStandardItem *hostItem = new QStandardItem(host);
hostItem->setFlags(isDummyEntry ? editableFlags : nonEditableFlags);
// Empty for dummy, else "..." or count
QStandardItem *projectCountItem = 0;
QString countItemText;
if (!isDummyEntry) {
countItemText = projectCount ? QString::number(projectCount) : QString(QLatin1String("..."));
}
projectCountItem = new QStandardItem(countItemText);
projectCountItem->setFlags(nonEditableFlags);
QStandardItem *descriptionItem = new QStandardItem(description);
descriptionItem->setFlags(editableFlags);
QList<QStandardItem *> rc;
rc << hostItem << projectCountItem << descriptionItem;
return rc;
}
static inline QList<QStandardItem *> hostEntry(const GitoriousHost &h)
{
return hostEntry(h.hostName, h.projects.size(), h.description, false);
}
GitoriousHostWidget::GitoriousHostWidget(QWidget *parent) :
QWidget(parent),
m_newHost(tr("<New Host>")),
ui(new Ui::GitoriousHostWidget),
m_model(new QStandardItemModel(0, ColumnCount)),
m_errorClearTimer(0),
m_isValid(false),
m_isHostListDirty(false)
{
ui->setupUi(this);
ui->errorLabel->setVisible(false);
ui->browseToolButton->setIcon(style()->standardIcon(QStyle::SP_MessageBoxInformation));
connect(ui->browseToolButton, SIGNAL(clicked()), this, SLOT(slotBrowse()));
ui->browseToolButton->setEnabled(false);
ui->deleteToolButton->setIcon(QIcon(Core::Constants::ICON_MINUS));
connect(ui->deleteToolButton, SIGNAL(clicked()), this, SLOT(slotDelete()));
ui->deleteToolButton->setEnabled(false);
// Model
QStringList headers;
headers << tr("Host") << tr("Projects") << tr("Description");
m_model->setHorizontalHeaderLabels(headers);
Gitorious &gitorious = Gitorious::instance();
foreach( const GitoriousHost &gh, gitorious.hosts())
m_model->appendRow(hostEntry(gh));
appendNewDummyEntry();
connect(m_model, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(slotItemEdited(QStandardItem*)));
ui->hostView->setModel(m_model);
// View
ui->hostView->setRootIsDecorated(false);
ui->hostView->setUniformRowHeights(true);
connect(ui->hostView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
this, SLOT(slotCurrentChanged(QModelIndex,QModelIndex)));
ui->hostView->setSelectionMode(QAbstractItemView::SingleSelection);
if (m_model->rowCount())
selectRow(0);
connect(&gitorious, SIGNAL(projectListPageReceived(int,int)),
this, SLOT(slotProjectListPageReceived(int)));
connect(&gitorious, SIGNAL(projectListReceived(int)),
this, SLOT(slotProjectListPageReceived(int)));
connect(&gitorious, SIGNAL(error(QString)), this, SLOT(slotError(QString)));
setMinimumWidth(700);
}
GitoriousHostWidget::~GitoriousHostWidget()
{
// Prevent crash?
Gitorious *gitorious = &Gitorious::instance();
disconnect(gitorious, SIGNAL(projectListPageReceived(int,int)),
this, SLOT(slotProjectListPageReceived(int)));
disconnect(gitorious, SIGNAL(projectListReceived(int)),
this, SLOT(slotProjectListPageReceived(int)));
disconnect(gitorious, SIGNAL(error(QString)), this, SLOT(slotError(QString)));
delete ui;
}
int GitoriousHostWidget::selectedRow() const
{
const QModelIndex idx = ui->hostView->selectionModel()->currentIndex();
if (idx.isValid())
return idx.row();
return -1;
}
void GitoriousHostWidget::selectRow(int r)
{
if (r >= 0 && r != selectedRow()) {
const QModelIndex index = m_model->index(r, 0);
ui->hostView->selectionModel()->setCurrentIndex(index, QItemSelectionModel::Select|QItemSelectionModel::Current|QItemSelectionModel::Rows);
}
}
void GitoriousHostWidget::appendNewDummyEntry()
{
// Append a new entry where a host name is editable
m_model->appendRow(hostEntry(m_newHost, 0, QString(), true));
}
void GitoriousHostWidget::slotItemEdited(QStandardItem *item)
{
// Synchronize with Gitorious singleton.
// Did someone enter a valid host name into the dummy item?
// -> Create a new one.
const int row = item->row();
const bool isDummyEntry = row >= Gitorious::instance().hostCount();
switch (item->column()) {
case HostNameColumn:
if (isDummyEntry) {
Gitorious::instance().addHost(item->text(), m_model->item(row, DescriptionColumn)->text());
m_isHostListDirty = true;
appendNewDummyEntry();
selectRow(row);
}
break;
case ProjectCountColumn:
break;
case DescriptionColumn:
if (!isDummyEntry) {
const QString description = item->text();
if (description != Gitorious::instance().hostDescription(row)) {
Gitorious::instance().setHostDescription(row, item->text());
m_isHostListDirty = true;
}
}
break;
}
}
void GitoriousHostWidget::slotProjectListPageReceived(int row)
{
if (debug)
qDebug() << Q_FUNC_INFO << row;
// Update column
const int projectCount = Gitorious::instance().projectCount(row);
m_model->item(row, ProjectCountColumn)->setText(QString::number(projectCount));
// If it is the currently selected host, re-check validity if not enabled
if (!m_isValid) {
const QModelIndex current = ui->hostView->selectionModel()->currentIndex();
if (current.isValid() && current.row() == row)
checkValid(current);
}
}
QStandardItem *GitoriousHostWidget::currentItem() const
{
const QModelIndex idx = ui->hostView->selectionModel()->currentIndex();
if (idx.isValid())
return m_model->itemFromIndex(idx.column() != 0 ? idx.sibling(idx.row(), 0) : idx);
return 0;
}
void GitoriousHostWidget::slotBrowse()
{
if (const QStandardItem *item = currentItem()) {
const QUrl url(QLatin1String("http://") + item->text() + QLatin1Char('/'));
if (url.isValid())
QDesktopServices::openUrl(url);
}
}
void GitoriousHostWidget::slotDelete()
{
const QModelIndex index = ui->hostView->selectionModel()->currentIndex();
ui->hostView->selectionModel()->clear();
if (index.isValid()) {
const int row = index.row();
qDeleteAll(m_model->takeRow(row));
Gitorious::instance().removeAt(row);
m_isHostListDirty = true;
}
}
void GitoriousHostWidget::slotCurrentChanged(const QModelIndex ¤t, const QModelIndex & /* previous */)
{
checkValid(current);
}
void GitoriousHostWidget::checkValid(const QModelIndex &index)
{
if (debug)
qDebug() << Q_FUNC_INFO << index;
bool hasSelectedHost = false;
bool hasProjects = false;
if (index.isValid()) {
// Are we on the new dummy item?
Gitorious &gitorious = Gitorious::instance();
const int row = index.row();
hasSelectedHost = row < gitorious.hostCount();
hasProjects = hasSelectedHost && gitorious.projectCount(row) > 0;
}
ui->deleteToolButton->setEnabled(hasSelectedHost);
ui->browseToolButton->setEnabled(hasSelectedHost);
const bool valid = hasSelectedHost && hasProjects;
if (valid != m_isValid) {
m_isValid = valid;
emit validChanged();
}
}
bool GitoriousHostWidget::isValid() const
{
return m_isValid;
}
bool GitoriousHostWidget::isHostListDirty() const
{
return m_isHostListDirty;
}
void GitoriousHostWidget::slotClearError()
{
ui->errorLabel->setVisible(false);
ui->errorLabel->clear();
}
void GitoriousHostWidget::slotError(const QString &e)
{
// Display error for a while
ui->errorLabel->setText(e);
ui->errorLabel->setVisible(true);
if (!m_errorClearTimer) {
m_errorClearTimer = new QTimer(this);
m_errorClearTimer->setSingleShot(true);
m_errorClearTimer->setInterval(5000);
connect(m_errorClearTimer, SIGNAL(timeout()), this, SLOT(slotClearError()));
}
if (!m_errorClearTimer->isActive())
m_errorClearTimer->start();
}
void GitoriousHostWidget::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
} // namespace Internal
} // namespace Gitorious
|
TheProjecter/project-qtcreator
|
src/plugins/git/gitorious/gitorioushostwidget.cpp
|
C++
|
lgpl-2.1
| 10,581
|
package processing.app;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import cc.arduino.files.DeleteFilesOnShutdown;
import processing.app.helpers.FileUtils;
import static processing.app.I18n.tr;
/**
* This represents a single sketch, consisting of one or more files.
*/
public class Sketch {
public static final String DEFAULT_SKETCH_EXTENSION = "ino";
public static final List<String> OLD_SKETCH_EXTENSIONS = Arrays.asList("pde");
public static final List<String> SKETCH_EXTENSIONS = Stream.concat(Stream.of(DEFAULT_SKETCH_EXTENSION), OLD_SKETCH_EXTENSIONS.stream()).collect(Collectors.toList());
public static final List<String> OTHER_ALLOWED_EXTENSIONS = Arrays.asList("c", "cpp", "h", "hh", "hpp", "s");
public static final List<String> EXTENSIONS = Stream.concat(SKETCH_EXTENSIONS.stream(), OTHER_ALLOWED_EXTENSIONS.stream()).collect(Collectors.toList());
/**
* folder that contains this sketch
*/
private File folder;
private List<SketchFile> files = new ArrayList<>();
private File buildPath;
public static final Comparator<SketchFile> CODE_DOCS_COMPARATOR = new Comparator<SketchFile>() {
@Override
public int compare(SketchFile x, SketchFile y) {
if (x.isPrimary() && !y.isPrimary())
return -1;
if (y.isPrimary() && !x.isPrimary())
return 1;
return x.getFileName().compareTo(y.getFileName());
}
};
/**
* Create a new SketchData object, and looks at the sketch directory
* on disk to get populate the list of files in this sketch.
*
* @param file
* Any file inside the sketch directory.
*/
Sketch(File file) throws IOException {
folder = file.getParentFile();
files = listSketchFiles(true);
}
static public File checkSketchFile(File file) {
// check to make sure that this .pde file is
// in a folder of the same name
String fileName = file.getName();
File parent = file.getParentFile();
String parentName = parent.getName();
String pdeName = parentName + ".pde";
File altPdeFile = new File(parent, pdeName);
String inoName = parentName + ".ino";
File altInoFile = new File(parent, inoName);
if (pdeName.equals(fileName) || inoName.equals(fileName))
return file;
if (altPdeFile.exists())
return altPdeFile;
if (altInoFile.exists())
return altInoFile;
return null;
}
/**
* Reload the list of files. This checks the sketch directory on disk,
* to see if any files were added or removed. This does *not* check
* the contents of the files, just their presence.
*
* @return true when the list of files was changed, false when it was
* not.
*/
public boolean reload() throws IOException {
List<SketchFile> reloaded = listSketchFiles(false);
if (!reloaded.equals(files)) {
files = reloaded;
return true;
}
return false;
}
/**
* Scan this sketch's directory for files that should be loaded as
* part of this sketch. Doesn't modify this SketchData instance, just
* returns a filtered and sorted list of File objects ready to be
* passed to the SketchFile constructor.
*
* @param showWarnings
* When true, any invalid filenames will show a warning.
*/
private List<SketchFile> listSketchFiles(boolean showWarnings) throws IOException {
Set<SketchFile> result = new TreeSet<>(CODE_DOCS_COMPARATOR);
for (File file : FileUtils.listFiles(folder, false, EXTENSIONS)) {
if (BaseNoGui.isSanitaryName(FileUtils.splitFilename(file).basename)) {
result.add(new SketchFile(this, file));
} else if (showWarnings) {
System.err.println(I18n.format(tr("File name {0} is invalid: ignored"), file.getName()));
}
}
if (result.size() == 0)
throw new IOException(tr("No valid code files found"));
return new ArrayList<>(result);
}
/**
* Create the data folder if it does not exist already. As a
* convenience, it also returns the data folder, since it's likely
* about to be used.
*/
public File prepareDataFolder() {
File dataFolder = getDataFolder();
if (!dataFolder.exists()) {
dataFolder.mkdirs();
}
return dataFolder;
}
public void save() throws IOException {
for (SketchFile file : getFiles()) {
if (file.isModified())
file.save();
}
}
public int getCodeCount() {
return files.size();
}
public SketchFile[] getFiles() {
return files.toArray(new SketchFile[0]);
}
/**
* Returns a file object for the primary .pde of this sketch.
*/
public SketchFile getPrimaryFile() {
return files.get(0);
}
/**
* Returns path to the main .pde file for this sketch.
*/
public String getMainFilePath() {
return getPrimaryFile().getFile().getAbsolutePath();
}
public SketchFile getFile(int i) {
return files.get(i);
}
/**
* Gets the build path for this sketch. The first time this is called,
* a build path is generated and created and the same path is returned
* on all subsequent calls.
*
* This takes into account the build.path preference. If it is set,
* that path is always returned, and the directory is *not* deleted on
* shutdown. If the preference is not set, a random pathname in a
* temporary directory is generated, which is automatically deleted on
* shutdown.
*/
public File getBuildPath() throws IOException {
if (buildPath == null) {
if (PreferencesData.get("build.path") != null) {
buildPath = BaseNoGui.absoluteFile(PreferencesData.get("build.path"));
Files.createDirectories(buildPath.toPath());
} else {
buildPath = FileUtils.createTempFolder("arduino_build_");
DeleteFilesOnShutdown.add(buildPath);
}
}
return buildPath;
}
protected void removeFile(SketchFile which) {
if (!files.remove(which))
System.err.println("removeCode: internal error.. could not find code");
}
public String getName() {
return folder.getName();
}
public File getFolder() {
return folder;
}
public File getDataFolder() {
return new File(folder, "data");
}
/**
* Is any of the files in this sketch modified?
*/
public boolean isModified() {
for (SketchFile file : files) {
if (file.isModified())
return true;
}
return false;
}
/**
* Finds the file with the given filename and returns its index.
* Returns -1 when the file was not found.
*/
public int findFileIndex(File filename) {
int i = 0;
for (SketchFile file : files) {
if (file.getFile().equals(filename))
return i;
i++;
}
return -1;
}
/**
* Check if renaming/saving this sketch to the given folder would
* cause a problem because: 1. The new folder already exists 2.
* Renaming the primary file would cause a conflict with an existing
* file. If so, an IOEXception is thrown. If not, the name of the new
* primary file is returned.
*/
protected File checkNewFoldername(File newFolder) throws IOException {
String newPrimary = FileUtils.addExtension(newFolder.getName(), DEFAULT_SKETCH_EXTENSION);
// Verify the new folder does not exist yet
if (newFolder.exists()) {
String msg = I18n.format(tr("Sorry, the folder \"{0}\" already exists."), newFolder.getAbsoluteFile());
throw new IOException(msg);
}
// If the folder is actually renamed (as opposed to moved somewhere
// else), check for conflicts using the new filename, but the
// existing folder name.
if (!newFolder.getName().equals(folder.getName()))
checkNewFilename(new File(folder, newPrimary));
return new File(newFolder, newPrimary);
}
/**
* Check if renaming or adding a file would cause a problem because
* the file already exists in this sketch. If so, an IOEXception is
* thrown.
*
* @param newFile
* The filename of the new file, or the new name for an
* existing file.
*/
protected void checkNewFilename(File newFile) throws IOException {
// Verify that the sketch doesn't have a filem with the new name
// already, other than the current primary (index 0)
if (findFileIndex(newFile) >= 0) {
String msg = I18n.format(tr("The sketch already contains a file named \"{0}\""), newFile.getName());
throw new IOException(msg);
}
}
/**
* Rename this sketch' folder to the given name. Unlike saveAs(), this
* moves the sketch directory, not leaving anything in the old place.
* This operation does not *save* the sketch, so the files on disk are
* moved, but not modified.
*
* @param newFolder
* The new folder name for this sketch. The new primary
* file's name will be derived from this.
*
* @throws IOException
* When a problem occurs. The error message should be
* already translated.
*/
public void renameTo(File newFolder) throws IOException {
// Check intended rename (throws if there is a problem)
File newPrimary = checkNewFoldername(newFolder);
// Rename the sketch folder
if (!getFolder().renameTo(newFolder))
throw new IOException(tr("Failed to rename sketch folder"));
folder = newFolder;
// Tell each file about its new name
for (SketchFile file : files)
file.renamedTo(new File(newFolder, file.getFileName()));
// And finally, rename the primary file
getPrimaryFile().renameTo(newPrimary.getName());
}
public SketchFile addFile(String newName) throws IOException {
// Check the name will not cause any conflicts
File newFile = new File(folder, newName);
checkNewFilename(newFile);
// Add a new sketchFile
SketchFile sketchFile = new SketchFile(this, newFile);
files.add(sketchFile);
Collections.sort(files, CODE_DOCS_COMPARATOR);
return sketchFile;
}
/**
* Save this sketch under the new name given. Unlike renameTo(), this
* leaves the existing sketch in place.
*
* @param newFolder
* The new folder name for this sketch. The new primary
* file's name will be derived from this.
*
* @throws IOException
* When a problem occurs. The error message should be
* already translated.
*/
public void saveAs(File newFolder) throws IOException {
// Check intented rename (throws if there is a problem)
File newPrimary = checkNewFoldername(newFolder);
// Create the folder
if (!newFolder.mkdirs()) {
String msg = I18n.format(tr("Could not create directory \"{0}\""), newFolder.getAbsolutePath());
throw new IOException(msg);
}
// Save the files to their new location
for (SketchFile file : files) {
if (file.isPrimary())
file.saveAs(newPrimary);
else
file.saveAs(new File(newFolder, file.getFileName()));
}
folder = newFolder;
// Copy the data folder (this may take a while.. add progress bar?)
if (getDataFolder().exists()) {
File newDataFolder = new File(newFolder, "data");
FileUtils.copy(getDataFolder(), newDataFolder);
}
}
/**
* Deletes this entire sketch from disk.
*/
void delete() {
FileUtils.recursiveDelete(folder);
}
}
|
Chris--A/Arduino
|
arduino-core/src/processing/app/Sketch.java
|
Java
|
lgpl-2.1
| 11,401
|
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="es_UY">
<context>
<name>LXQtModuleManager</name>
<message>
<location filename="../src/lxqtmodman.cpp" line="311"/>
<source>Crash Report</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/lxqtmodman.cpp" line="312"/>
<source><b>%1</b> crashed too many times. Its autorestart has been disabled until next login.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>SessionApplication</name>
<message>
<location filename="../src/main.cpp" line="62"/>
<source>Configuration file path.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/main.cpp" line="62"/>
<location filename="../src/main.cpp" line="63"/>
<source>file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/main.cpp" line="63"/>
<source>Window manager to use.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WmSelectDialog</name>
<message>
<location filename="../src/wmselectdialog.ui" line="14"/>
<source>Welcome to LXQt</source>
<translation>Bienvenido a LXQt</translation>
</message>
<message>
<location filename="../src/wmselectdialog.cpp" line="65"/>
<source>Other ...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/wmselectdialog.cpp" line="66"/>
<source>Choose your favorite one.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/wmselectdialog.ui" line="20"/>
<source><html><head/><body><p><span style=" font-weight:600;">Welcome to LXQt</span></p><p>Please select your default Window Manager.</p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/wmselectdialog.ui" line="71"/>
<source>You will be able to change this at any time through Preferences -> Session Settings -> Basic Settings.</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
|
stefonarch/lxqt-session
|
lxqt-session/translations/lxqt-session_es_UY.ts
|
TypeScript
|
lgpl-2.1
| 2,573
|
/*BHEADER**********************************************************************
* Copyright (c) 2008, Lawrence Livermore National Security, LLC.
* Produced at the Lawrence Livermore National Laboratory.
* This file is part of HYPRE. See file COPYRIGHT for details.
*
* HYPRE is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License (as published by the Free
* Software Foundation) version 2.1 dated February 1999.
*
* $Revision$
***********************************************************************EHEADER*/
/*****************************************************************************
*
* This code implements a class for a dense block of a compressed sparse row
* matrix.
*
*****************************************************************************/
#ifndef hypre_BCSR_MATRIX_DENSE_BLOCK_HEADER
#define hypre_BCSR_MATRIX_DENSE_BLOCK_HEADER
typedef struct {
HYPRE_Real* data;
HYPRE_Int num_rows;
HYPRE_Int num_cols;
} hypre_BCSRMatrixDenseBlock;
/*****************************************************************************
*
* Prototypes
*
*****************************************************************************/
hypre_BCSRMatrixDenseBlock*
hypre_BCSRMatrixDenseBlockCreate(HYPRE_Int num_rows, HYPRE_Int num_cols);
HYPRE_Int
hypre_BCSRMatrixDenseBlockDestroy(hypre_BCSRMatrixDenseBlock* A);
HYPRE_Int
hypre_BCSRMatrixDenseBlockInitialise(hypre_BCSRMatrixDenseBlock* A);
HYPRE_Int
hypre_BCSRMatrixDenseBlockFillData(hypre_BCSRMatrixDenseBlock* A,
HYPRE_Real* data);
HYPRE_Int
hypre_BCSRMatrixDenseBlockGetData(hypre_BCSRMatrixDenseBlock* A,
HYPRE_Real* data);
hypre_BCSRMatrixDenseBlock*
hypre_BCSRMatrixDenseBlockCopy(hypre_BCSRMatrixDenseBlock* A);
HYPRE_Int
hypre_BCSRMatrixDenseBlockAdd(hypre_BCSRMatrixDenseBlock* A,
hypre_BCSRMatrixDenseBlock* B);
HYPRE_Int
hypre_BCSRMatrixDenseBlockMultiply(hypre_BCSRMatrixDenseBlock* A,
hypre_BCSRMatrixDenseBlock* B);
HYPRE_Int
hypre_BCSRMatrixDenseBlockNeg(hypre_BCSRMatrixDenseBlock* A);
hypre_BCSRMatrixDenseBlock*
hypre_BCSRMatrixDenseBlockDiag(hypre_BCSRMatrixDenseBlock* A);
HYPRE_Int
hypre_BCSRMatrixDenseBlockMulInv(hypre_BCSRMatrixDenseBlock* A,
hypre_BCSRMatrixDenseBlock* B);
HYPRE_Int
hypre_BCSRMatrixDenseBlockMultiplyInverse2(hypre_BCSRMatrixDenseBlock* A,
hypre_BCSRMatrixDenseBlock* B);
HYPRE_Int
hypre_BCSRMatrixDenseBlockTranspose(hypre_BCSRMatrixDenseBlock* A);
HYPRE_Int
hypre_BCSRMatrixBlockMatvec(HYPRE_Real alpha, hypre_BCSRMatrixDenseBlock* A,
HYPRE_Real* x_data, HYPRE_Real beta, HYPRE_Real* y_data);
HYPRE_Int
hypre_BCSRMatrixBlockMatvecT(HYPRE_Real alpha, hypre_BCSRMatrixDenseBlock* A,
HYPRE_Real* x_data, HYPRE_Real beta, HYPRE_Real* y_data);
HYPRE_Real
hypre_BCSRMatrixDenseBlockNorm(hypre_BCSRMatrixDenseBlock* A,
const char* norm);
HYPRE_Int
hypre_BCSRMatrixDenseBlockPrint(hypre_BCSRMatrixDenseBlock* A,
FILE* out_file);
#ifdef hypre_BCSR_MATRIX_USE_DENSE_BLOCKS
#define hypre_BCSRMatrixBlock hypre_BCSRMatrixDenseBlock
#define hypre_BCSRMatrixBlockCreate hypre_BCSRMatrixDenseBlockCreate
#define hypre_BCSRMatrixBlockDestroy hypre_BCSRMatrixDenseBlockDestroy
#define hypre_BCSRMatrixBlockInitialise hypre_BCSRMatrixDenseBlockInitialise
#define hypre_BCSRMatrixBlockFillData hypre_BCSRMatrixDenseBlockFillData
#define hypre_BCSRMatrixBlockGetData hypre_BCSRMatrixDenseBlockGetData
#define hypre_BCSRMatrixBlockCopy hypre_BCSRMatrixDenseBlockCopy
#define hypre_BCSRMatrixBlockAdd hypre_BCSRMatrixDenseBlockAdd
#define hypre_BCSRMatrixBlockMultiply hypre_BCSRMatrixDenseBlockMultiply
#define hypre_BCSRMatrixBlockNeg hypre_BCSRMatrixDenseBlockNeg
#define hypre_BCSRMatrixBlockDiag hypre_BCSRMatrixDenseBlockDiag
#define hypre_BCSRMatrixBlockMulInv hypre_BCSRMatrixDenseBlockMulInv
#define hypre_BCSRMatrixBlockMultiplyInverse2 hypre_BCSRMatrixDenseBlockMultiplyInverse2
#define hypre_BCSRMatrixBlockTranspose hypre_BCSRMatrixDenseBlockTranspose
#define hypre_BCSRMatrixBlockMatvec hypre_BCSRMatrixDenseBlockMatvec
#define hypre_BCSRMatrixBlockMatvecT hypre_BCSRMatrixDenseBlockMatvecT
#define hypre_BCSRMatrixBlockNorm hypre_BCSRMatrixDenseBlockNorm
#define hypre_BCSRMatrixBlockPrint hypre_BCSRMatrixDenseBlockPrint
#endif
#endif
|
jbakosi/HYPRE
|
src/seq_ls/pamg/bcsr_matrix_dense_block.h
|
C
|
lgpl-2.1
| 4,311
|
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
#
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
import datetime as dt
class Lammps(CMakePackage):
"""LAMMPS stands for Large-scale Atomic/Molecular Massively
Parallel Simulator. This package uses patch releases, not
stable release.
See https://github.com/spack/spack/pull/5342 for a detailed
discussion.
"""
homepage = "http://lammps.sandia.gov/"
url = "https://github.com/lammps/lammps/archive/patch_1Sep2017.tar.gz"
git = "https://github.com/lammps/lammps.git"
tags = ['ecp', 'ecp-apps']
version('develop', branch='master')
version('20180629', '6d5941863ee25ad2227ff3b7577d5e7c')
version('20180316', '25bad35679583e0dd8cb8753665bb84b')
version('20180222', '4d0513e3183bd57721814d217fdaf957')
version('20170922', '4306071f919ec7e759bda195c26cfd9a')
version('20170901', '767e7f07289663f033474dfe974974e7')
def url_for_version(self, version):
vdate = dt.datetime.strptime(str(version), "%Y%m%d")
return "https://github.com/lammps/lammps/archive/patch_{0}.tar.gz".format(
vdate.strftime("%d%b%Y").lstrip('0'))
supported_packages = ['asphere', 'body', 'class2', 'colloid', 'compress',
'coreshell', 'dipole', 'granular', 'kspace', 'latte',
'manybody', 'mc', 'meam', 'misc', 'molecule',
'mpiio', 'peri', 'poems', 'python', 'qeq', 'reax',
'replica', 'rigid', 'shock', 'snap', 'srd',
'user-atc', 'user-h5md', 'user-lb', 'user-misc',
'user-netcdf', 'user-omp', 'voronoi']
for pkg in supported_packages:
variant(pkg, default=False,
description='Activate the {0} package'.format(pkg))
variant('lib', default=True,
description='Build the liblammps in addition to the executable')
variant('mpi', default=True,
description='Build with mpi')
depends_on('mpi', when='+mpi')
depends_on('mpi', when='+mpiio')
depends_on('fftw', when='+kspace')
depends_on('voropp', when='+voronoi')
depends_on('netcdf+mpi', when='+user-netcdf')
depends_on('blas', when='+user-atc')
depends_on('lapack', when='+user-atc')
depends_on('latte@1.0.1', when='@:20180222+latte')
depends_on('latte@1.1.1:', when='@20180316:20180628+latte')
depends_on('latte@1.2.1:', when='@20180629:+latte')
depends_on('blas', when='+latte')
depends_on('lapack', when='+latte')
depends_on('python', when='+python')
depends_on('mpi', when='+user-lb')
depends_on('mpi', when='+user-h5md')
depends_on('hdf5', when='+user-h5md')
conflicts('+body', when='+poems@:20180628')
conflicts('+latte', when='@:20170921')
conflicts('+python', when='~lib')
conflicts('+qeq', when='~manybody')
conflicts('+user-atc', when='~manybody')
conflicts('+user-misc', when='~manybody')
conflicts('+user-phonon', when='~kspace')
conflicts('+user-misc', when='~manybody')
patch("lib.patch", when="@20170901")
patch("660.patch", when="@20170922")
root_cmakelists_dir = 'cmake'
def cmake_args(self):
spec = self.spec
mpi_prefix = 'ENABLE'
pkg_prefix = 'ENABLE'
if spec.satisfies('@20180629:'):
mpi_prefix = 'BUILD'
pkg_prefix = 'PKG'
args = [
'-DBUILD_SHARED_LIBS={0}'.format(
'ON' if '+lib' in spec else 'OFF'),
'-D{0}_MPI={1}'.format(
mpi_prefix,
'ON' if '+mpi' in spec else 'OFF')
]
if spec.satisfies('@20180629:+lib'):
args.append('-DBUILD_LIB=ON')
for pkg in self.supported_packages:
opt = '-D{0}_{1}'.format(pkg_prefix, pkg.upper())
if '+{0}'.format(pkg) in spec:
args.append('{0}=ON'.format(opt))
else:
args.append('{0}=OFF'.format(opt))
if '+kspace' in spec:
args.append('-DFFT=FFTW3')
return args
|
krafczyk/spack
|
var/spack/repos/builtin/packages/lammps/package.py
|
Python
|
lgpl-2.1
| 5,249
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LCOV - doc-coverage.info - Cqrs.WebApi/SignalR/Hubs/ISingleSignOnTokenNotificationHub.cs</title>
<link rel="stylesheet" type="text/css" href="../../../gcov.css">
</head>
<body>
<table width="100%" border=0 cellspacing=0 cellpadding=0>
<tr><td class="title">LCOV - code coverage report</td></tr>
<tr><td class="ruler"><img src="../../../glass.png" width=3 height=3 alt=""></td></tr>
<tr>
<td width="100%">
<table cellpadding=1 border=0 width="100%">
<tr>
<td width="10%" class="headerItem">Current view:</td>
<td width="35%" class="headerValue"><a href="../../../index.html">top level</a> - <a href="index.html">Cqrs.WebApi/SignalR/Hubs</a> - ISingleSignOnTokenNotificationHub.cs</td>
<td width="5%"></td>
<td width="15%"></td>
<td width="10%" class="headerCovTableHead">Hit</td>
<td width="10%" class="headerCovTableHead">Total</td>
<td width="15%" class="headerCovTableHead">Coverage</td>
</tr>
<tr>
<td class="headerItem">Test:</td>
<td class="headerValue">doc-coverage.info</td>
<td></td>
<td class="headerItem">Lines:</td>
<td class="headerCovTableEntry">4</td>
<td class="headerCovTableEntry">4</td>
<td class="headerCovTableEntryHi">100.0 %</td>
</tr>
<tr>
<td class="headerItem">Date:</td>
<td class="headerValue">2017-07-26</td>
<td></td>
</tr>
<tr><td><img src="../../../glass.png" width=3 height=3 alt=""></td></tr>
</table>
</td>
</tr>
<tr><td class="ruler"><img src="../../../glass.png" width=3 height=3 alt=""></td></tr>
</table>
<table cellpadding=0 cellspacing=0 border=0>
<tr>
<td><br></td>
</tr>
<tr>
<td>
<pre class="sourceHeading"> Line data Source code</pre>
<pre class="source">
<span class="lineNum"> 1 </span> : using System;
<span class="lineNum"> 2 </span> : using Cqrs.Authentication;
<span class="lineNum"> 3 </span> : using Cqrs.Events;
<span class="lineNum"> 4 </span> :
<span class="lineNum"> 5 </span> : namespace Cqrs.WebApi.SignalR.Hubs
<span class="lineNum"> 6 </span> : {
<span class="lineNum"> 7 </span> : public interface ISingleSignOnTokenNotificationHub
<span class="lineNum"> 8 </span> : {
<span class="lineNum"> 9 </span> : /// <summary>
<span class="lineNum"> 10 </span> : /// Send out an event to specific user RSNs
<span class="lineNum"> 11 </span> : /// </summary>
<span class="lineNum"> 12 </span><span class="lineCov"> 1 : void SendUsersEvent<TSingleSignOnToken>(IEvent<TSingleSignOnToken> eventData, params Guid[] userRsnCollection)</span>
<span class="lineNum"> 13 </span> : where TSingleSignOnToken : ISingleSignOnToken;
<span class="lineNum"> 14 </span> :
<span class="lineNum"> 15 </span> : /// <summary>
<span class="lineNum"> 16 </span> : /// Send out an event to specific user token
<span class="lineNum"> 17 </span> : /// </summary>
<span class="lineNum"> 18 </span><span class="lineCov"> 1 : void SendUserEvent<TSingleSignOnToken>(IEvent<TSingleSignOnToken> eventData, string userToken)</span>
<span class="lineNum"> 19 </span> : where TSingleSignOnToken : ISingleSignOnToken;
<span class="lineNum"> 20 </span> :
<span class="lineNum"> 21 </span> : /// <summary>
<span class="lineNum"> 22 </span> : /// Send out an event to all users
<span class="lineNum"> 23 </span> : /// </summary>
<span class="lineNum"> 24 </span><span class="lineCov"> 1 : void SendAllUsersEvent<TSingleSignOnToken>(IEvent<TSingleSignOnToken> eventData)</span>
<span class="lineNum"> 25 </span> : where TSingleSignOnToken : ISingleSignOnToken;
<span class="lineNum"> 26 </span> :
<span class="lineNum"> 27 </span> : /// <summary>
<span class="lineNum"> 28 </span> : /// Send out an event to all users except the specific user token
<span class="lineNum"> 29 </span> : /// </summary>
<span class="lineNum"> 30 </span><span class="lineCov"> 1 : void SendExceptThisUserEvent<TSingleSignOnToken>(IEvent<TSingleSignOnToken> eventData, string userToken)</span>
<span class="lineNum"> 31 </span> : where TSingleSignOnToken : ISingleSignOnToken;
<span class="lineNum"> 32 </span> : }
<span class="lineNum"> 33 </span> : }
</pre>
</td>
</tr>
</table>
<br>
<table width="100%" border=0 cellspacing=0 cellpadding=0>
<tr><td class="ruler"><img src="../../../glass.png" width=3 height=3 alt=""></td></tr>
<tr><td class="versionInfo">Generated by: <a href="http://ltp.sourceforge.net/coverage/lcov.php" target="_parent">LCOV version 1.10</a></td></tr>
</table>
<br>
</body>
</html>
|
Chinchilla-Software-Com/CQRS
|
wiki/docs/2.1/coverage-report/Cqrs.WebApi/SignalR/Hubs/ISingleSignOnTokenNotificationHub.cs.gcov.html
|
HTML
|
lgpl-2.1
| 5,875
|
/*
*********************************************************************
**
** 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 autotests 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$
**
*********************************************************************
*/
/********************************************************************************
** Form generated from reading UI file 'qtgradientviewdialog.ui'
**
** Created: Fri Sep 4 10:17:14 2009
** by: Qt User Interface Compiler version 4.6.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef QTGRADIENTVIEWDIALOG_H
#define QTGRADIENTVIEWDIALOG_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QDialog>
#include <QtGui/QDialogButtonBox>
#include <QtGui/QHeaderView>
#include <QtGui/QVBoxLayout>
#include "qtgradientview.h"
QT_BEGIN_NAMESPACE
class Ui_QtGradientViewDialog
{
public:
QVBoxLayout *vboxLayout;
QtGradientView *gradientView;
QDialogButtonBox *buttonBox;
void setupUi(QDialog *QtGradientViewDialog)
{
if (QtGradientViewDialog->objectName().isEmpty())
QtGradientViewDialog->setObjectName(QString::fromUtf8("QtGradientViewDialog"));
QtGradientViewDialog->resize(178, 72);
vboxLayout = new QVBoxLayout(QtGradientViewDialog);
vboxLayout->setObjectName(QString::fromUtf8("vboxLayout"));
gradientView = new QtGradientView(QtGradientViewDialog);
gradientView->setObjectName(QString::fromUtf8("gradientView"));
QSizePolicy sizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(gradientView->sizePolicy().hasHeightForWidth());
gradientView->setSizePolicy(sizePolicy);
vboxLayout->addWidget(gradientView);
buttonBox = new QDialogButtonBox(QtGradientViewDialog);
buttonBox->setObjectName(QString::fromUtf8("buttonBox"));
buttonBox->setOrientation(Qt::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
vboxLayout->addWidget(buttonBox);
retranslateUi(QtGradientViewDialog);
QObject::connect(buttonBox, SIGNAL(accepted()), QtGradientViewDialog, SLOT(accept()));
QObject::connect(buttonBox, SIGNAL(rejected()), QtGradientViewDialog, SLOT(reject()));
QMetaObject::connectSlotsByName(QtGradientViewDialog);
} // setupUi
void retranslateUi(QDialog *QtGradientViewDialog)
{
QtGradientViewDialog->setWindowTitle(QApplication::translate("QtGradientViewDialog", "Select Gradient", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class QtGradientViewDialog: public Ui_QtGradientViewDialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // QTGRADIENTVIEWDIALOG_H
|
igor-sfdc/qt-wk
|
tests/auto/uic/baseline/qtgradientviewdialog.ui.h
|
C
|
lgpl-2.1
| 4,255
|
// The libMesh Finite Element Library.
// Copyright (C) 2002-2017 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#ifndef LIBMESH_PARALLEL_HISTOGRAM_H
#define LIBMESH_PARALLEL_HISTOGRAM_H
// This class contains all the functionality for bin sorting
// Templated on the type of keys you will be sorting and the
// type of iterator you will be using.
// C++ includes
#include "libmesh/libmesh_common.h" // for libmesh_assert()
#include "libmesh/parallel_object.h"
// Local includes
#include <vector>
#include <iterator>
namespace libMesh
{
namespace Parallel
{
/**
* Defines a histogram to be used in parallel in conjunction with
* a \p BinSorter.
*
* \author Benjamin S. Kirk
* \author John W. Peterson
* \date 2007
* \brief Used in conjunction with a BinSorter for parallel sorting.
*/
template <typename KeyType, typename IdxType=unsigned int>
class Histogram : public ParallelObject
{
// The type of iterator we will be using is inferred from KeyType
typedef typename std::vector<KeyType>::const_iterator IterType;
public:
/**
* Constructor.
*/
explicit
Histogram (const Parallel::Communicator & comm,
const std::vector<KeyType> & d);
/**
* The actual function which sorts the data into
* nbins. Currently based on the global min and
* max which you must provide e.g. by using MPI.
*/
void make_histogram (const IdxType nbins,
KeyType max,
KeyType min);
/**
* Build the histogram across all processors and store the
* result in the input vector \p hist.
*/
void build_histogram ();
/**
* \returns The raw histogram data to the user.
*/
const std::vector<IdxType> & get_histogram() const;
/**
* The number of bins in the histogram.
*/
IdxType n_bins () const;
/**
* \returns The size of local bin \p bin.
*/
IdxType local_bin_size (const IdxType bin) const;
/**
* \returns The size of global bin \p bin.
*
* Requires that the user first call \p build_histogram().
*/
IdxType global_bin_size (const IdxType bin) const;
/**
* \returns The lower boundary of bin \p bin.
*/
double lower_bound (const IdxType bin) const;
/**
* \returns The upper boundary of bin \p bin.
*/
double upper_bound (const IdxType bin) const;
private:
const std::vector<KeyType> & data;
std::vector<IdxType> hist; // The actual histogram
std::vector<double> bin_bounds; // The boundary values of each bin
std::vector<IterType> bin_iters; // Iterators to the bin boundaries in data
};
template <typename KeyType, typename IdxType>
inline
const std::vector<IdxType> & Histogram<KeyType,IdxType>::get_histogram () const
{
return hist;
}
template <typename KeyType, typename IdxType>
inline
IdxType Histogram<KeyType,IdxType>::n_bins () const
{
if (bin_iters.empty())
return 0;
return cast_int<IdxType>(bin_iters.size()-1);
}
template <typename KeyType, typename IdxType>
inline
IdxType Histogram<KeyType,IdxType>::local_bin_size (const IdxType bin) const
{
libmesh_assert_less ((bin+1), bin_iters.size());
// The number of entries in the bin (locally)
return cast_int<IdxType>
(std::distance (bin_iters[bin], bin_iters[bin+1]));
}
template <typename KeyType, typename IdxType>
inline
IdxType Histogram<KeyType,IdxType>::global_bin_size (const IdxType bin) const
{
libmesh_assert_less (bin, hist.size());
// The number of entries in the bin (globally)
return hist[bin];
}
template <typename KeyType, typename IdxType>
inline
double Histogram<KeyType,IdxType>::lower_bound (const IdxType bin) const
{
libmesh_assert_less ((bin+1), bin_bounds.size());
return bin_bounds[bin];
}
template <typename KeyType, typename IdxType>
inline
double Histogram<KeyType,IdxType>::upper_bound (const IdxType bin) const
{
libmesh_assert_less ((bin+1), bin_bounds.size());
return bin_bounds[bin+1];
}
}
} // namespace libMesh
#endif // LIBMESH_PARALLEL_HISTOGRAM_H
|
balborian/libmesh
|
include/parallel/parallel_histogram.h
|
C
|
lgpl-2.1
| 4,729
|
/*
Copyright (C) 2012-2014 Fredrik Johansson
This file is part of Arb.
Arb is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <http://www.gnu.org/licenses/>.
*/
#include "arb.h"
int main()
{
slong iter;
flint_rand_t state;
flint_printf("add_fmpz....");
fflush(stdout);
flint_randinit(state);
for (iter = 0; iter < 10000 * arb_test_multiplier(); iter++)
{
arb_t a, b, c, d;
fmpz_t x;
slong prec;
arb_init(a);
arb_init(b);
arb_init(c);
arb_init(d);
fmpz_init(x);
arb_randtest_special(a, state, 1 + n_randint(state, 2000), 100);
arb_randtest_special(b, state, 1 + n_randint(state, 2000), 100);
arb_randtest_special(c, state, 1 + n_randint(state, 2000), 100);
fmpz_randtest(x, state, 1 + n_randint(state, 2000));
prec = 2 + n_randint(state, 2000);
arb_set_fmpz(b, x);
arb_add_fmpz(c, a, x, prec);
arb_add(d, a, b, prec);
if (!arb_equal(c, d))
{
flint_printf("FAIL\n\n");
flint_printf("a = "); arb_print(a); flint_printf("\n\n");
flint_printf("b = "); arb_print(b); flint_printf("\n\n");
flint_printf("c = "); arb_print(c); flint_printf("\n\n");
flint_printf("d = "); arb_print(d); flint_printf("\n\n");
flint_abort();
}
arb_clear(a);
arb_clear(b);
arb_clear(c);
arb_clear(d);
fmpz_clear(x);
}
/* aliasing */
for (iter = 0; iter < 10000 * arb_test_multiplier(); iter++)
{
arb_t a, b, c;
fmpz_t x;
slong prec;
arb_init(a);
arb_init(b);
arb_init(c);
fmpz_init(x);
arb_randtest_special(a, state, 1 + n_randint(state, 2000), 100);
arb_randtest_special(b, state, 1 + n_randint(state, 2000), 100);
arb_randtest_special(c, state, 1 + n_randint(state, 2000), 100);
fmpz_randtest(x, state, 1 + n_randint(state, 2000));
prec = 2 + n_randint(state, 2000);
arb_set_fmpz(b, x);
arb_add_fmpz(c, a, x, prec);
arb_add_fmpz(a, a, x, prec);
if (!arb_equal(a, c))
{
flint_printf("FAIL (aliasing)\n\n");
flint_printf("a = "); arb_print(a); flint_printf("\n\n");
flint_printf("b = "); arb_print(b); flint_printf("\n\n");
flint_printf("c = "); arb_print(c); flint_printf("\n\n");
flint_abort();
}
arb_clear(a);
arb_clear(b);
arb_clear(c);
fmpz_clear(x);
}
flint_randclear(state);
flint_cleanup();
flint_printf("PASS\n");
return EXIT_SUCCESS;
}
|
fredrik-johansson/arb
|
arb/test/t-add_fmpz.c
|
C
|
lgpl-2.1
| 2,923
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.