code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
/* microprotocols.c - definitions for minimalist and non-validating protocols
*
* Copyright (C) 2003-2004 Federico Di Gregorio <fog@debian.org>
*
* This file is part of psycopg and was adapted for pysqlite. Federico Di
* Gregorio gave the permission to use it within pysqlite under the following
* license:
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef PSYCOPG_MICROPROTOCOLS_H
#define PSYCOPG_MICROPROTOCOLS_H 1
#include <Python.h>
/** adapters registry **/
extern PyObject *psyco_adapters;
/** the names of the three mandatory methods **/
#define MICROPROTOCOLS_GETQUOTED_NAME "getquoted"
#define MICROPROTOCOLS_GETSTRING_NAME "getstring"
#define MICROPROTOCOLS_GETBINARY_NAME "getbinary"
/** exported functions **/
/* used by module.c to init the microprotocols system */
extern int pysqlite_microprotocols_init(PyObject *dict);
extern int pysqlite_microprotocols_add(
PyTypeObject *type, PyObject *proto, PyObject *cast);
extern PyObject *pysqlite_microprotocols_adapt(
PyObject *obj, PyObject *proto, PyObject *alt);
extern PyObject *
pysqlite_adapt(pysqlite_Cursor* self, PyObject *args);
#define pysqlite_adapt_doc \
"adapt(obj, protocol, alternate) -> adapt obj to given protocol. Non-standard."
#endif /* !defined(PSYCOPG_MICROPROTOCOLS_H) */
| 0o2batodd-tntlovspenny | src/microprotocols.h | C | mit | 2,118 |
#!/usr/bin/env python
#
# Cross-compile and build pysqlite installers for win32 on Linux or Mac OS X.
#
# The way this works is very ugly, but hey, it *works*! And I didn't have to
# reinvent the wheel using NSIS.
import os
import sys
import urllib
import zipfile
from setup import get_amalgamation
# Cross-compiler
if sys.platform == "darwin":
CC = "/usr/local/i386-mingw32-4.3.0/bin/i386-mingw32-gcc"
LIBDIR = "lib.macosx-10.6-i386-2.5"
STRIP = "/usr/local/i386-mingw32-4.3.0/bin/i386-mingw32-gcc --strip-all"
else:
CC = "/usr/bin/i586-mingw32msvc-gcc"
LIBDIR = "lib.linux-i686-2.5"
STRIP = "strip --strip-all"
# Optimization settings
OPT = "-O2"
# pysqlite sources + SQLite amalgamation
SRC = "src/module.c src/connection.c src/cursor.c src/cache.c src/microprotocols.c src/prepare_protocol.c src/statement.c src/util.c src/row.c amalgamation/sqlite3.c"
# You will need to fetch these from
# https://pyext-cross.pysqlite.googlecode.com/hg/
CROSS_TOOLS = "../pysqlite-pyext-cross"
def execute(cmd):
print cmd
return os.system(cmd)
def compile_module(pyver):
VER = pyver.replace(".", "")
INC = "%s/python%s/include" % (CROSS_TOOLS, VER)
vars = locals()
vars.update(globals())
cmd = '%(CC)s -mno-cygwin %(OPT)s -mdll -DMODULE_NAME=\\"pysqlite2._sqlite\\" -DSQLITE_ENABLE_RTREE=1 -DSQLITE_ENABLE_FTS3=1 -I amalgamation -I %(INC)s -I . %(SRC)s -L %(CROSS_TOOLS)s/python%(VER)s/libs -lpython%(VER)s -o build/%(LIBDIR)s/pysqlite2/_sqlite.pyd' % vars
execute(cmd)
execute("%(STRIP)s build/%(LIBDIR)s/pysqlite2/_sqlite.pyd" % vars)
def main():
vars = locals()
vars.update(globals())
get_amalgamation()
for ver in ["2.5", "2.6", "2.7"]:
execute("rm -rf build")
# First, compile the host version. This is just to get the .py files in place.
execute("python2.5 setup.py build")
# Yes, now delete the host extension module. What a waste of time.
os.unlink("build/%(LIBDIR)s/pysqlite2/_sqlite.so" % vars)
# Cross-compile win32 extension module.
compile_module(ver)
# Prepare for target Python version.
libdir_ver = LIBDIR[:-3] + ver
os.rename("build/%(LIBDIR)s" % vars, "build/" + libdir_ver)
# And create the installer!
os.putenv("PYEXT_CROSS", CROSS_TOOLS)
execute("python2.5 setup.py cross_bdist_wininst --skip-build --target-version=" + ver)
if __name__ == "__main__":
main()
| 0o2batodd-tntlovspenny | mkwin32.py | Python | mit | 2,464 |
/*
:Author: David Goodger
:Contact: goodger@users.sourceforge.net
:Date: $Date: 2005-04-25 22:24:49 +0200 (Mon, 25 Apr 2005) $
:Version: $Revision: 3256 $
:Copyright: This stylesheet has been placed in the public domain.
Default cascading style sheet for the HTML output of Docutils.
*/
/* "! important" is used here to override other ``margin-top`` and
``margin-bottom`` styles that are later in the stylesheet or
more specific. See http://www.w3.org/TR/CSS1#the-cascade */
.first {
margin-top: 0 ! important }
.last {
margin-bottom: 0 ! important }
.hidden {
display: none }
a.toc-backref {
text-decoration: none ;
color: black }
blockquote.epigraph {
margin: 2em 5em ; }
dl.docutils dd {
margin-bottom: 0.5em }
/* Uncomment (and remove this text!) to get bold-faced definition list terms
dl.docutils dt {
font-weight: bold }
*/
div.abstract {
margin: 2em 5em }
div.abstract p.topic-title {
font-weight: bold ;
text-align: center }
div.admonition, div.attention, div.caution, div.danger, div.error,
div.hint, div.important, div.note, div.tip, div.warning {
margin: 2em ;
border: medium outset ;
padding: 1em }
div.admonition p.admonition-title, div.hint p.admonition-title,
div.important p.admonition-title, div.note p.admonition-title,
div.tip p.admonition-title {
font-weight: bold ;
font-family: sans-serif }
div.attention p.admonition-title, div.caution p.admonition-title,
div.danger p.admonition-title, div.error p.admonition-title,
div.warning p.admonition-title {
color: red ;
font-weight: bold ;
font-family: sans-serif }
/* Uncomment (and remove this text!) to get reduced vertical space in
compound paragraphs.
div.compound .compound-first, div.compound .compound-middle {
margin-bottom: 0.5em }
div.compound .compound-last, div.compound .compound-middle {
margin-top: 0.5em }
*/
div.dedication {
margin: 2em 5em ;
text-align: center ;
font-style: italic }
div.dedication p.topic-title {
font-weight: bold ;
font-style: normal }
div.figure {
margin-left: 2em }
div.footer, div.header {
font-size: smaller }
div.line-block {
display: block ;
margin-top: 1em ;
margin-bottom: 1em }
div.line-block div.line-block {
margin-top: 0 ;
margin-bottom: 0 ;
margin-left: 1.5em }
div.sidebar {
margin-left: 1em ;
border: medium outset ;
padding: 1em ;
background-color: #ffffee ;
width: 40% ;
float: right ;
clear: right }
div.sidebar p.rubric {
font-family: sans-serif ;
font-size: medium }
div.system-messages {
margin: 5em }
div.system-messages h1 {
color: red }
div.system-message {
border: medium outset ;
padding: 1em }
div.system-message p.system-message-title {
color: red ;
font-weight: bold }
div.topic {
margin: 2em }
h1.title {
text-align: center }
h2.subtitle {
text-align: center }
hr.docutils {
width: 75% }
ol.simple, ul.simple {
margin-bottom: 1em }
ol.arabic {
list-style: decimal }
ol.loweralpha {
list-style: lower-alpha }
ol.upperalpha {
list-style: upper-alpha }
ol.lowerroman {
list-style: lower-roman }
ol.upperroman {
list-style: upper-roman }
p.attribution {
text-align: right ;
margin-left: 50% }
p.caption {
font-style: italic }
p.credits {
font-style: italic ;
font-size: smaller }
p.label {
white-space: nowrap }
p.rubric {
font-weight: bold ;
font-size: larger ;
color: maroon ;
text-align: center }
p.sidebar-title {
font-family: sans-serif ;
font-weight: bold ;
font-size: larger }
p.sidebar-subtitle {
font-family: sans-serif ;
font-weight: bold }
p.topic-title {
font-weight: bold }
pre.address {
margin-bottom: 0 ;
margin-top: 0 ;
font-family: serif ;
font-size: 100% }
pre.line-block {
font-family: serif ;
font-size: 100% }
pre.literal-block, pre.doctest-block {
margin-left: 2em ;
margin-right: 2em ;
background-color: #eeeeee }
span.classifier {
font-family: sans-serif ;
font-style: oblique }
span.classifier-delimiter {
font-family: sans-serif ;
font-weight: bold }
span.interpreted {
font-family: sans-serif }
span.option {
white-space: nowrap }
span.pre {
white-space: pre }
span.problematic {
color: red }
table.citation {
border-left: solid thin gray }
table.docinfo {
margin: 2em 4em }
table.docutils {
margin-top: 0.5em ;
margin-bottom: 0.5em }
table.footnote {
border-left: solid thin black }
table.docutils td, table.docutils th,
table.docinfo td, table.docinfo th {
padding-left: 0.5em ;
padding-right: 0.5em ;
vertical-align: top }
table.docutils th.field-name, table.docinfo th.docinfo-name {
font-weight: bold ;
text-align: left ;
white-space: nowrap ;
padding-left: 0 }
h1 tt.docutils, h2 tt.docutils, h3 tt.docutils,
h4 tt.docutils, h5 tt.docutils, h6 tt.docutils {
font-size: 100% }
tt.docutils {
background-color: #eeeeee }
ul.auto-toc {
list-style-type: none }
body {
background-color: #eeeeff;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
| 0o2batodd-tntlovspenny | doc/docutils.css | CSS | mit | 5,000 |
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
ALLSPHINXOPTS = -d .build/doctrees -D latex_paper_size=$(PAPER) \
$(SPHINXOPTS) .
.PHONY: help clean html web htmlhelp latex changes linkcheck
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " web to make files usable by Sphinx.web"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " changes to make an overview over all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
clean:
-rm -rf .build/*
html:
mkdir -p .build/html .build/doctrees
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) .build/html
@echo
@echo "Build finished. The HTML pages are in .build/html."
web:
mkdir -p .build/web .build/doctrees
$(SPHINXBUILD) -b web $(ALLSPHINXOPTS) .build/web
@echo
@echo "Build finished; now you can run"
@echo " python -m sphinx.web .build/web"
@echo "to start the server."
htmlhelp:
mkdir -p .build/htmlhelp .build/doctrees
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) .build/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in .build/htmlhelp."
latex:
mkdir -p .build/latex .build/doctrees
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) .build/latex
@echo
@echo "Build finished; the LaTeX files are in .build/latex."
@echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
"run these through (pdf)latex."
changes:
mkdir -p .build/changes .build/doctrees
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) .build/changes
@echo
@echo "The overview file is in .build/changes."
linkcheck:
mkdir -p .build/linkcheck .build/doctrees
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) .build/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in .build/linkcheck/output.txt."
| 0o2batodd-tntlovspenny | doc/sphinx/Makefile | Makefile | mit | 2,107 |
# -*- coding: utf-8 -*-
#
# pysqlite documentation build configuration file, created by
# sphinx-quickstart.py on Sat Mar 22 02:47:54 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed automatically).
#
# All configuration values have a default value; values that are commented out
# serve to show the default value.
import sys
# If your extensions are in another directory, add it here.
#sys.path.append('some/directory')
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.addons.*') or your custom ones.
#extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['.templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General substitutions.
project = 'pysqlite'
copyright = u'2008-2009, Gerhard Häring'
# The default replacements for |version| and |release|, also used in various
# other places throughout the built documents.
#
# The short X.Y version.
version = '2.6'
# The full version, including alpha/beta/rc tags.
release = '2.6.0'
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# Options for HTML output
# -----------------------
# The style sheet to use for HTML and HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
# given in html_static_path.
html_style = 'default.css'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['.static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Content template for the index page.
#html_index = ''
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If true, the reST sources are included in the HTML build as _sources/<name>.
#html_copy_source = True
# Output file base name for HTML help builder.
htmlhelp_basename = 'pysqlitedoc'
# Options for LaTeX output
# ------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
#latex_documents = []
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
| 0o2batodd-tntlovspenny | doc/sphinx/conf.py | Python | mit | 4,030 |
from pysqlite2 import dbapi2 as sqlite3
FIELD_MAX_WIDTH = 20
TABLE_NAME = 'people'
SELECT = 'select * from %s order by age, name_last' % TABLE_NAME
con = sqlite3.connect("mydb")
cur = con.cursor()
cur.execute(SELECT)
# Print a header.
for fieldDesc in cur.description:
print fieldDesc[0].ljust(FIELD_MAX_WIDTH) ,
print # Finish the header with a newline.
print '-' * 78
# For each row, print the value of each field left-justified within
# the maximum possible width of that field.
fieldIndices = range(len(cur.description))
for row in cur:
for fieldIndex in fieldIndices:
fieldValue = str(row[fieldIndex])
print fieldValue.ljust(FIELD_MAX_WIDTH) ,
print # Finish the row with a newline.
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/simple_tableprinter.py | Python | mit | 722 |
from pysqlite2 import dbapi2 as sqlite3
def progress():
print "Query still executing. Please wait ..."
con = sqlite3.connect(":memory:")
con.execute("create table test(x)")
# Let's create some data
con.executemany("insert into test(x) values (?)", [(x,) for x in xrange(300)])
# A progress handler, executed every 10 million opcodes
con.set_progress_handler(progress, 10000000)
# A particularly long-running query
killer_stament = """
select count(*) from (
select t1.x from test t1, test t2, test t3
)
"""
con.execute(killer_stament)
print "-" * 50
# Clear the progress handler
con.set_progress_handler(None, 0)
con.execute(killer_stament)
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/progress.py | Python | mit | 674 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
cur = con.cursor()
SELECT = "select name_last, age from people order by age, name_last"
# 1. Iterate over the rows available from the cursor, unpacking the
# resulting sequences to yield their elements (name_last, age):
cur.execute(SELECT)
for (name_last, age) in cur:
print '%s is %d years old.' % (name_last, age)
# 2. Equivalently:
cur.execute(SELECT)
for row in cur:
print '%s is %d years old.' % (row[0], row[1])
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/execsql_fetchonerow.py | Python | mit | 500 |
from pysqlite2 import dbapi2 as sqlite3
# Create a connection to the database file "mydb":
con = sqlite3.connect("mydb")
# Get a Cursor object that operates in the context of Connection con:
cur = con.cursor()
# Execute the SELECT statement:
cur.execute("select * from people order by age")
# Retrieve all rows as a sequence and print that sequence:
print cur.fetchall()
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/execsql_printall_1.py | Python | mit | 375 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/connect_db_1.py | Python | mit | 71 |
from pysqlite2 import dbapi2 as sqlite3
class MySum:
def __init__(self):
self.count = 0
def step(self, value):
self.count += value
def finalize(self):
return self.count
con = sqlite3.connect(":memory:")
con.create_aggregate("mysum", 1, MySum)
cur = con.cursor()
cur.execute("create table test(i)")
cur.execute("insert into test(i) values (1)")
cur.execute("insert into test(i) values (2)")
cur.execute("select mysum(i) from test")
print cur.fetchone()[0]
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/mysumaggr.py | Python | mit | 495 |
# A minimal SQLite shell for experiments
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect(":memory:")
con.isolation_level = None
cur = con.cursor()
buffer = ""
print "Enter your SQL commands to execute in SQLite."
print "Enter a blank line to exit."
while True:
line = raw_input()
if line == "":
break
buffer += line
if sqlite3.complete_statement(buffer):
try:
buffer = buffer.strip()
cur.execute(buffer)
if buffer.lstrip().upper().startswith("SELECT"):
print cur.fetchall()
except sqlite3.Error, e:
print "An error occurred:", e.args[0]
buffer = ""
con.close()
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/complete_statement.py | Python | mit | 694 |
from pysqlite2 import dbapi2 as sqlite3
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print cur.fetchone()["a"]
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/row_factory.py | Python | mit | 316 |
from pysqlite2 import dbapi2 as sqlite3
import datetime
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("create table test(d date, ts timestamp)")
today = datetime.date.today()
now = datetime.datetime.now()
cur.execute("insert into test(d, ts) values (?, ?)", (today, now))
cur.execute("select d, ts from test")
row = cur.fetchone()
print today, "=>", row[0], type(row[0])
print now, "=>", row[1], type(row[1])
cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"')
row = cur.fetchone()
print "current_date", row[0], type(row[0])
print "current_timestamp", row[1], type(row[1])
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/pysqlite_datetime.py | Python | mit | 693 |
from pysqlite2 import dbapi2 as sqlite3
def authorizer_callback(action, arg1, arg2, dbname, source):
if action != sqlite3.SQLITE_SELECT:
return sqlite3.SQLITE_DENY
if arg1 == "private_table":
return sqlite3.SQLITE_DENY
return sqlite3.SQLITE_OK
con = sqlite3.connect(":memory:")
con.executescript("""
create table public_table(c1, c2);
create table private_table(c1, c2);
""")
con.set_authorizer(authorizer_callback)
try:
con.execute("select * from private_table")
except sqlite3.DatabaseError, e:
print "SELECT FROM private_table =>", e.args[0] # access ... prohibited
try:
con.execute("insert into public_table(c1, c2) values (1, 2)")
except sqlite3.DatabaseError, e:
print "DML command =>", e.args[0] # access ... prohibited
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/authorizer.py | Python | mit | 796 |
from pysqlite2 import dbapi2 as sqlite3
# The shared cache is only available in SQLite versions 3.3.3 or later
# See the SQLite documentaton for details.
sqlite3.enable_shared_cache(True)
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/shared_cache.py | Python | mit | 190 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect(":memory:")
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/connect_db_2.py | Python | mit | 75 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
cur = con.cursor()
who = "Yeltsin"
age = 72
cur.execute("select name_last, age from people where name_last=? and age=?", (who, age))
print cur.fetchone()
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/execute_1.py | Python | mit | 228 |
from __future__ import with_statement
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect(":memory:")
con.execute("create table person (id integer primary key, firstname varchar unique)")
# Successful, con.commit() is called automatically afterwards
with con:
con.execute("insert into person(firstname) values (?)", ("Joe",))
# con.rollback() is called after the with block finishes with an exception, the
# exception is still raised and must be catched
try:
with con:
con.execute("insert into person(firstname) values (?)", ("Joe",))
except sqlite3.IntegrityError:
print "couldn't add Joe twice"
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/ctx_manager.py | Python | mit | 632 |
from pysqlite2 import dbapi2 as sqlite3
import md5
def md5sum(t):
return md5.md5(t).hexdigest()
con = sqlite3.connect(":memory:")
con.create_function("md5", 1, md5sum)
cur = con.cursor()
cur.execute("select md5(?)", ("foo",))
print cur.fetchone()[0]
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/md5func.py | Python | mit | 256 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("select name_last, age from people")
for row in cur:
assert row[0] == row["name_last"]
assert row["name_last"] == row["nAmE_lAsT"]
assert row[1] == row["age"]
assert row[1] == row["AgE"]
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/rowclass.py | Python | mit | 336 |
from pysqlite2 import dbapi2 as sqlite3
class Point(object):
def __init__(self, x, y):
self.x, self.y = x, y
def adapt_point(point):
return "%f;%f" % (point.x, point.y)
sqlite3.register_adapter(Point, adapt_point)
con = sqlite3.connect(":memory:")
cur = con.cursor()
p = Point(4.0, -3.2)
cur.execute("select ?", (p,))
print cur.fetchone()[0]
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/adapter_point_2.py | Python | mit | 363 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
# Create the table
con.execute("create table person(lastname, firstname)")
AUSTRIA = u"\xd6sterreich"
# by default, rows are returned as Unicode
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
assert row[0] == AUSTRIA
# but we can make pysqlite always return bytestrings ...
con.text_factory = str
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
assert type(row[0]) == str
# the bytestrings will be encoded in UTF-8, unless you stored garbage in the
# database ...
assert row[0] == AUSTRIA.encode("utf-8")
# we can also implement a custom text_factory ...
# here we implement one that will ignore Unicode characters that cannot be
# decoded from UTF-8
con.text_factory = lambda x: unicode(x, "utf-8", "ignore")
cur.execute("select ?", ("this is latin1 and would normally create errors" + u"\xe4\xf6\xfc".encode("latin1"),))
row = cur.fetchone()
assert type(row[0]) == unicode
# pysqlite offers a builtin optimized text_factory that will return bytestring
# objects, if the data is in ASCII only, and otherwise return unicode objects
con.text_factory = sqlite3.OptimizedUnicode
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
assert type(row[0]) == unicode
cur.execute("select ?", ("Germany",))
row = cur.fetchone()
assert type(row[0]) == str
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/text_factory.py | Python | mit | 1,370 |
from pysqlite2 import dbapi2 as sqlite3
class CountCursorsConnection(sqlite3.Connection):
def __init__(self, *args, **kwargs):
sqlite3.Connection.__init__(self, *args, **kwargs)
self.numcursors = 0
def cursor(self, *args, **kwargs):
self.numcursors += 1
return sqlite3.Connection.cursor(self, *args, **kwargs)
con = sqlite3.connect(":memory:", factory=CountCursorsConnection)
cur1 = con.cursor()
cur2 = con.cursor()
print con.numcursors
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/countcursors.py | Python | mit | 480 |
from pysqlite2 import dbapi2 as sqlite3
def collate_reverse(string1, string2):
return -cmp(string1, string2)
con = sqlite3.connect(":memory:")
con.create_collation("reverse", collate_reverse)
cur = con.cursor()
cur.execute("create table test(x)")
cur.executemany("insert into test(x) values (?)", [("a",), ("b",)])
cur.execute("select x from test order by x collate reverse")
for row in cur:
print row
con.close()
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/collation_reverse.py | Python | mit | 425 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.executescript("""
create table person(
firstname,
lastname,
age
);
create table book(
title,
author,
published
);
insert into book(title, author, published)
values (
'Dirk Gently''s Holistic Detective Agency',
'Douglas Adams',
1987
);
""")
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/executescript.py | Python | mit | 444 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect(":memory:")
# enable extension loading
con.enable_load_extension(True)
# Load the fulltext search extension
con.execute("select load_extension('./fts3.so')")
# alternatively you can load the extension using an API call:
# con.load_extension("./fts3.so")
# disable extension laoding again
con.enable_load_extension(False)
# example from SQLite wiki
con.execute("create virtual table recipe using fts3(name, ingredients)")
con.executescript("""
insert into recipe (name, ingredients) values ('broccoli stew', 'broccoli peppers cheese tomatoes');
insert into recipe (name, ingredients) values ('pumpkin stew', 'pumpkin onions garlic celery');
insert into recipe (name, ingredients) values ('broccoli pie', 'broccoli cheese onions flour');
insert into recipe (name, ingredients) values ('pumpkin pie', 'pumpkin sugar flour butter');
""")
for row in con.execute("select rowid, name, ingredients from recipe where name match 'pie'"):
print row
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/load_extension.py | Python | mit | 1,032 |
from pysqlite2 import dbapi2 as sqlite3
persons = [
("Hugo", "Boss"),
("Calvin", "Klein")
]
con = sqlite3.connect(":memory:")
# Create the table
con.execute("create table person(firstname, lastname)")
# Fill the table
con.executemany("insert into person(firstname, lastname) values (?, ?)", persons)
# Print the table contents
for row in con.execute("select firstname, lastname from person"):
print row
# Using a dummy WHERE clause to not let SQLite take the shortcut table deletes.
print "I just deleted", con.execute("delete from person where 1=1").rowcount, "rows"
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/shortcut_methods.py | Python | mit | 590 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
cur = con.cursor()
who = "Yeltsin"
age = 72
cur.execute("select name_last, age from people where name_last=:who and age=:age",
locals())
print cur.fetchone()
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/execute_3.py | Python | mit | 236 |
# Not referenced from the documentation, but builds the database file the other
# code snippets expect.
from pysqlite2 import dbapi2 as sqlite3
import os
DB_FILE = "mydb"
if os.path.exists(DB_FILE):
os.remove(DB_FILE)
con = sqlite3.connect(DB_FILE)
cur = con.cursor()
cur.execute("""
create table people
(
name_last varchar(20),
age integer
)
""")
cur.execute("insert into people (name_last, age) values ('Yeltsin', 72)")
cur.execute("insert into people (name_last, age) values ('Putin', 51)")
con.commit()
cur.close()
con.close()
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/createdb.py | Python | mit | 616 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
cur = con.cursor()
who = "Yeltsin"
age = 72
cur.execute("select name_last, age from people where name_last=:who and age=:age",
{"who": who, "age": age})
print cur.fetchone()
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/execute_2.py | Python | mit | 252 |
from pysqlite2 import dbapi2 as sqlite3
import datetime
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute('select ? as "x [timestamp]"', (datetime.datetime.now(),))
dt = cur.fetchone()[0]
print dt, type(dt)
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/parse_colnames.py | Python | mit | 260 |
from pysqlite2 import dbapi2 as sqlite3
def char_generator():
import string
for c in string.letters[:26]:
yield (c,)
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")
cur.executemany("insert into characters(c) values (?)", char_generator())
cur.execute("select c from characters")
print cur.fetchall()
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/executemany_2.py | Python | mit | 367 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
cur = con.cursor()
newPeople = (
('Lebed' , 53),
('Zhirinovsky' , 57),
)
for person in newPeople:
cur.execute("insert into people (name_last, age) values (?, ?)", person)
# The changes will not be saved unless the transaction is committed explicitly:
con.commit()
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/insert_more_people.py | Python | mit | 359 |
from pysqlite2 import dbapi2 as sqlite3
class Point(object):
def __init__(self, x, y):
self.x, self.y = x, y
def __conform__(self, protocol):
if protocol is sqlite3.PrepareProtocol:
return "%f;%f" % (self.x, self.y)
con = sqlite3.connect(":memory:")
cur = con.cursor()
p = Point(4.0, -3.2)
cur.execute("select ?", (p,))
print cur.fetchone()[0]
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/adapter_point_1.py | Python | mit | 384 |
from pysqlite2 import dbapi2 as sqlite3
class Point(object):
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return "(%f;%f)" % (self.x, self.y)
def adapt_point(point):
return "%f;%f" % (point.x, point.y)
def convert_point(s):
x, y = map(float, s.split(";"))
return Point(x, y)
# Register the adapter
sqlite3.register_adapter(Point, adapt_point)
# Register the converter
sqlite3.register_converter("point", convert_point)
p = Point(4.0, -3.2)
#########################
# 1) Using declared types
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute("create table test(p point)")
cur.execute("insert into test(p) values (?)", (p,))
cur.execute("select p from test")
print "with declared types:", cur.fetchone()[0]
cur.close()
con.close()
#######################
# 1) Using column names
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("create table test(p)")
cur.execute("insert into test(p) values (?)", (p,))
cur.execute('select p as "p [point]" from test')
print "with column names:", cur.fetchone()[0]
cur.close()
con.close()
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/converter_point.py | Python | mit | 1,198 |
from pysqlite2 import dbapi2 as sqlite3
class IterChars:
def __init__(self):
self.count = ord('a')
def __iter__(self):
return self
def next(self):
if self.count > ord('z'):
raise StopIteration
self.count += 1
return (chr(self.count - 1),) # this is a 1-tuple
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")
theIter = IterChars()
cur.executemany("insert into characters(c) values (?)", theIter)
cur.execute("select c from characters")
print cur.fetchall()
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/executemany_1.py | Python | mit | 572 |
from pysqlite2 import dbapi2 as sqlite3
import apsw
apsw_con = apsw.Connection(":memory:")
apsw_con.createscalarfunction("times_two", lambda x: 2*x, 1)
# Create pysqlite connection from APSW connection
con = sqlite3.connect(apsw_con)
result = con.execute("select times_two(15)").fetchone()[0]
assert result == 30
con.close()
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/apsw_example.py | Python | mit | 328 |
from pysqlite2 import dbapi2 as sqlite3
import datetime, time
def adapt_datetime(ts):
return time.mktime(ts.timetuple())
sqlite3.register_adapter(datetime.datetime, adapt_datetime)
con = sqlite3.connect(":memory:")
cur = con.cursor()
now = datetime.datetime.now()
cur.execute("select ?", (now,))
print cur.fetchone()[0]
| 0o2batodd-tntlovspenny | doc/includes/sqlite3/adapter_datetime.py | Python | mit | 328 |
@import url(docutils.css);
@import url(silvercity.css);
div.code-block{
margin-left: 2em ;
margin-right: 2em ;
background-color: #eeeeee;
font-family: "Courier New", Courier, monospace;
font-size: 10pt;
}
| 0o2batodd-tntlovspenny | doc/default.css | CSS | mit | 206 |
# Author: Paul Kippes <kippesp@gmail.com>
import unittest
from pysqlite2 import dbapi2 as sqlite
class DumpTests(unittest.TestCase):
def setUp(self):
self.cx = sqlite.connect(":memory:")
self.cu = self.cx.cursor()
def tearDown(self):
self.cx.close()
def CheckTableDump(self):
expected_sqls = [
"CREATE TABLE t1(id integer primary key, s1 text, " \
"t1_i1 integer not null, i2 integer, unique (s1), " \
"constraint t1_idx1 unique (i2));"
,
"INSERT INTO \"t1\" VALUES(1,'foo',10,20);"
,
"INSERT INTO \"t1\" VALUES(2,'foo2',30,30);"
,
"CREATE TABLE t2(id integer, t2_i1 integer, " \
"t2_i2 integer, primary key (id)," \
"foreign key(t2_i1) references t1(t1_i1));"
,
"CREATE TRIGGER trigger_1 update of t1_i1 on t1 " \
"begin " \
"update t2 set t2_i1 = new.t1_i1 where t2_i1 = old.t1_i1; " \
"end;"
,
"CREATE VIEW v1 as select * from t1 left join t2 " \
"using (id);"
]
[self.cu.execute(s) for s in expected_sqls]
i = self.cx.iterdump()
actual_sqls = [s for s in i]
expected_sqls = ['BEGIN TRANSACTION;'] + expected_sqls + \
['COMMIT;']
[self.assertEqual(expected_sqls[i], actual_sqls[i])
for i in xrange(len(expected_sqls))]
def suite():
return unittest.TestSuite(unittest.makeSuite(DumpTests, "Check"))
def test():
runner = unittest.TextTestRunner()
runner.run(suite())
if __name__ == "__main__":
test()
| 0o2batodd-tntlovspenny | lib/test/dump.py | Python | mit | 1,753 |
# Mimic the sqlite3 console shell's .dump command
# Author: Paul Kippes <kippesp@gmail.com>
def _iterdump(connection):
"""
Returns an iterator to the dump of the database in an SQL text format.
Used to produce an SQL dump of the database. Useful to save an in-memory
database for later restoration. This function should not be called
directly but instead called from the Connection method, iterdump().
"""
cu = connection.cursor()
yield('BEGIN TRANSACTION;')
# sqlite_master table contains the SQL CREATE statements for the database.
q = """
SELECT name, type, sql
FROM sqlite_master
WHERE sql NOT NULL AND
type == 'table'
"""
schema_res = cu.execute(q)
for table_name, type, sql in schema_res.fetchall():
if table_name == 'sqlite_sequence':
yield('DELETE FROM sqlite_sequence;')
elif table_name == 'sqlite_stat1':
yield('ANALYZE sqlite_master;')
elif table_name.startswith('sqlite_'):
continue
# NOTE: Virtual table support not implemented
#elif sql.startswith('CREATE VIRTUAL TABLE'):
# qtable = table_name.replace("'", "''")
# yield("INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"\
# "VALUES('table','%s','%s',0,'%s');" %
# qtable,
# qtable,
# sql.replace("''"))
else:
yield('%s;' % sql)
# Build the insert statement for each row of the current table
res = cu.execute("PRAGMA table_info('%s')" % table_name)
column_names = [str(table_info[1]) for table_info in res.fetchall()]
q = "SELECT 'INSERT INTO \"%(tbl_name)s\" VALUES("
q += ",".join(["'||quote(" + col + ")||'" for col in column_names])
q += ")' FROM '%(tbl_name)s'"
query_res = cu.execute(q % {'tbl_name': table_name})
for row in query_res:
yield("%s;" % row[0])
# Now when the type is 'index', 'trigger', or 'view'
q = """
SELECT name, type, sql
FROM sqlite_master
WHERE sql NOT NULL AND
type IN ('index', 'trigger', 'view')
"""
schema_res = cu.execute(q)
for name, type, sql in schema_res.fetchall():
yield('%s;' % sql)
yield('COMMIT;')
| 0o2batodd-tntlovspenny | lib/dump.py | Python | mit | 2,350 |
//
// MyTreeNode.m
// MyTreeViewPrototype
//
// Created by Jon Limjap on 4/21/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "MyTreeNode.h"
@implementation MyTreeNode
@synthesize index, value;
@synthesize parent, children;
@synthesize inclusive;
#pragma mark -
#pragma mark Initializers
- (id)initWithValue:(NSString *)_value {
self = [super init];
if (self) {
value = _value;
inclusive = YES;
}
return self;
}
#pragma mark -
#pragma mark Custom Properties
- (NSMutableArray *)children {
if (!children) {
children = [[NSMutableArray alloc] initWithCapacity:1];
}
return children;
}
#pragma mark -
#pragma mark Memory Management
- (void) dealloc {
[children release];
[flattenedTreeCache release];
[super dealloc];
}
#pragma mark -
#pragma mark Methods
- (NSUInteger)descendantCount {
NSUInteger cnt = 0;
for (MyTreeNode *child in self.children) {
if (self.inclusive) {
cnt++;
if (child.children.count > 0) {
cnt += [child descendantCount];
}
}
}
// cnt = cnt+1;
return cnt;
}
- (NSArray *)flattenElements {
return [self flattenElementsWithCacheRefresh:NO];
}
- (NSArray *)flattenElementsWithCacheRefresh:(BOOL)invalidate {
if (!flattenedTreeCache || invalidate) {
//if there was a previous cache and due for invalidate, release resources first
if (flattenedTreeCache) {
[flattenedTreeCache release];
flattenedTreeCache = nil;
}
NSMutableArray *allElements = [[[NSMutableArray alloc] initWithCapacity:[self descendantCount]] autorelease];
[allElements addObject:self];
if (inclusive) {
for (MyTreeNode *child in self.children) {
[allElements addObjectsFromArray:[child flattenElementsWithCacheRefresh:invalidate]];
}
}
flattenedTreeCache = [[NSArray alloc] initWithArray:allElements];
}
return flattenedTreeCache;
}
- (void)addChild:(MyTreeNode *)newChild {
newChild.parent = self;
[self.children addObject:newChild];
}
- (NSUInteger)levelDepth {
if (!parent) return 0;
NSUInteger cnt = 0;
cnt++;
cnt += [parent levelDepth];
return cnt;
}
- (BOOL)isRoot {
return (!parent);
}
- (BOOL)hasChildren {
return (self.children.count > 0);
}
@end
| 009-20120511-zi | trunk/Zinipad/MyTreeNode.m | Objective-C | gpl3 | 2,192 |
//
// SmartSearchView.h
// Zinipad
//
// Created by ZeLkOvA on 12. 5. 23..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface SmartSearchView : UIViewController
@end
| 009-20120511-zi | trunk/Zinipad/SmartSearchView.h | Objective-C | gpl3 | 225 |
//
// SampleBookMainView.m
// Zinipad
//
// Created by ZeLkOvA on 12. 5. 17..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import "SampleBookViewWallpaper.h"
#import "MyTreeViewCell.h"
#import "TreeView.h"
#import "iCarousel.h"
#import "DatabaseManager.h"
//#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
//#define NUMBER_OF_ITEMS 6
#define NUMBER_OF_VISIBLE_ITEMS 5
#define ITEM_SPACING 60.0f
#define INCLUDE_PLACEHOLDERS YES
@interface SampleBookViewWallpaper () <UIActionSheetDelegate>
@property (nonatomic, assign) BOOL wrap;
@property (nonatomic, retain) NSMutableArray *items;
@end
@implementation SampleBookViewWallpaper
@synthesize carousel;
@synthesize wrap;
@synthesize items;
@synthesize bottomListScroll;
@synthesize ColorImgArray;
@synthesize detailImageView;
@synthesize carouselColor;
@synthesize patternView;
@synthesize selectedImgList;
@synthesize detailDescriptionBg;
@synthesize selectedImgOrigin;
@synthesize WideButton;
@synthesize MatchingButton;
@synthesize PatternButton;
- (void)setUpImg
{
//set up data
wrap = YES;
// self.items = [NSMutableArray array];
//
// // 이미지 가져와서 저장하기
// [items addObject:@"x.png"];
// [items addObject:@"y.png"];
// [items addObject:@"z.png"];
// [items addObject:@"x.png"];
// [items addObject:@"y.png"];
// [items addObject:@"z.png"];
// [items addObject:@"x.png"];
// [items addObject:@"y.png"];
// [items addObject:@"z.png"];
// [items addObject:@"x.png"];
// [items addObject:@"y.png"];
// [items addObject:@"z.png"];
}
-(void)SettingColorImg
{
self.ColorImgArray = [NSMutableArray array];
[ColorImgArray addObject:@"color_19.png"];
[ColorImgArray addObject:@"color_09.png"];
[ColorImgArray addObject:@"color_11.png"];
[ColorImgArray addObject:@"color_06.png"];
[ColorImgArray addObject:@"color_02.png"];
[ColorImgArray addObject:@"color_17.png"];
[ColorImgArray addObject:@"color_13.png"];
[ColorImgArray addObject:@"color_04.png"];
[ColorImgArray addObject:@"color_09.png"];
[ColorImgArray addObject:@"color_10.png"];
[ColorImgArray addObject:@"color_15.png"];
[ColorImgArray addObject:@"color_05.png"];
[ColorImgArray addObject:@"color_12.png"];
[ColorImgArray addObject:@"color_14.png"];
[ColorImgArray addObject:@"color_08.png"];
[ColorImgArray addObject:@"color_07.png"];
[ColorImgArray addObject:@"color_01.png"];
// [ColorImgArray addObject:@"color_18.png"];
// [ColorImgArray addObject:@"color_01.png"];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
bFirstLoad = YES;
[self SettingColorImg];
[self setUpImg];
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/
-(void)categoryIndexReceive:(int)_nCount
{
nCategoryIndex = _nCount;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
firstLoad = false;
bWide = false;
UIImage* BGSampleBookImage = [UIImage imageNamed:@"bg_samplebook"];
UIImageView* BGSampleBookImageView = [[UIImageView alloc] initWithImage:BGSampleBookImage];
[BGSampleBookImageView setFrame:CGRectMake(0, 0, BGSampleBookImage.size.width, BGSampleBookImage.size.height)];
[self.view addSubview:BGSampleBookImageView];
[self InitColorCarousel];
[self InitCarousel];
// bottomListScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 550, self.view.frame.size.width, 130)];
// [bottomListScroll setBackgroundColor:[UIColor blackColor]];
//
// [self.view addSubview:bottomListScroll];
///////////////////
// 관련 바닥재 이미지 불러와야함
//////////////////
UIImage* tileBGImage = [UIImage imageNamed:[self.items objectAtIndex:0]];
detailImageView = [[UIImageView alloc] initWithImage:tileBGImage];
[detailImageView setFrame:CGRectMake(97, 7, 515, 636)];
detailDescriptionBg = [[UIImageView alloc] init];
[detailDescriptionBg setBackgroundColor:[UIColor blackColor]];
[detailDescriptionBg setFrame:CGRectMake(0, 636-50, 515, 50)];
[detailDescriptionBg setAlpha:0.0f];
[detailImageView addSubview:detailDescriptionBg];
[self.view addSubview:detailImageView];
WideButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[WideButton setFrame:CGRectMake(250,642-45, 40, 40)];
[WideButton setTitle:[NSString stringWithFormat:@""] forState:UIControlStateNormal];
[WideButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[WideButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
// [WideButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[WideButton addTarget:self action:@selector(WideButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:WideButton];
MatchingButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[MatchingButton setFrame:CGRectMake(450,642-45, 40, 40)];
[MatchingButton setTitle:[NSString stringWithFormat:@"매칭"] forState:UIControlStateNormal];
[MatchingButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[MatchingButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
// [MatchingButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[MatchingButton addTarget:self action:@selector(MatchingButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:MatchingButton];
PatternButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[PatternButton setFrame:CGRectMake(510, 642-45, 40, 40)];
[PatternButton setTitle:[NSString stringWithFormat:@"패턴"] forState:UIControlStateNormal];
[PatternButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[PatternButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
// [PatternButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[PatternButton addTarget:self action:@selector(PatternButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:PatternButton];
//
// for (int i =0; i<[items count]; i++)
// {
//
// UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
// [button addTarget:self action:@selector(imageTouch:withEvent:) forControlEvents:UIControlEventTouchDown];
// [button addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragInside];
// [button addTarget:self action:@selector(imageTouchUp:withEvent:) forControlEvents:UIControlEventTouchUpInside];
// [button setImage:[UIImage imageNamed:[items objectAtIndex:i]] forState:UIControlStateNormal];
// [button setFrame:CGRectMake(10+i*240, 10, 200, 100)];
// [button setTag:i];
// [bottomListScroll setContentSize:CGSizeMake(250*[items count],130)];
// [bottomListScroll addSubview:button];
// }
}
-(void)WideButtonPressed:(id)sender
{
if(bWide == false)
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[detailDescriptionBg setFrame:CGRectMake(0, 636-200, 515, 200)];
[WideButton setFrame:CGRectMake(250,642-200, 40, 40)];
// [MatchingButton setFrame:CGRectMake(450,642-200, 40, 40)];
// [PatternButton setFrame:CGRectMake(510, 642-200, 40, 40)];
[UIView commitAnimations];
bWide = true;
}
else
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[detailDescriptionBg setFrame:CGRectMake(0, 636-50, 515, 50)];
[WideButton setFrame:CGRectMake(250,642-45, 40, 40)];
// [MatchingButton setFrame:CGRectMake(450,642-45, 40, 40)];
// [PatternButton setFrame:CGRectMake(510, 642-45, 40, 40)];
[UIView commitAnimations];
bWide = false;
}
}
- (void) imageMoved:(id) sender withEvent:(UIEvent *) event
{
CGPoint point = [[[event allTouches] anyObject] locationInView:self.view];
UIControl *control = sender;
control.center = point;
}
- (void) imageTouch:(id) sender withEvent:(UIEvent *) event
{
// CGPoint point = [[[event allTouches] anyObject] locationInView:bottomListScroll];
CGPoint point2 = [[[event allTouches] anyObject] locationInView:self.view];
UIControl *control = sender;
control.center = point2;
[self.view addSubview:control];
}
- (void) imageTouchUp:(id) sender withEvent:(UIEvent *) event
{
CGPoint point = [[[event allTouches] anyObject] locationInView:self.view];
UIControl *control = sender;
control.center = point;
int aa = [sender tag];
// [self.view addSubview:control];
NSLog(@"%f",point.x);
NSLog(@"%f",point.y);
if(point.x > 20 && point.x < 600)
{
if(point.y > 300 && point.y < 500)
{
[self.view addSubview:control];
[control removeFromSuperview ];
NSLog(@"Come Inside");
// [control setFrame:CGRectMake(10+240*aa,10,200,100)];
// [bottomListScroll addSubview:control];
////////////////////
// 바닥재 이미지 들어가기
////////////////////
// return;
}
}
[control setFrame:CGRectMake(10+240*aa,10,200,100)];
[bottomListScroll addSubview:control];
}
-(void)InitCarousel
{
carousel = [[iCarousel alloc] init];
[carousel setFrame:CGRectMake(590,170,150,300)];
[self.view addSubview:carousel];
carousel.delegate = self;
carousel.dataSource = self;
//configure carousel
carousel.type = iCarouselTypeInvertedWheel;
// navItem.title = @"CoverFlow2";
carousel.vertical = !carousel.vertical;
}
-(void)InitColorCarousel
{
// carouselColor
carouselColor = [[iCarouselColor alloc] init];
[carouselColor setFrame:CGRectMake(-20,170,150,300)];
carouselColor.dataSourceColor = self;
carouselColor.delegate = self;
[self.view addSubview:carouselColor];
// carouselColor.delegate = self;
// carouselColor.dataSourceColor = self;
carouselColor.type = iCarouselColorTypeWheel;
carouselColor.vertical = !carouselColor.vertical;
// ColorView = [[SampleBookColorViewWallpaper alloc] init];
// [ColorView.view setFrame:CGRectMake(40,100,150,300)];
// [self.view addSubview:ColorView.view];
}
-(void)MatchingButtonPressed:(id)sender
{
}
-(void)PatternButtonPressed:(id)sender
{
[self PatternView:@"파일명"];
}
- (void)carouselCurrnetImgIndex:(int)_imgIndex;
{
NSLog(@"ImgIndex == %d",_imgIndex);
UIImage* tileBGImage = [UIImage imageNamed:[selectedImgOrigin objectAtIndex:_imgIndex]];
[detailImageView setImage:tileBGImage];
[detailImageView setAlpha:1.0f];
[detailDescriptionBg setAlpha:0.6f];
}
- (void)carouselCurrnetImgIndexColor:(int)_imgIndex;
{
if(firstLoad == false)
{
firstLoad = true;
return;
}
NSLog(@"ImgIndexColor %% == %d",_imgIndex);
if(nCategoryIndex == 0)
{
}
selectedImgList = [[NSMutableArray alloc] init];
selectedImgList = [DatabaseManager selectedColorList:_imgIndex category:nCategoryIndex];
if([selectedImgList count] == 0)
{
[carousel removeFromSuperview];
[detailImageView setAlpha:0.0f];
[detailDescriptionBg setAlpha:0.0f];
// if(carousel)
// {
// [carousel removeFromSuperview];
// [carousel release];
// }
return;
}
self.items = [NSMutableArray array];
selectedImgOrigin = [[NSMutableArray alloc] init];
for (int i = 0; i<[selectedImgList count]; i++)
{
NSMutableDictionary* dic = [NSMutableDictionary dictionary];
dic = [selectedImgList objectAtIndex:i];
NSString* thumbImg = [dic objectForKey:@"W_img_thumb"];
[self.items addObject:thumbImg];
NSString* originImg = [dic objectForKey:@"W_img_original"];
[selectedImgOrigin addObject:originImg];
}
if(carousel)
{
[carousel removeFromSuperview];
[carousel release];
}
[self InitCarousel];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
return [items count];
}
- (NSUInteger)numberOfVisibleItemsInCarousel:(iCarousel *)carousel
{
//limit the number of items views loaded concurrently (for performance reasons)
//this also affects the appearance of circular-type carousels
return NUMBER_OF_VISIBLE_ITEMS;
}
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
if (view == nil)
{
// NSLog(@"here %d",index);
view = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:[items objectAtIndex:index]]] autorelease];
[view setFrame:CGRectMake(0, 0, 70, 70)];
view.layer.doubleSided = YES; //prevent back side of view from showing
// label = [[[UILabel alloc] initWithFrame:view.bounds] autorelease];
// label.backgroundColor = [UIColor clearColor];
// label.textAlignment = UITextAlignmentCenter;
// label.font = [label.font fontWithSize:10];
// label.text = [NSString stringWithFormat:@"%d",count];
// [view addSubview:label];
// count++;
}
else
{
// NSLog(@"here %d",index);
view = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:[items objectAtIndex:index]]] autorelease];
[view setFrame:CGRectMake(0, 0, 70, 70)];
view.layer.doubleSided = YES;
}
//
return view;
}
- (NSUInteger)numberOfPlaceholdersInCarousel:(iCarousel *)carousel
{
//note: placeholder views are only displayed on some carousels if wrapping is disabled
return 0;
}
- (CGFloat)carouselItemWidth:(iCarousel *)carousel
{
//usually this should be slightly wider than the item views
return ITEM_SPACING;
}
- (BOOL)carouselShouldWrap:(iCarousel *)carousel
{
return wrap;
}
// 패던보기
-(void)PatternView:(NSString*)_imgFile
{
patternView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
[patternView setBackgroundColor:[UIColor whiteColor]];
UIButton* PatternBackButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[PatternBackButton setFrame:CGRectMake(1024 - 70, 30, 70, 70)];
[PatternBackButton setTitle:[NSString stringWithFormat:@"X"] forState:UIControlStateNormal];
[PatternBackButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[PatternBackButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[PatternBackButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[PatternBackButton addTarget:self action:@selector(PatternBackButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[patternView addSubview:PatternBackButton];
[self.view.superview addSubview:patternView];
}
-(void)PatternBackButtonPressed:(id)sender
{
[patternView removeFromSuperview];
[patternView release];
}
-(void)dealloc
{
carousel.delegate = nil;
carousel.dataSource = nil;
[carousel release];
[items release];
[super dealloc];
}
#pragma mark - Button Handler
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (NSUInteger)numberOfItemsInCarouselColor:(iCarouselColor *)carousel
{
return [ColorImgArray count];
}
- (NSUInteger)numberOfVisibleItemsInCarouselColor:(iCarouselColor *)carousel
{
//limit the number of items views loaded concurrently (for performance reasons)
//this also affects the appearance of circular-type carousels
return NUMBER_OF_VISIBLE_ITEMS;
}
- (UIView *)carouselColor:(iCarouselColor *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
if (view == nil)
{
// NSLog(@"here %d",index);
view = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:[ColorImgArray objectAtIndex:index]]] autorelease];
[view setFrame:CGRectMake(0, 0, 70, 70)];
view.layer.doubleSided = YES; //prevent back side of view from showing
// label = [[[UILabel alloc] initWithFrame:view.bounds] autorelease];
// label.backgroundColor = [UIColor clearColor];
// label.textAlignment = UITextAlignmentCenter;
// label.font = [label.font fontWithSize:10];
// label.text = [NSString stringWithFormat:@"%d",count];
// [view addSubview:label];
// count++;
}
else
{
// NSLog(@"here %d",index);
view = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:[ColorImgArray objectAtIndex:index]]] autorelease];
[view setFrame:CGRectMake(0, 0, 70, 70)];
view.layer.doubleSided = YES;
}
//
return view;
}
- (NSUInteger)numberOfPlaceholdersInCarouselColor:(iCarouselColor *)carousel
{
//note: placeholder views are only displayed on some carousels if wrapping is disabled
return 0;
}
- (CGFloat)carouselItemWidthColor:(iCarouselColor *)carousel
{
//usually this should be slightly wider than the item views
return ITEM_SPACING;
}
- (BOOL)carouselShouldWrapColor:(iCarouselColor *)carousel
{
return wrap;
}
@end
| 009-20120511-zi | trunk/Zinipad/SampleBookViewWallpaper.m | Objective-C | gpl3 | 18,310 |
//
// SampleBookMainView.h
// Zinipad
//
// Created by ZeLkOvA on 12. 5. 17..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "iCarousel.h"
#import "iCarouselColor.h"
@interface SampleBookViewWallpaper : UIViewController<iCarouselDataSource, iCarouselDelegate,iCarouselColorDataSource,iCarouselColorDelegate>
{
iCarousel* carousel;
iCarouselColor* carouselColor;
// iCarouselColor* carouselColor;
// UIView* RightCarousel;
UIScrollView* bottomListScroll;
int nCategoryIndex;
NSMutableArray* ColorImgArray;
UIImageView* detailImageView;
NSMutableArray* selectedImgList;
NSMutableArray* selectedImgOrigin;
UIView* patternView;
BOOL bFirstLoad;
BOOL firstLoad;
UIImageView* detailDescriptionBg;
UIButton* WideButton;
UIButton* MatchingButton;
UIButton* PatternButton;
BOOL bWide;
}
@property (nonatomic, retain) iCarousel *carousel;
@property (nonatomic, retain) iCarouselColor* carouselColor;
@property (nonatomic, retain) UIScrollView* bottomListScroll;
@property (nonatomic, retain) NSMutableArray* ColorImgArray;
@property (nonatomic, retain) UIImageView* detailImageView;
@property (nonatomic, retain) NSMutableArray* selectedImgList;
@property (nonatomic, retain) UIImageView* detailDescriptionBg;
@property (nonatomic, retain) NSMutableArray* selectedImgOrigin;
@property (nonatomic, retain) UIView* patternView;
@property (nonatomic, retain) UIButton* WideButton;
@property (nonatomic, retain) UIButton* MatchingButton;
@property (nonatomic, retain) UIButton* PatternButton;
-(void)setUpImg;
-(void)InitCarousel;
-(void)categoryIndexReceive:(int)_nCount;
@end
| 009-20120511-zi | trunk/Zinipad/SampleBookViewWallpaper.h | Objective-C | gpl3 | 1,716 |
//
// Copyright 2011 Kakao Corp. All rights reserved.
// @author kakaolink@kakao.com
// @version 2.0
//
#ifndef __IPHONE_3_0
#error "This class uses features only available in iPhone SDK 3.0 and later."
#endif
#import <UIKit/UIKit.h>
/**
*
*/
@interface KakaoLinkCenter : NSObject {
@private
}
/**
* Returns the default singleton instance.
*/
+ (KakaoLinkCenter *)defaultCenter;
/**
* Returns whether the application can open kakaolink URLs.
*/
- (BOOL)canOpenKakaoLink;
/**
* Gets a kakaolink URL for parameters.
*/
- (NSString *)kakaoLinkURLStringForParameters:(NSDictionary *)parameters;
/**
* Opens kakaolink with parameters.
*/
- (BOOL)openKakaoLinkWithURL:(NSString *)referenceURLString
appVersion:(NSString *)appVersion
appBundleID:(NSString *)appBundleID
appName:(NSString *)appName
message:(NSString *)message;
/**
* Opens kakaoApplink with parameters.
*/
- (BOOL)openKakaoAppLinkWithMessage:(NSString *)message
URL:(NSString *)referenceURLString
appBundleID:(NSString *)appBundleID
appVersion:(NSString *)appVersion
appName:(NSString *)appName
metaInfoArray:(NSArray *)metaInfoArray;
@end
| 009-20120511-zi | trunk/Zinipad/KakaoLinkCenter.h | Objective-C | gpl3 | 1,237 |
/*
File: Reachability.h
Abstract: Basic demonstration of how to use the SystemConfiguration Reachablity APIs.
Version: 2.2
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple Software"), to
use, reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions
of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may be used
to endorse or promote products derived from the Apple Software without specific
prior written permission from Apple. Except as expressly stated in this notice,
no other rights or licenses, express or implied, are granted by Apple herein,
including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be
incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2010 Apple Inc. All Rights Reserved.
*/
#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
typedef enum {
NotReachable = 0,
ReachableViaWiFi,
ReachableViaWWAN
} NetworkStatus;
#define kReachabilityChangedNotification @"kNetworkReachabilityChangedNotification"
@interface Reachability: NSObject
{
BOOL localWiFiRef;
SCNetworkReachabilityRef reachabilityRef;
}
//reachabilityWithHostName- Use to check the reachability of a particular host name.
+ (Reachability*) reachabilityWithHostName: (NSString*) hostName;
//reachabilityWithAddress- Use to check the reachability of a particular IP address.
+ (Reachability*) reachabilityWithAddress: (const struct sockaddr_in*) hostAddress;
//reachabilityForInternetConnection- checks whether the default route is available.
// Should be used by applications that do not connect to a particular host
+ (Reachability*) reachabilityForInternetConnection;
//reachabilityForLocalWiFi- checks whether a local wifi connection is available.
+ (Reachability*) reachabilityForLocalWiFi;
//Start listening for reachability notifications on the current run loop
- (BOOL) startNotifier;
- (void) stopNotifier;
- (NetworkStatus) currentReachabilityStatus;
//WWAN may be available, but not active until a connection has been established.
//WiFi may require a connection for VPN on Demand.
- (BOOL) connectionRequired;
@end
| 009-20120511-zi | trunk/Zinipad/Reachability.h | Objective-C | gpl3 | 3,867 |
//
// RootViewController.h
// MyTreeViewPrototype
//
// Created by Jon Limjap on 4/21/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "MyTreeNode.h"
@protocol TreeViewSelectDelegate
@required
-(void)TreeViewSelect:(NSInteger)selectedIndex haschilden:(BOOL)lastElement;
@end
@interface TreeView : UITableViewController {
id<TreeViewSelectDelegate> Trdelegate;
MyTreeNode *treeNode;
}
@property (nonatomic, retain) id<TreeViewSelectDelegate> Trdelegate;
@property (nonatomic, retain) MyTreeNode *treeNode;
@end
| 009-20120511-zi | trunk/Zinipad/TreeView.h | Objective-C | gpl3 | 573 |
//
// DatabaseManager.h
// DockToy
//
// Created by realmingz on 11. 3. 16..
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <sqlite3.h>
@interface DatabaseManager : NSObject
{
}
+ (void) connectDatabse;
+ (void) closeDatabse;
+ (NSMutableArray *) customerList;
+ (NSMutableArray *) selectedColorList:(NSInteger)colorCode category:(NSInteger)categoryCode;
+(NSArray *) spliteString:(NSString*)_words;
+(NSString*) searchColorName:(NSInteger)code;
@end
| 009-20120511-zi | trunk/Zinipad/DatabaseManager.h | Objective-C | gpl3 | 522 |
//
// MbochureMainView.m
// Zinipad
//
// Created by ZeLkOvA on 12. 5. 24..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import "MbochureMainView.h"
@interface MbochureMainView ()
@end
@implementation MbochureMainView
@synthesize myPDFView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect frame = CGRectMake(0, 0, 1024, 768);
myPDFView = [[viewPDF alloc] initWithFrame:frame FileName:@"ZIN_TABLETAPP_V0.1_20120517"];
[self.view addSubview:myPDFView];
UIButton* CloseButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[CloseButton setFrame:CGRectMake(1024-50,10, 40, 40)];
[CloseButton setTitle:[NSString stringWithFormat:@"매칭"] forState:UIControlStateNormal];
[CloseButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[CloseButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[CloseButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[CloseButton addTarget:self action:@selector(CloseButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:CloseButton];
}
-(void)CloseButtonPressed:(id)sender
{
[self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
| 009-20120511-zi | trunk/Zinipad/MbochureMainView.m | Objective-C | gpl3 | 1,757 |
//
// MyTreeNode.h
// MyTreeViewPrototype
//
// Created by Jon Limjap on 4/21/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "MyTreeNode.h"
@interface MyTreeNode : NSObject {
int index;
NSString *value;
MyTreeNode *parent;
NSMutableArray *children;
BOOL inclusive;
NSArray *flattenedTreeCache;
}
@property (nonatomic) int index;
@property (nonatomic, retain) NSString *value;
@property (nonatomic, retain) MyTreeNode *parent;
@property (nonatomic, retain, readonly) NSMutableArray *children;
@property (nonatomic) BOOL inclusive;
- (id)initWithValue:(NSString *)_value;
- (void)addChild:(MyTreeNode *)newChild;
- (NSUInteger)descendantCount;
- (NSUInteger)levelDepth;
- (NSArray *)flattenElements;
- (NSArray *)flattenElementsWithCacheRefresh:(BOOL)invalidate;
- (BOOL)isRoot;
- (BOOL)hasChildren;
@end
| 009-20120511-zi | trunk/Zinipad/MyTreeNode.h | Objective-C | gpl3 | 879 |
/*
File: Reachability.m
Abstract: Basic demonstration of how to use the SystemConfiguration Reachablity APIs.
Version: 2.2
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple Software"), to
use, reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions
of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may be used
to endorse or promote products derived from the Apple Software without specific
prior written permission from Apple. Except as expressly stated in this notice,
no other rights or licenses, express or implied, are granted by Apple herein,
including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be
incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2010 Apple Inc. All Rights Reserved.
*/
#import <sys/socket.h>
#import <netinet/in.h>
#import <netinet6/in6.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <netdb.h>
#import <CoreFoundation/CoreFoundation.h>
#import "Reachability.h"
#define kShouldPrintReachabilityFlags 1
static void PrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* comment)
{
#if kShouldPrintReachabilityFlags
NSLog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n",
(flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-',
(flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-',
(flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-',
(flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-',
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-',
(flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-',
(flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-',
(flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-',
(flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-',
comment
);
#endif
}
@implementation Reachability
static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info)
{
#pragma unused (target, flags)
NSCAssert(info != NULL, @"info was NULL in ReachabilityCallback");
NSCAssert([(NSObject*) info isKindOfClass: [Reachability class]], @"info was wrong class in ReachabilityCallback");
//We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively
// in case someon uses the Reachablity object in a different thread.
NSAutoreleasePool* myPool = [[NSAutoreleasePool alloc] init];
Reachability* noteObject = (Reachability*) info;
// Post a notification to notify the client that the network reachability changed.
[[NSNotificationCenter defaultCenter] postNotificationName: kReachabilityChangedNotification object: noteObject];
[myPool release];
}
- (BOOL) startNotifier
{
BOOL retVal = NO;
SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
if(SCNetworkReachabilitySetCallback(reachabilityRef, ReachabilityCallback, &context))
{
if(SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode))
{
retVal = YES;
}
}
return retVal;
}
- (void) stopNotifier
{
if(reachabilityRef!= NULL)
{
SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
}
}
- (void) dealloc
{
[self stopNotifier];
if(reachabilityRef!= NULL)
{
CFRelease(reachabilityRef);
}
[super dealloc];
}
+ (Reachability*) reachabilityWithHostName: (NSString*) hostName;
{
Reachability* retVal = NULL;
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]);
if(reachability!= NULL)
{
retVal= [[[self alloc] init] autorelease];
if(retVal!= NULL)
{
retVal->reachabilityRef = reachability;
retVal->localWiFiRef = NO;
}
}
return retVal;
}
+ (Reachability*) reachabilityWithAddress: (const struct sockaddr_in*) hostAddress;
{
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)hostAddress);
Reachability* retVal = NULL;
if(reachability!= NULL)
{
retVal= [[[self alloc] init] autorelease];
if(retVal!= NULL)
{
retVal->reachabilityRef = reachability;
retVal->localWiFiRef = NO;
}
}
return retVal;
}
+ (Reachability*) reachabilityForInternetConnection;
{
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
return [self reachabilityWithAddress: &zeroAddress];
}
+ (Reachability*) reachabilityForLocalWiFi;
{
struct sockaddr_in localWifiAddress;
bzero(&localWifiAddress, sizeof(localWifiAddress));
localWifiAddress.sin_len = sizeof(localWifiAddress);
localWifiAddress.sin_family = AF_INET;
// IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0
localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM);
Reachability* retVal = [self reachabilityWithAddress: &localWifiAddress];
if(retVal!= NULL)
{
retVal->localWiFiRef = YES;
}
return retVal;
}
#pragma mark Network Flag Handling
- (NetworkStatus) localWiFiStatusForFlags: (SCNetworkReachabilityFlags) flags
{
PrintReachabilityFlags(flags, "localWiFiStatusForFlags");
BOOL retVal = NotReachable;
if((flags & kSCNetworkReachabilityFlagsReachable) && (flags & kSCNetworkReachabilityFlagsIsDirect))
{
retVal = ReachableViaWiFi;
}
return retVal;
}
- (NetworkStatus) networkStatusForFlags: (SCNetworkReachabilityFlags) flags
{
PrintReachabilityFlags(flags, "networkStatusForFlags");
if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
{
// if target host is not reachable
return NotReachable;
}
BOOL retVal = NotReachable;
if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
{
// if target host is reachable and no connection is required
// then we'll assume (for now) that your on Wi-Fi
retVal = ReachableViaWiFi;
}
if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
{
// ... and the connection is on-demand (or on-traffic) if the
// calling application is using the CFSocketStream or higher APIs
if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
{
// ... and no [user] intervention is needed
retVal = ReachableViaWiFi;
}
}
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
{
// ... but WWAN connections are OK if the calling application
// is using the CFNetwork (CFSocketStream?) APIs.
retVal = ReachableViaWWAN;
}
return retVal;
}
- (BOOL) connectionRequired;
{
NSAssert(reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef");
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
{
return (flags & kSCNetworkReachabilityFlagsConnectionRequired);
}
return NO;
}
- (NetworkStatus) currentReachabilityStatus
{
NSAssert(reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef");
NetworkStatus retVal = NotReachable;
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
{
if(localWiFiRef)
{
retVal = [self localWiFiStatusForFlags: flags];
}
else
{
retVal = [self networkStatusForFlags: flags];
}
}
return retVal;
}
@end
| 009-20120511-zi | trunk/Zinipad/Reachability.m | Objective-C | gpl3 | 9,115 |
//
// viewPDF.h
// customPDFViewer
//
// Created by Andrew Cefalo on 3/22/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface viewPDF : UIView {
CGPDFDocumentRef document;
int currentPage;
}
-(void)increasePageNumber;
-(void)decreasePageNumber;
- (id)initWithFrame:(CGRect)frame FileName:(NSString*)name;
@end
| 009-20120511-zi | trunk/Zinipad/viewPDF.h | Objective-C | gpl3 | 374 |
//
// RootViewController.m
// ViewAnimationTest
//
// Created by 성주 이 on 5/17/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "ZinMainViewController.h"
#import "MyTreeViewCell.h"
#import "TreeView.h"
#import "SmartSearchView.h"
#import "SampleBookViewWallpaper.h"
#import "SampleBookViewFlooring.h"
#import "SmartCounselMainView.h"
#import "DatabaseManager.h"
#import "Util.h"
#import "MbochureMainView.h"
#import "MatchingViewController.h"
//@interface ZinMainViewController ()
//
//@end
@implementation ZinMainViewController
@synthesize _leftMenuBar;
@synthesize _mainStage;
@synthesize _rightMenuBar;
@synthesize CurrentView;
@synthesize secDepthView;
@synthesize leftMenuScroll;
@synthesize rightMenuScroll;
@synthesize leftMenuButtonList;
@synthesize rightMenuButtonList;
@synthesize rootButtonImg;
@synthesize subButtonLastImg;
@synthesize rootButtonPressedImg;
@synthesize secDepthViewWallpaper;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
#define SIZE_WIDE 204.0f
#define SIZE_NARROW 50.0f
#define SIZE_TOPBAR 60.0f
#define SAMPLE_LIST_HIGHT 61.0f
#define LEFT_SAMPLEBOOKLIST_TAG 100
#define RIGHT_SAMPLEBOOKLIST_TAG 200
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
_isExpanded = NO;
[self.view setFrame:CGRectMake(0, 0, 1024, 768)];
// [self.view setBackgroundColor:[UIColor blackColor]];
UIImage* BGImage = [UIImage imageNamed:@"bg_main"];
UIImageView* bgMain = [[UIImageView alloc] initWithImage:BGImage];
UIImageView* BackgroundImg = [Util cropImage: @"bg_main" targetX:0 targetY:0 targetWidth:SIZE_WIDE targetHeight:718 resultX:0 resultY:0 resultWidth:SIZE_WIDE resultHeight:718];
[self.view addSubview:bgMain];
// 왼쪽 메뉴
self._leftMenuBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SIZE_WIDE, 718)];
// [BackgroundImg setFrame:CGRectMake(0, 0, SIZE_WIDE, 718)];
[self._leftMenuBar addSubview:BackgroundImg];
[self.view addSubview:self._leftMenuBar];
UIImageView* BackgroundImgRight = [Util cropImage: @"bg_main" targetX:1024-SIZE_WIDE targetY:0 targetWidth:SIZE_WIDE targetHeight:718 resultX:0 resultY:0 resultWidth:SIZE_WIDE resultHeight:718];
// 오른쪽 메뉴
self._rightMenuBar = [[UIView alloc] initWithFrame:CGRectMake(1024-SIZE_WIDE, 0, SIZE_WIDE, 718)];
[self._rightMenuBar addSubview:BackgroundImgRight];
[self.view addSubview:self._rightMenuBar];
UIImageView* BackgroundImgCenter = [Util cropImage: @"bg_main" targetX:SIZE_WIDE targetY:0 targetWidth:1024-SIZE_WIDE-SIZE_WIDE targetHeight:718 resultX:0 resultY:0 resultWidth:1024-SIZE_WIDE-SIZE_WIDE resultHeight:718];
// 가운데 메인스테이지
self._mainStage = [[UIView alloc] initWithFrame:CGRectMake(SIZE_WIDE, 0,1024-SIZE_WIDE-SIZE_WIDE, 718)];
// [self._mainStage setBackgroundColor:[UIColor yellowColor]];
[self._mainStage addSubview:BackgroundImgCenter];
[self.view addSubview:self._mainStage];
CurrentView = _mainStage;
CurrentViewIndex = 0;
[self mainStageView];
// tv = [[TreeView alloc] init];
// tv.trdelegate = self;
// [tv.view setFrame:CGRectMake(10*2, 110, 188-18, 615-99)];
//
// [_rightMenuBar addSubview:tv.view];
sampleBookView = [[SampleBookViewWallpaper alloc] init];
sampleBookViewFlooring = [[SampleBookViewFlooring alloc] init];
rootButtonImg = [UIImage imageNamed:@"bg_lnb_m"];
subButtonLastImg = [UIImage imageNamed:@"bg_lnb_b"];
rootButtonPressedImg = [UIImage imageNamed:@"btn_rollOver"];
// 왼쪽 메뉴 항목
[self leftMenuView];
[self rightMenuView];
[self bottomMenuView];
}
-(void)leftMenuView
{
UIImage* leftMenuTitleImage = [UIImage imageNamed:@"tit_lnb"];
UIImageView* leftMenuTitleImageView = [[UIImageView alloc] initWithImage:leftMenuTitleImage];
[leftMenuTitleImageView setFrame:CGRectMake(11, 11, 188, 99)];
[self._leftMenuBar addSubview:leftMenuTitleImageView];
UIImageView* bgLeftMenuScroll = [Util tileImage:@"bg_lnb_m" resultX:0 resultY:0 resultWidth:188 resultHeight:530];
leftMenuScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(11, 110, 188, 530)];
[leftMenuScroll setContentSize:CGSizeMake(188, 50*10 + SAMPLE_LIST_HIGHT)];
[leftMenuScroll addSubview:bgLeftMenuScroll];
[self._leftMenuBar addSubview:leftMenuScroll];
[self MakeLeftMenuButton];
// UIImageView* blankList = [[UIImageView alloc] initWithImage:rootButtonImg];
// [blankList setFrame:CGRectMake(0, i*50, 188, 51)];
// [leftMenuScroll addSubview:blankList];
// UIImage* SampleBookButtonImg = [UIImage imageNamed:@"bg_lnb_b"];
// UIButton* SampleBookListbutton = [[UIButton alloc] initWithFrame:CGRectMake(0, 540, 188, 61)];
// [SampleBookListbutton setBackgroundImage:SampleBookButtonImg forState:UIControlStateNormal];
// [SampleBookListbutton setTag:LEFT_SAMPLEBOOKLIST_TAG];
// [SampleBookListbutton addTarget:self action:@selector(SampleBookListbuttonPressed:) forControlEvents:UIControlEventTouchUpInside];
// [SampleBookListbutton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
// [SampleBookListbutton setTitle: @"샘플북 리스트" forState:UIControlStateNormal];
// [leftMenuScroll addSubview:SampleBookListbutton];
}
-(void)MakeLeftMenuButton
{
NSMutableArray* leftRootList = [[NSMutableArray alloc] init ];
[leftRootList addObject:@"프리미엄벽지"];
[leftRootList addObject:@"실크벽지"];
[leftRootList addObject:@"합지벽지"];
[leftRootList addObject:@"벽타일"];
for (int i = 0; i < [leftRootList count]; i++)
{
UIFont *font;
font = [UIFont boldSystemFontOfSize:16];
UIButton *listRootbutton = [[UIButton alloc] initWithFrame:CGRectMake(0, i*50, 188, 50)];
[listRootbutton setBackgroundImage:rootButtonImg forState:UIControlStateNormal];
[listRootbutton setBackgroundImage:rootButtonPressedImg forState:UIControlStateHighlighted];
[listRootbutton addTarget:self action:@selector(listRootbuttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[listRootbutton setTitleColor:[UIColor colorWithRed:0.29f green:0.29f blue:0.29f alpha:1.0f] forState:UIControlStateNormal];
[listRootbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[listRootbutton setTitle: [leftRootList objectAtIndex:i] forState:UIControlStateNormal];
[listRootbutton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[listRootbutton setTitleEdgeInsets:UIEdgeInsetsMake(0, 30, 0, 0)];
[listRootbutton setTag:i];
listRootbutton.titleLabel.font = font;
[leftMenuScroll addSubview:listRootbutton];
}
}
-(void)ClearLeftScrollView
{
NSArray *subviews = leftMenuScroll.subviews;
for(int i =0;i<[subviews count];i++)
{
[[subviews objectAtIndex:i] removeFromSuperview];
}
}
-(void)listRootbuttonPressed:(id)sender
{
nIndexRootWallpaper = -1;
UIImageView* bgLeftMenuScroll = [Util tileImage:@"bg_lnb_m" resultX:0 resultY:0 resultWidth:188 resultHeight:530];
self.secDepthViewWallpaper = [[UIView alloc]initWithFrame:CGRectMake(-188, 110 ,0, 530)];
[self.secDepthViewWallpaper addSubview:bgLeftMenuScroll];
[self.view addSubview:self.secDepthViewWallpaper];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[self.secDepthViewWallpaper setFrame:CGRectMake(11,110,188,530)];
[UIView commitAnimations];
switch ([sender tag]) {
case 0:
{
nIndexRootWallpaper = 0;
NSMutableArray* secWallpaperList = [[NSMutableArray alloc] init ];
[secWallpaperList addObject:@"지아벽지"];
[secWallpaperList addObject:@"베라왕"];
[secWallpaperList addObject:@"애냐라킨"];
[secWallpaperList addObject:@"뮤럴벽지"];
[self makesubDepthWallpaperButton:secWallpaperList];
}
break;
case 1:
{
nIndexRootWallpaper = 1;
NSMutableArray* secWallpaperList = [[NSMutableArray alloc] init ];
[secWallpaperList addObject:@"공기를 살리는 벽지"];
[secWallpaperList addObject:@"아이비리그"];
[secWallpaperList addObject:@"실크NB"];
[secWallpaperList addObject:@"실크테라피"];
[secWallpaperList addObject:@"방염벽지"];
[self makesubDepthWallpaperButton:secWallpaperList];
}
break;
case 2:
{
nIndexRootWallpaper = 2;
NSMutableArray* secWallpaperList = [[NSMutableArray alloc] init ];
[secWallpaperList addObject:@"휘앙새"];
[self makesubDepthWallpaperButton:secWallpaperList];
}
break;
case 3:
{
nIndexRootWallpaper = 3;
NSMutableArray* secWallpaperList = [[NSMutableArray alloc] init ];
[secWallpaperList addObject:@"공기를 살리는 숨타일"];
[self makesubDepthWallpaperButton:secWallpaperList];
}
break;
default:
break;
}
}
-(void)makesubDepthWallpaperButton:(NSMutableArray*)list
{
UIButton* TopButton = [UIButton buttonWithType:UIButtonTypeCustom];
[TopButton setFrame: CGRectMake(0, 0, 188, 50)];
[TopButton setBackgroundImage:rootButtonImg forState:UIControlStateNormal];
[TopButton setBackgroundImage:rootButtonPressedImg forState:UIControlStateHighlighted];
[TopButton addTarget:self action:@selector(wallpaperTopButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[TopButton setTitleColor:[UIColor colorWithRed:0.29f green:0.29f blue:0.29f alpha:1.0f] forState:UIControlStateNormal];
[TopButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[TopButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[TopButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 50, 0, 0)];
[TopButton setTitle:[Util findWallpaperRootCategoryName: nIndexRootWallpaper ] forState:UIControlStateNormal];
[self.secDepthViewWallpaper addSubview:TopButton];
for(int i = 0; i < [list count];i++)
{
UIFont *font;
font = [UIFont boldSystemFontOfSize:14];
UIButton *listLastDepthButton;
listLastDepthButton = [[UIButton alloc] initWithFrame:CGRectMake(0, i*50+50, 188, 50)];
[listLastDepthButton setBackgroundImage:rootButtonImg forState:UIControlStateNormal];
[listLastDepthButton setBackgroundImage:rootButtonPressedImg forState:UIControlStateHighlighted];
[listLastDepthButton addTarget:self action:@selector(leftlistLastDepthButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[listLastDepthButton setTitleColor:[UIColor colorWithRed:0.29f green:0.29f blue:0.29f alpha:1.0f] forState:UIControlStateNormal];
[listLastDepthButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[listLastDepthButton setTitle: [list objectAtIndex:i] forState:UIControlStateNormal];
[listLastDepthButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[listLastDepthButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 30, 0, 0)];
[listLastDepthButton setTag:i];
listLastDepthButton.titleLabel.font = font;
[secDepthViewWallpaper addSubview:listLastDepthButton];
}
}
-(void)wallpaperTopButtonPressed:(id)sender
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[secDepthViewWallpaper setFrame:CGRectMake(-188,110,0, 530)];
[UIView commitAnimations];
}
-(void)leftlistLastDepthButtonPressed:(id)sender
{
int nCategoryIndex;
nCategoryIndex = [Util findCategory: nIndexRootWallpaper sub:[sender tag]];
[self leftTreeViewSelect:nCategoryIndex haschilden:NO];
}
-(void)rightMenuView
{
UIImageView* bgRightMenuScroll = [Util tileImage:@"bg_lnb_m" resultX:0 resultY:0 resultWidth:188 resultHeight:530];
rightMenuScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(11, 110, 188, 530)];
[rightMenuScroll setContentSize:CGSizeMake(188, 50*10 + SAMPLE_LIST_HIGHT)];
[rightMenuScroll addSubview:bgRightMenuScroll];
[self._rightMenuBar addSubview:rightMenuScroll];
UIImage* rightMenuTitleImage = [UIImage imageNamed:@"tit_rnb"];
UIImageView* rightMenuTitleImageView = [[UIImageView alloc] initWithImage:rightMenuTitleImage];
[rightMenuTitleImageView setFrame:CGRectMake(11, 11, 188, 99)];
[self._rightMenuBar addSubview:rightMenuTitleImageView];
// UIImage* homeFloorImage = [UIImage imageNamed:rootButtonImg];
UIImageView* homeFloorImageView = [[UIImageView alloc] initWithImage:rootButtonImg];
[homeFloorImageView setFrame:CGRectMake(0, 0, 188, 50)];
[rightMenuScroll addSubview:homeFloorImageView];
UILabel* homeFloorTitlelb = [[UILabel alloc] initWithFrame:CGRectMake(50, 10, 188, 30)];
[homeFloorTitlelb setBackgroundColor:[UIColor clearColor]];
[homeFloorTitlelb setFont:[UIFont boldSystemFontOfSize:18]];
[homeFloorTitlelb setText:@"주택용 바닥재"];
[homeFloorImageView addSubview:homeFloorTitlelb];
// UIImage* storeFloorImage = [UIImage imageNamed:rootButtonImg];
UIImageView* storeFloorImageView = [[UIImageView alloc] initWithImage:rootButtonImg];
[storeFloorImageView setFrame:CGRectMake(0, 212, 188, 50)];
[rightMenuScroll addSubview:storeFloorImageView];
UILabel* storeFloorTitlelb = [[UILabel alloc] initWithFrame:CGRectMake(50, 10, 188, 30)];
[storeFloorTitlelb setBackgroundColor:[UIColor clearColor]];
[storeFloorTitlelb setFont:[UIFont boldSystemFontOfSize:18]];
[storeFloorTitlelb setText:@"상업용 바닥재"];
[storeFloorImageView addSubview:storeFloorTitlelb];
[rightMenuScroll setContentSize:CGSizeMake(188, 50*10 + SAMPLE_LIST_HIGHT)];
[self MakeRightMenuButton:YES];
[self MakeRightMenuButton:NO];
UIImageView* storeFloorImageLastView = [[UIImageView alloc] initWithImage:subButtonLastImg];
[storeFloorImageLastView setFrame:CGRectMake(0, 463, 188, 61)];
[rightMenuScroll addSubview:storeFloorImageLastView];
}
-(void)MakeRightMenuButton:(BOOL)homeORStore
{
if(homeORStore)
{
NSMutableArray* subHomeFloor = [[NSMutableArray alloc] init];
[subHomeFloor addObject:@"마루"];
[subHomeFloor addObject:@"시트"];
[subHomeFloor addObject:@"타일"];
for (int i = 0; i < [subHomeFloor count]; i++)
{
UIFont *font;
font = [UIFont boldSystemFontOfSize:16];
UIButton *listRootbutton;
if(i == [subHomeFloor count] -1)
{
listRootbutton = [[UIButton alloc] initWithFrame:CGRectMake(0, i*50+50, 188, 61)];
[listRootbutton setBackgroundImage:subButtonLastImg forState:UIControlStateNormal];
[listRootbutton setBackgroundImage:rootButtonPressedImg forState:UIControlStateHighlighted];
[listRootbutton setTitleEdgeInsets:UIEdgeInsetsMake(-10, 50, 0, 0)];
}
else
{
listRootbutton = [[UIButton alloc] initWithFrame:CGRectMake(0, i*50+50, 188, 50)];
[listRootbutton setBackgroundImage:rootButtonImg forState:UIControlStateNormal];
[listRootbutton setBackgroundImage:rootButtonPressedImg forState:UIControlStateHighlighted];
[listRootbutton setTitleEdgeInsets:UIEdgeInsetsMake(0, 50, 0, 0)];
}
[listRootbutton addTarget:self action:@selector(rightListSubButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[listRootbutton setTitleColor:[UIColor colorWithRed:0.29f green:0.29f blue:0.29f alpha:1.0f] forState:UIControlStateNormal];
[listRootbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[listRootbutton setTitle: [subHomeFloor objectAtIndex:i] forState:UIControlStateNormal];
[listRootbutton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[listRootbutton setTag:i];
listRootbutton.titleLabel.font = font;
[rightMenuScroll addSubview:listRootbutton];
}
}
else
{
NSMutableArray* subHomeFloor = [[NSMutableArray alloc] init];
[subHomeFloor addObject:@"타일"];
[subHomeFloor addObject:@"시트"];
[subHomeFloor addObject:@"카펫타일"];
[subHomeFloor addObject:@"스톤타일"];
for (int i = 0; i < [subHomeFloor count]; i++)
{
UIFont *font;
font = [UIFont boldSystemFontOfSize:16];
UIButton *listRootbutton;
listRootbutton = [[UIButton alloc] initWithFrame:CGRectMake(0, i*50+262, 188, 50)];
[listRootbutton setBackgroundImage:rootButtonImg forState:UIControlStateNormal];
[listRootbutton setBackgroundImage:rootButtonPressedImg forState:UIControlStateHighlighted];
[listRootbutton addTarget:self action:@selector(rightListSubButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[listRootbutton setTitleColor:[UIColor colorWithRed:0.29f green:0.29f blue:0.29f alpha:1.0f] forState:UIControlStateNormal];
[listRootbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[listRootbutton setTitle: [subHomeFloor objectAtIndex:i] forState:UIControlStateNormal];
[listRootbutton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[listRootbutton setTitleEdgeInsets:UIEdgeInsetsMake(0, 50, 0, 0)];
[listRootbutton setTag:i+10];
listRootbutton.titleLabel.font = font;
[rightMenuScroll addSubview:listRootbutton];
}
}
}
-(void)rightListSubButtonPressed:(id)sender
{
[self rightListButtonClickSubView:[sender tag]];
// [self TreeViewSelect:[sender tag] haschilden:NO];
}
-(void)rightListButtonClickSubView:(int)index
{
nIndexRoot = -1;
UIImageView* bgRightMenuScroll = [Util tileImage:@"bg_lnb_m" resultX:0 resultY:0 resultWidth:188 resultHeight:530];
self.secDepthView = [[UIView alloc]initWithFrame:CGRectMake(1024, 110 ,0, 530)];
[self.secDepthView addSubview:bgRightMenuScroll];
UIScrollView* secDepthScroll = [[UIScrollView alloc] init];
[secDepthScroll setFrame:CGRectMake(0, 0, 188, 530)];
[secDepthScroll setBackgroundColor:[UIColor clearColor]];
[self.secDepthView addSubview:secDepthScroll];
[self.view addSubview:self.secDepthView];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[self.secDepthView setFrame:CGRectMake(1024-192,110,188,530)];
[UIView commitAnimations];
NSMutableArray* itemList = [[NSMutableArray alloc] init];
switch (index) {
case 0:
{
nIndexRoot = 0;
[itemList addObject:@"지아마루 - 프레스티지"];
[itemList addObject:@"지아마루 - 7"];
[itemList addObject:@"원목마루"];
[itemList addObject:@"녹차마루"];
[itemList addObject:@"강그린마루"];
[itemList addObject:@"포르테마루 - 광폭"];
[itemList addObject:@"포르테마루 - 소폭"];
}
break;
case 1:
{
nIndexRoot = 1;
[itemList addObject:@"소리잠"];
[itemList addObject:@"휴앤미"];
[itemList addObject:@"네이쳐라이프"];
[itemList addObject:@"자연애2.5"];
[itemList addObject:@"자연애2.2"];
[itemList addObject:@"자연애1.8"];
[itemList addObject:@"뉴청맥1.8"];
}
break;
case 2:
{
nIndexRoot = 2;
[itemList addObject:@"하우스"];
}
break;
case 10:
{
nIndexRoot = 3;
[itemList addObject:@"데코타일 - 파인.5"];
[itemList addObject:@"데코타일 - 갤러리"];
[itemList addObject:@"데코타일 - 에코노"];
[itemList addObject:@"하우스 이지"];
[itemList addObject:@"VIP타일-VIP마블/포스트"];
[itemList addObject:@"VIP타일-VIP인레이드"];
[itemList addObject:@"VCT타일-갤런트"];
[itemList addObject:@"VCT타일-GR"];
[itemList addObject:@"VCT타일-디럭스"];
[itemList addObject:@"기능성타일-VIP전도성"];
[itemList addObject:@"기능성타일-OA"];
}
break;
case 11:
{
nIndexRoot = 4;
[itemList addObject:@"우븐"];
[itemList addObject:@"지아플로어 호모젠"];
[itemList addObject:@"엘스트롱 유나이트"];
[itemList addObject:@"엘스트롱 클레버"];
[itemList addObject:@"엘스트롱 노블아트"];
[itemList addObject:@"네이쳐라이프"];
[itemList addObject:@"와이드"];
[itemList addObject:@"EQ플로어"];
[itemList addObject:@"렉스코트"];
[itemList addObject:@"SD메탈/트랜스"];
}
break;
case 12:
{
nIndexRoot = 5;
[itemList addObject:@"Style"];
[itemList addObject:@"L1000"];
[itemList addObject:@"L9300"];
[itemList addObject:@"L9600"];
[itemList addObject:@"L9700"];
[itemList addObject:@"L3300"];
[itemList addObject:@"L7000"];
}
break;
case 13:
{
nIndexRoot = 6;
[itemList addObject:@"마블"];
[itemList addObject:@"폴리싱"];
}
break;
default:
break;
}
[secDepthScroll setContentSize:CGSizeMake(188, [itemList count]*50+50)];
[self makesubDepthButton:itemList scroll:secDepthScroll];
}
-(void)TopButtonPressed:(id)sender
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[secDepthView setFrame:CGRectMake(1024,110,0, 530)];
[UIView commitAnimations];
}
-(void)makesubDepthButton:(NSMutableArray*)list scroll:(UIScrollView*)scrollView
{
UIButton* TopButton = [UIButton buttonWithType:UIButtonTypeCustom];
[TopButton setFrame: CGRectMake(0, 0, 188, 50)];
[TopButton setBackgroundImage:rootButtonImg forState:UIControlStateNormal];
[TopButton setBackgroundImage:rootButtonPressedImg forState:UIControlStateHighlighted];
[TopButton addTarget:self action:@selector(TopButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[TopButton setTitleColor:[UIColor colorWithRed:0.29f green:0.29f blue:0.29f alpha:1.0f] forState:UIControlStateNormal];
[TopButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[TopButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[TopButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 50, 0, 0)];
[TopButton setTitle:[Util findFloorRootCategoryName: nIndexRoot ] forState:UIControlStateNormal];
[scrollView addSubview:TopButton];
for(int i = 0; i < [list count];i++)
{
UIFont *font;
font = [UIFont boldSystemFontOfSize:14];
UIButton *listLastDepthButton;
listLastDepthButton = [[UIButton alloc] initWithFrame:CGRectMake(0, i*50+50, 188, 50)];
[listLastDepthButton setBackgroundImage:rootButtonImg forState:UIControlStateNormal];
[listLastDepthButton setBackgroundImage:rootButtonPressedImg forState:UIControlStateHighlighted];
[listLastDepthButton addTarget:self action:@selector(rightlistLastDepthButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[listLastDepthButton setTitleColor:[UIColor colorWithRed:0.29f green:0.29f blue:0.29f alpha:1.0f] forState:UIControlStateNormal];
[listLastDepthButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[listLastDepthButton setTitle: [list objectAtIndex:i] forState:UIControlStateNormal];
[listLastDepthButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[listLastDepthButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 30, 0, 0)];
[listLastDepthButton setTag:i];
listLastDepthButton.titleLabel.font = font;
[scrollView addSubview:listLastDepthButton];
}
}
-(void)rightlistLastDepthButtonPressed:(id)sender
{
nIndexSub = [sender tag];
categoryValue = [Util findCategory:nIndexRoot sub:nIndexSub];
[self TreeViewSelect: nIndexRoot haschilden:NO];
}
-(void)bottomMenuView
{
UIButton* zinButton = [UIButton buttonWithType:UIButtonTypeCustom];
[zinButton setFrame:CGRectMake(0,718 ,213, 50)];
UIImage* zinLogoImg = [UIImage imageNamed:@"h1_logo"];
[zinButton setImage:zinLogoImg forState:UIControlStateNormal];
[zinButton addTarget:self action:@selector(zinButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:zinButton];
UIButton* zinSampleBookButton = [UIButton buttonWithType:UIButtonTypeCustom];
[zinSampleBookButton setFrame:CGRectMake(213,718 ,199, 50)];
UIImage* zinSampleBookButtonImg = [UIImage imageNamed:@"gnb_01"];
[zinSampleBookButton setImage:zinSampleBookButtonImg forState:UIControlStateNormal];
UIImage* zinSampleBookButtonPressedImg = [UIImage imageNamed:@"gnb_01_on"];
[zinSampleBookButton setImage:zinSampleBookButtonPressedImg forState:UIControlStateHighlighted];
[zinSampleBookButton addTarget:self action:@selector(zinSampleBookButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:zinSampleBookButton];
UIButton* smartCounselButton = [UIButton buttonWithType:UIButtonTypeCustom];
[smartCounselButton setFrame:CGRectMake(412,718 ,199, 50)];
UIImage* smartCounselButtonImg = [UIImage imageNamed:@"gnb_02"];
[smartCounselButton setImage:smartCounselButtonImg forState:UIControlStateNormal];
UIImage* smartCounselButtonPressedImg = [UIImage imageNamed:@"gnb_02"];
[smartCounselButton setImage:smartCounselButtonPressedImg forState:UIControlStateHighlighted];
[smartCounselButton addTarget:self action:@selector(smartCounselButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:smartCounselButton];
UIButton* mBrochureButton = [UIButton buttonWithType:UIButtonTypeCustom];
[mBrochureButton setFrame:CGRectMake(611,718 ,201, 50)];
UIImage* mBrochureButtonImg = [UIImage imageNamed:@"gnb_03"];
[mBrochureButton setImage:mBrochureButtonImg forState:UIControlStateNormal];
UIImage* mBrochureButtonPressedImg = [UIImage imageNamed:@"gnb_03"];
[mBrochureButton setImage:mBrochureButtonPressedImg forState:UIControlStateHighlighted];
[mBrochureButton addTarget:self action:@selector(mBrochureButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:mBrochureButton];
UIButton* matchingButton = [UIButton buttonWithType:UIButtonTypeCustom];
[matchingButton setFrame:CGRectMake(812,718 ,53, 50)];
UIImage* matchingButtonImg = [UIImage imageNamed:@"btn_option_01"];
[matchingButton setImage:matchingButtonImg forState:UIControlStateNormal];
UIImage* matchingButtonPressedImg = [UIImage imageNamed:@"btn_option_01"];
[matchingButton setImage:matchingButtonPressedImg forState:UIControlStateHighlighted];
[matchingButton addTarget:self action:@selector(matchingButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:matchingButton];
UIButton* calcButton = [UIButton buttonWithType:UIButtonTypeCustom];
[calcButton setFrame:CGRectMake(865,718 ,53, 50)];
UIImage* calcButtonImg = [UIImage imageNamed:@"btn_option_02"];
[calcButton setImage:calcButtonImg forState:UIControlStateNormal];
UIImage* calcButtonPressedImg = [UIImage imageNamed:@"btn_option_02"];
[calcButton setImage:calcButtonPressedImg forState:UIControlStateHighlighted];
[calcButton addTarget:self action:@selector(calcButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:calcButton];
UIButton* aboutButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aboutButton setFrame:CGRectMake(918,718 ,53, 50)];
UIImage* aboutButtonImg = [UIImage imageNamed:@"btn_option_03"];
[aboutButton setImage:aboutButtonImg forState:UIControlStateNormal];
UIImage* aboutButtonPressedImg = [UIImage imageNamed:@"btn_option_03"];
[aboutButton setImage:aboutButtonPressedImg forState:UIControlStateHighlighted];
[aboutButton addTarget:self action:@selector(aboutButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:aboutButton];
UIButton* settingButton = [UIButton buttonWithType:UIButtonTypeCustom];
[settingButton setFrame:CGRectMake(971,718 ,53, 50)];
UIImage* settingButtonImg = [UIImage imageNamed:@"btn_option_04"];
[settingButton setImage:settingButtonImg forState:UIControlStateNormal];
UIImage* settingButtonPressedImg = [UIImage imageNamed:@"btn_option_04"];
[settingButton setImage:settingButtonPressedImg forState:UIControlStateHighlighted];
[settingButton addTarget:self action:@selector(settingButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:settingButton];
}
-(void)matchingButtonPressed:(id)sender
{
MatchingViewController* abc = [[MatchingViewController alloc] init];
[self.navigationController pushViewController:abc animated:YES];
}
-(void)calcButtonPressed:(id)sender
{
}
-(void)aboutButtonPressed:(id)sender
{
}
-(void)settingButtonPressed:(id)sender
{
}
-(void)mainStageView
{
// 메인스테이지 라벨
UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(50, SIZE_TOPBAR + 200, 400, 20)];
[label setText:@"Select a menu"];
[label setTextAlignment:UITextAlignmentLeft];
[label setBackgroundColor:[UIColor clearColor]];
[label setFont:[UIFont systemFontOfSize:20.0f]];
[self._mainStage addSubview:label];
UIButton* SearchButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[SearchButton setFrame:CGRectMake(400,SIZE_TOPBAR + 500 , 200, 36)];
[SearchButton setTitle:[NSString stringWithFormat:@"검색결과 제품보기"] forState:UIControlStateNormal];
[SearchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[SearchButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[SearchButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 45, 5, 5)];
[SearchButton addTarget:self action:@selector(SearchButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self._mainStage addSubview:SearchButton];
}
-(void)dealloc
{
[self._leftMenuBar release];
[self._mainStage release];
[self._rightMenuBar release];
// [tv release];
[super dealloc];
}
-(void)zinButtonPressed:(id)sender
{
[sampleBookView.view removeFromSuperview];
[sampleBookViewFlooring.view removeFromSuperview];
// [tv.view removeFromSuperview];
[sampleBookView release];
[sampleBookViewFlooring release];
// [tv release];
// [self.view removeFromSuperview];
// [_mainStage release];
// [sampleBookView release];
// [sampleBookViewFlooring release];
[self viewDidLoad];
// self._mainStage = [[UIView alloc] initWithFrame:CGRectMake(200, SIZE_TOPBAR,1024-SIZE_WIDE*2, 748)];
// [self._mainStage setBackgroundColor:[UIColor grayColor]];
// [self.view addSubview:self._mainStage];
// [self mainStageView];
// [tv.view setFrame:CGRectMake(SIZE_WIDE+1024-(SIZE_WIDE*2)+20, SIZE_TOPBAR, SIZE_WIDE-20, 748)];
}
-(void)MatchingButtonPressed:(id)sender
{
}
-(void)CalButtonPressed:(id)sender
{
}
-(void)SetButtonPressed:(id)sender
{
}
-(void)HelpButtonPressed:(id)sender
{
}
-(void)zinSampleBookButtonPressed:(id)sender
{
}
-(void)smartCounselButtonPressed:(id)sender
{
SmartCounselMainView* smartCounselMainView = [[SmartCounselMainView alloc] init];
[self.navigationController pushViewController:smartCounselMainView animated:YES];
[self release];
}
-(void)mBrochureButtonPressed:(id)sender
{
MbochureMainView* abc = [[MbochureMainView alloc] init];
[self.navigationController pushViewController:abc animated:YES];
// [self release];
}
#pragma mark - Button Handler
-(void)buttonPressed:(id)sender
{
// 메인스테이지에 선택된 버튼 타이틀 표시
// [self.navigationController pushViewController:sampleBookView animated:YES];
}
-(void)TreeViewSelect:(NSInteger)selectedIndex haschilden:(BOOL)lastElement
{
// NSLog(@"delegate Come ");
NSLog(@"%d",selectedIndex);
if(CurrentViewIndex == 2)
{
treeSelectIndex = selectedIndex;
// if(lastElement)
// {
// NSLog(@"%d ",lastElement);
// [self TreeViewSelectView];
// }
return;
}
float mainStageWidth = CurrentView.frame.size.width;
[self._mainStage removeFromSuperview];
[sampleBookView.view removeFromSuperview];
[sampleBookViewFlooring.view removeFromSuperview];
[sampleBookViewFlooring.view setFrame:CGRectMake(self._leftMenuBar.frame.origin.x + SIZE_WIDE, CurrentView.frame.origin.y, mainStageWidth, CurrentView.frame.size.height)];
// [sampleBookViewFlooring.view setBackgroundColor:[UIColor yellowColor]];
[self.view addSubview:sampleBookViewFlooring.view];
CurrentView = sampleBookViewFlooring.view;
CurrentViewIndex = 2;
UIView* wideMenu;
UIView* narrowMenu;
wideMenu = self._rightMenuBar;
narrowMenu = self._leftMenuBar;
// float mainStageWidth = CurrentView.frame.size.width;
float sizeDiscrepancy = SIZE_WIDE - SIZE_NARROW;
if(!_isExpanded)
{
_isExpanded = YES;
mainStageWidth = CurrentView.frame.size.width + sizeDiscrepancy;
}
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[self._leftMenuBar setFrame:CGRectMake(-(SIZE_WIDE/2), self._leftMenuBar.frame.origin.y, self._leftMenuBar.frame.size.width, self._leftMenuBar.frame.size.height)];
[self.CurrentView setFrame:CGRectMake((SIZE_WIDE/2), CurrentView.frame.origin.y, CurrentView.frame.size.width , CurrentView.frame.size.height)];
[self._rightMenuBar setFrame:CGRectMake(1024-SIZE_WIDE, 0, SIZE_WIDE, 718-11)];
[UIView commitAnimations];
// [tv.view setFrame:CGRectMake(SIZE_WIDE+1024-(SIZE_WIDE*2)+20, 0, SIZE_WIDE-20, 700)];
// CurrentView = sampleBookViewFlooring.view;
treeSelectIndex = selectedIndex;
// if(lastElement)
// {
// NSLog(@"%d ",lastElement);
// [self TreeViewSelectView];
// }
// [self.view bringSubviewToFront:self._leftMenuBar];
// [self.view bringSubviewToFront:self._rightMenuBar];
// [self.view bringSubviewToFront:tv.view];
// [self.view bringSubviewToFront:self._leftMenuBar];
}
-(void)leftTreeViewSelect:(NSInteger)selectedIndex haschilden:(BOOL)lastElement
{
[sampleBookViewFlooring.view removeFromSuperview];
if(CurrentViewIndex == 2)
{
[sampleBookView.view setFrame:CGRectMake(204, 11, 1024-204-204/2, 686)];
[sampleBookView categoryIndexReceive:selectedIndex];
// [sampleBookView.view setBackgroundColor:[UIColor blueColor]];
////////////////////////////
//이미지 갯수 받아와서 전송해야 함
//////////////////////////
[self.view addSubview:sampleBookView.view];
}
else
{
[sampleBookView.view setFrame:CGRectMake(204, 11, 1024-204-204/2, 686)];
[sampleBookView categoryIndexReceive:selectedIndex];
// [sampleBookView.view setBackgroundColor:[UIColor blueColor]];
////////////////////////////
//이미지 갯수 받아와서 전송해야 함
////////////////////////////
[self.view addSubview:sampleBookView.view];
}
CurrentView = sampleBookView.view;
CurrentViewIndex = 1;
// 왼쪽/오른쪽 메뉴영역 크기 조절 애니메이션 부분
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
// [self._leftMenuBar setFrame:CGRectMake(0, 0, SIZE_WIDE, 718-11)];
[self.CurrentView setFrame:CGRectMake(204, 11, 1024-204-204/2, 686)];
[self._rightMenuBar setFrame:CGRectMake(1024-SIZE_WIDE + SIZE_WIDE/2 , self._rightMenuBar.frame.origin.y, SIZE_WIDE, self._rightMenuBar.frame.size.height)];
// [self.view bringSubviewToFront:self._rightMenuBar];
// [self.view bringSubviewToFront:self._leftMenuBar];
[UIView commitAnimations];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
-(void)SearchButtonPressed:(id)sender
{
SmartSearchView * smartSearchView = [[SmartSearchView alloc] init];
[self.navigationController pushViewController:smartSearchView animated:YES];
}
@end
| 009-20120511-zi | trunk/Zinipad/ZinMainViewController.m | Objective-C | gpl3 | 38,397 |
//
// AppDelegate.h
// Zinipad
//
// Created by Kamain on 12. 5. 17..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "ZinMainViewController.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
UINavigationController* _aNavigationContoller;
ZinMainViewController* zinMainViewController;
}
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, retain) UINavigationController* _aNavigationController;
@end
| 009-20120511-zi | trunk/Zinipad/AppDelegate.h | Objective-C | gpl3 | 502 |
//
// MatchingViewController.m
// Zinipad
//
// Created by ZeLkOvA on 12. 6. 25..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import "MatchingViewController.h"
#import <QuartzCore/QuartzCore.h>
@interface MatchingViewController ()
@end
@implementation MatchingViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// UIView *view = [[UIView alloc] init];
// [view setFrame:CGRectMake(200, 100, 1024/3, 768/1.5f)];
// UIImage* leftMenuTitleImage = [UIImage imageNamed:@"x"];
// UIImageView* leftMenuTitleImageView = [[UIImageView alloc] initWithImage:leftMenuTitleImage];
// [leftMenuTitleImageView setFrame:CGRectMake(0, 0, 1024/3, 768/1.5f)];
// [view addSubview:leftMenuTitleImageView];
//
// CALayer *layer = view.layer;
// CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
// rotationAndPerspectiveTransform.m34 = 1.0 / -500;
// rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 25.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
// layer.transform = rotationAndPerspectiveTransform;
//
// [self.view addSubview:view];
//
// UIView *view2 = [[UIView alloc] init];
// [view2 setFrame:CGRectMake(130+1024/3, 100, 1024/3, 768/1.5f)];
// UIImage* MenuTitleImage = [UIImage imageNamed:@"y"];
// UIImageView* MenuTitleImageView = [[UIImageView alloc] initWithImage:MenuTitleImage];
// [MenuTitleImageView setFrame:CGRectMake(0, 0, 1024/3, 768/1.5f)];
// [view2 addSubview:MenuTitleImageView];
//
// CALayer *layer2 = view2.layer;
// CATransform3D rotationAndPerspectiveTransform2 = CATransform3DIdentity;
// rotationAndPerspectiveTransform2.m34 = 1.0 / -500;
// rotationAndPerspectiveTransform2 = CATransform3DRotate(rotationAndPerspectiveTransform2, -25.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
// layer2.transform = rotationAndPerspectiveTransform2;
// [self.view addSubview:view2];
// UIImage* a = [UIImage imageNamed:@"img_left_box.png"];
// UIImage* b = [UIImage imageNamed:@"img_right_slice_box.png"];
//
// UIImage* abc = [self maskingImage:a maskImage:@"img_right_slice_box"];
// UIImageView* ImageView = [[UIImageView alloc] initWithImage:abc];
// [ImageView setFrame:CGRectMake(200, 100, 330, 441)];
// [ImageView setBackgroundColor:[UIColor clearColor]];
// [self.view addSubview:ImageView];
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(UIImage *)maskingImage:(UIImage *)image maskImage:(NSString*)_maskImage
{
CGImageRef imageRef = [image CGImage];
CGImageRef maskRef = [[UIImage imageNamed:_maskImage] CGImage];
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef),
NULL, false);
CGImageRef masked = CGImageCreateWithMask(imageRef, mask);
CGImageRelease(mask);
UIImage *maskedImage = [UIImage imageWithCGImage:masked];
CGImageRelease(masked);
return maskedImage;
}
@end
| 009-20120511-zi | trunk/Zinipad/MatchingViewController.m | Objective-C | gpl3 | 3,658 |
//
// main.m
// Zinipad
//
// Created by ZeLkOvA on 12. 5. 17..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char *argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
| 009-20120511-zi | trunk/Zinipad/main.m | Objective-C | gpl3 | 344 |
//
// MyTreeViewCell.h
// MyTreeViewPrototype
//
// Created by Jon Limjap on 4/21/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface MyTreeViewCell : UITableViewCell {
UILabel *valueLabel;
UIImageView *arrowImage;
int level;
BOOL expanded;
}
@property (nonatomic, retain) UILabel *valueLabel;
@property (nonatomic, retain) UIImageView *arrowImage;
@property (nonatomic) int level;
@property (nonatomic) BOOL expanded;
- (id)initWithStyle:(UITableViewCellStyle)style
reuseIdentifier:(NSString *)reuseIdentifier
level:(NSUInteger)_level
expanded:(BOOL)_expanded;
@end
| 009-20120511-zi | trunk/Zinipad/MyTreeViewCell.h | Objective-C | gpl3 | 656 |
//
// RootViewController.m
// MyTreeViewPrototype
//
// Created by Jon Limjap on 4/21/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "LeftTreeView.h"
#import "MyTreeViewCell.h"
#import "KakaoLinkCenter.h"
@implementation LeftTreeView
@synthesize leftTrdelegate;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
treeNode = [[MyTreeNode alloc] initWithValue:@"Root"];
MyTreeNode *node1 = [[MyTreeNode alloc] initWithValue:@"프리미엄벽지"];
[treeNode addChild:node1];
MyTreeNode *node1a = [[MyTreeNode alloc] initWithValue:@"지아벽지"];
MyTreeNode *node1b = [[MyTreeNode alloc] initWithValue:@"베라왕"];
MyTreeNode *node1c = [[MyTreeNode alloc] initWithValue:@"애냐라킨"];
MyTreeNode *node1d = [[MyTreeNode alloc] initWithValue:@"뮤럴벽지"];
[node1 addChild:node1a];
[node1 addChild:node1b];
[node1 addChild:node1c];
[node1 addChild:node1d];
MyTreeNode *node2 = [[MyTreeNode alloc] initWithValue:@"실크벽지"];
[treeNode addChild:node2];
MyTreeNode *node2a = [[MyTreeNode alloc] initWithValue:@"공기를 살리는 벽지"];
MyTreeNode *node2b = [[MyTreeNode alloc] initWithValue:@"아이비리그"];
MyTreeNode *node2c = [[MyTreeNode alloc] initWithValue:@"실크NB"];
MyTreeNode *node2d = [[MyTreeNode alloc] initWithValue:@"실크테라피"];
MyTreeNode *node2e = [[MyTreeNode alloc] initWithValue:@"방염벽지"];
[node2 addChild:node2a];
[node2 addChild:node2b];
[node2 addChild:node2c];
[node2 addChild:node2d];
[node2 addChild:node2e];
MyTreeNode *node3 = [[MyTreeNode alloc] initWithValue:@"합지벽지"];
[treeNode addChild:node3];
MyTreeNode *node3a = [[MyTreeNode alloc] initWithValue:@"휘앙새"];
[node3 addChild:node3a];
node1.inclusive = NO;
node2.inclusive = NO;
node3.inclusive = NO;
// node1b.inclusive = NO;
MyTreeNode *node4 = [[MyTreeNode alloc] initWithValue:@"벽타일"];
[treeNode addChild:node4];
node4.inclusive = NO;
MyTreeNode *node4a = [[MyTreeNode alloc] initWithValue:@"공기룰 살리는 숨타일"];
[node4 addChild:node4a];
MyTreeNode *node9 = [[MyTreeNode alloc] initWithValue:@"MY샘플북"];
[treeNode addChild:node9];
// MyTreeNode *node8 = [[MyTreeNode alloc] initWithValue:@""];
// [treeNode addChild:node8];
// MyTreeNode *node4 = [[MyTreeNode alloc] initWithValue:@"MY샘플북"];
// [treeNode addChild:node4];
// MyTreeNode *node2a1 = [[MyTreeNode alloc] initWithValue:@"Node2a1"];
// [node2a addChild:node2a1];
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// descendantCount = descendantCount +1;
NSLog(@"%d",[treeNode descendantCount]);
// self.contentSizeForViewInPopover = CGSizeMake(self.view.frame.size.width, [treeNode descendantCount]*44 + 100);
return [treeNode descendantCount];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
MyTreeNode *node = [[treeNode flattenElements] objectAtIndex:indexPath.row + 1];
MyTreeViewCell *cell = [[MyTreeViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier
level:[node levelDepth] - 1
expanded:node.inclusive];
// UIImage* aaa = [UIImage imageNamed:@"x"];
// UIImageView* aaaa = [[UIImageView alloc] initWithImage:aaa];
// aaaa.frame = CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height);
// [cell addSubview:aaaa];
cell.valueLabel.text = node.value;
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
MyTreeNode *node = [[treeNode flattenElements] objectAtIndex:indexPath.row + 1];
if (!node.hasChildren)
{
[self.leftTrdelegate leftTreeViewSelect:indexPath.row haschilden:YES];
[tableView reloadData];
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
[cell setSelected:NO animated:YES];
return;
}
else
{
node.inclusive = !node.inclusive;
[treeNode flattenElementsWithCacheRefresh:YES];
[self.leftTrdelegate leftTreeViewSelect:indexPath.row haschilden:NO];
[tableView reloadData];
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
[cell setSelected:NO animated:YES];
}
/////
//
// NSString *message = @"카카오링크를 사용하여 메시지를 전달해보세요."; // 메세지
// NSString *referenceURLString = @"http://link.kakao.com"; // 링크 넘기기
// NSString *appBundleID = @"com.example.app";
// NSString *appVersion = @"2.0";
// NSString *appName = @"example"; // 제목
//
// if ([[KakaoLinkCenter defaultCenter] canOpenKakaoLink]) {
// [[KakaoLinkCenter defaultCenter] openKakaoLinkWithURL:referenceURLString
// appVersion:appVersion
// appBundleID:appBundleID
// appName:appName
// message:message];
// } else {
// // 카카오톡이 설치되어 있지 않은 경우에 대한 처리
// NSLog(@"카카오톡 없음요");
// }
// NSLog(@"%d",indexPath.row);
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
| 009-20120511-zi | trunk/Zinipad/LeftTreeView.m | Objective-C | gpl3 | 6,428 |
//
// Util.h
// Zinipad
//
// Created by ZeLkOvA on 12. 6. 20..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
/**
* 적용 방법
* 1. Reachability.h와 Reachability.m 파일 추가 (인터넷 접속 여부 확인용)
* 2. ASI 추가 (HTTPS 접속용)
* 3. SBJSON 추가 (JSON Parser)
*
* 추가할 framework
* Reachablility/ASI 공통 : SystemConfiguration.framework
* ASI : CFNetwork.framework, MobileCoreServices.framework, CoreGraphics.framework, libz.dylib
*/
#import <Foundation/Foundation.h>
#import "SBJSON.h"
#import "ASIFormDataRequest.h"
@interface Util : NSObject
{
}
+(UIColor*)hex2RGB:(NSString*)hexValue andAlpha:(float)alpha;
+(BOOL)checkNetworkEnable;
+(NSDictionary*)sendHTTPPost:(NSURL*)url sendData:(NSData*)data;
+(NSDictionary*)sendHTTPSPost:(NSURL *)url sendData:(NSArray *)dataArray;
+(NSDictionary*)sendHTTPGetWithParameter:(NSURL*)url;
+(NSDictionary*)sendHTTPSGetWithParameter:(NSURL*)url;
+(void)writeFileAtDir:(NSString*)dirName andFileName:(NSString*)fileName andData:(NSString*)data isOverWrite:(BOOL)isReplace;
+(NSString*)readFileAtDir:(NSString*)dirName andFileName:(NSString*)fileName;
+(void)deleteFileAtDir:(NSString*)dirName andFileName:(NSString*)fileName;
+(void)deleteAllFilesAtDir:(NSString*)dirName;
+(NSArray*)getFileList:(NSString*)dirName;
+(void)popModalsToFirstFrom:(UIViewController*)viewController;
+(int)getStringBytes:(NSString*)targetString;
+(UIImageView*)cropImage:(NSString*)targetImageName
targetX:(float)targetX targetY:(float)targetY targetWidth:(float)targetWidth targetHeight:(float)targetHeight
resultX:(float)resultX resultY:(float)resultY resultWidth:(float)resultWidth resultHeight:(float)resultHeight;
+(UIImageView*)tileImage:(NSString*)targetImageName resultX:(float)resultX resultY:(float)resultY resultWidth:(float)resultWidth resultHeight:(float)resultHeight;
+(NSInteger)findCategory:(int)_rootIndex sub:(int)_subIndex;
+(NSString*)findFloorRootCategoryName:(int)_index;
+(NSString*)findWallpaperRootCategoryName:(int)_index;
@end
| 009-20120511-zi | trunk/Zinipad/Util.h | Objective-C | gpl3 | 2,082 |
//
// ZinSampleBookPatternView.h
// Zinipad
//
// Created by ZeLkOvA on 12. 6. 7..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ZinSampleBookPatternView : UIViewController
@end
| 009-20120511-zi | trunk/Zinipad/ZinSampleBookPatternView.h | Objective-C | gpl3 | 242 |
//
// iCarousel.m
//
// Version 1.6.3 beta
//
// Created by Nick Lockwood on 01/04/2011.
// Copyright 2010 Charcoal Design
//
// Distributed under the permissive zlib License
// Get the latest version from either of these locations:
//
// http://charcoaldesign.co.uk/source/cocoa#icarousel
// https://github.com/nicklockwood/iCarousel
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
#import "iCarousel.h"
#import <QuartzCore/QuartzCore.h>
#define MIN_TOGGLE_DURATION 0.2f
#define MAX_TOGGLE_DURATION 0.4f
#define SCROLL_DURATION 1.0f
#define INSERT_DURATION 0.4f
#define DECELERATE_THRESHOLD 0.1f
#define SCROLL_SPEED_THRESHOLD 1.0f
#define SCROLL_DISTANCE_THRESHOLD 0.1f
#define DECELERATION_MULTIPLIER 30.0f
#define DEFAULT_FAN_COUNT 10
#define DEFAULT_SHAPE 20
#define DEFAULT_SHAPE_Wheel 10
@interface iCarousel ()
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) NSDictionary *itemViews;
@property (nonatomic, strong) NSMutableSet *itemViewPool;
@property (nonatomic, strong) NSMutableSet *placeholderViewPool;
@property (nonatomic, assign) NSInteger previousItemIndex;
@property (nonatomic, assign) NSInteger numberOfPlaceholdersToShow;
@property (nonatomic, assign) NSInteger numberOfVisibleItems;
@property (nonatomic, assign) CGFloat itemWidth;
@property (nonatomic, assign) CGFloat scrollOffset;
@property (nonatomic, assign) CGFloat offsetMultiplier;
@property (nonatomic, assign) CGFloat startOffset;
@property (nonatomic, assign) CGFloat endOffset;
@property (nonatomic, assign) NSTimeInterval scrollDuration;
@property (nonatomic, assign) BOOL scrolling;
@property (nonatomic, assign) NSTimeInterval startTime;
@property (nonatomic, assign) CGFloat startVelocity;
@property (nonatomic, unsafe_unretained) id timer;
@property (nonatomic, assign) BOOL decelerating;
@property (nonatomic, assign) CGFloat previousTranslation;
@property (nonatomic, assign) BOOL shouldWrap;
@property (nonatomic, assign) BOOL dragging;
@property (nonatomic, assign) BOOL didDrag;
@property (nonatomic, assign) NSTimeInterval toggleTime;
@property (nonatomic, assign) NSInteger animationDisableCount;
NSComparisonResult compareViewDepth(UIView *view1, UIView *view2, iCarousel *self);
- (void)step;
- (void)didMoveToSuperview;
- (void)layOutItemViews;
- (UIView *)loadViewAtIndex:(NSInteger)index;
- (NSInteger)clampedIndex:(NSInteger)index;
- (CGFloat)clampedOffset:(CGFloat)offset;
- (void)transformItemView:(UIView *)view atIndex:(NSInteger)index;
- (void)startAnimation;
- (void)stopAnimation;
- (void)enableAnimation;
- (void)disableAnimation;
- (void)didScroll;
@end
@implementation iCarousel
@synthesize dataSource;
@synthesize delegate;
@synthesize type;
@synthesize perspective;
@synthesize numberOfItems;
@synthesize numberOfPlaceholders;
@synthesize numberOfPlaceholdersToShow;
@synthesize numberOfVisibleItems;
@synthesize contentView;
@synthesize itemViews;
@synthesize itemViewPool;
@synthesize placeholderViewPool;
@synthesize previousItemIndex;
@synthesize itemWidth;
@synthesize scrollOffset;
@synthesize offsetMultiplier;
@synthesize startVelocity;
@synthesize timer;
@synthesize decelerating;
@synthesize scrollEnabled;
@synthesize decelerationRate;
@synthesize bounceDistance;
@synthesize bounces;
@synthesize contentOffset;
@synthesize viewpointOffset;
@synthesize startOffset;
@synthesize endOffset;
@synthesize scrollDuration;
@synthesize startTime;
@synthesize scrolling;
@synthesize previousTranslation;
@synthesize shouldWrap;
@synthesize vertical;
@synthesize dragging;
@synthesize didDrag;
@synthesize scrollSpeed;
@synthesize toggleTime;
@synthesize toggle;
@synthesize stopAtItemBoundary;
@synthesize scrollToItemBoundary;
@synthesize useDisplayLink;
@synthesize ignorePerpendicularSwipes;
@synthesize animationDisableCount;
#ifdef ICAROUSEL_IOS
@synthesize centerItemWhenSelected;
#else
CVReturn displayLinkCallback(CVDisplayLinkRef displayLink,
const CVTimeStamp *inNow,
const CVTimeStamp *inOutputTime,
CVOptionFlags flagsIn,
CVOptionFlags *flagsOut,
iCarousel *self)
{
[self performSelectorOnMainThread:@selector(step) withObject:nil waitUntilDone:NO];
return kCVReturnSuccess;
}
#endif
#pragma mark -
#pragma mark Initialisation
- (void)setUp
{
// NSLog(@"here hmhmhmhmhmhmhmhm");
// type = iCarouselTypeLinear;
// type = _type;
perspective = -1.0f/500.0f;
decelerationRate = 0.95f;
scrollEnabled = YES;
bounces = YES;
scrollOffset = 0.0f;
offsetMultiplier = 1.0f;
contentOffset = CGSizeZero;
viewpointOffset = CGSizeZero;
shouldWrap = NO;
scrollSpeed = 1.0f;
bounceDistance = 1.0f;
toggle = 0.0f;
stopAtItemBoundary = YES;
scrollToItemBoundary = YES;
useDisplayLink = YES;
ignorePerpendicularSwipes = YES;
contentView = [[UIView alloc] initWithFrame:self.bounds];
#ifdef ICAROUSEL_IOS
centerItemWhenSelected = YES;
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didPan:)];
panGesture.delegate = (id <UIGestureRecognizerDelegate>)self;
[contentView addGestureRecognizer:panGesture];
AH_RELEASE(panGesture);
#else
[contentView setWantsLayer:YES];
#endif
[self addSubview:contentView];
[self reloadData];
}
#ifndef USING_CHAMELEON
- (id)initWithCoder:(NSCoder *)aDecoder
{
if ((self = [super initWithCoder:aDecoder]))
{
[self setUp];
[self didMoveToSuperview];
}
return self;
}
#endif
- (id)initWithFrame:(NSRect)frame
{
if ((self = [super initWithFrame:frame]))
{
[self setUp];
}
return self;
}
- (void)dealloc
{
[self stopAnimation];
AH_RELEASE(contentView);
AH_RELEASE(itemViews);
AH_RELEASE(itemViewPool);
AH_RELEASE(placeholderViewPool);
AH_SUPER_DEALLOC;
}
- (void)setDataSource:(id<iCarouselDataSource>)_dataSource
{
if (dataSource != _dataSource)
{
dataSource = _dataSource;
if (dataSource)
{
[self reloadData];
}
}
}
- (void)setDelegate:(id<iCarouselDelegate>)_delegate
{
if (delegate != _delegate)
{
delegate = _delegate;
if (delegate && dataSource)
{
[self layOutItemViews];
}
}
}
- (void)setType:(iCarouselType)_type
{
if (type != _type)
{
type = _type;
[self layOutItemViews];
}
}
- (void)setVertical:(BOOL)_vertical
{
if (vertical != _vertical)
{
vertical = _vertical;
[self layOutItemViews];
}
}
- (void)setNumberOfVisibleItems:(NSInteger)_numberOfVisibleItems
{
if (numberOfVisibleItems != _numberOfVisibleItems)
{
numberOfVisibleItems = _numberOfVisibleItems;
[self layOutItemViews];
}
}
- (void)setContentOffset:(CGSize)_contentOffset
{
if (!CGSizeEqualToSize(contentOffset, _contentOffset))
{
contentOffset = _contentOffset;
[self layOutItemViews];
}
}
- (void)setViewpointOffset:(CGSize)_viewpointOffset
{
if (!CGSizeEqualToSize(viewpointOffset, _viewpointOffset))
{
viewpointOffset = _viewpointOffset;
[self layOutItemViews];
}
}
- (void)setUseDisplayLinkIfAvailable:(BOOL)_useDisplayLink
{
if (useDisplayLink != _useDisplayLink)
{
useDisplayLink = _useDisplayLink;
if (timer)
{
[self stopAnimation];
[self startAnimation];
}
}
}
- (void)enableAnimation
{
animationDisableCount --;
if (animationDisableCount == 0)
{
[CATransaction setDisableActions:NO];
}
}
- (void)disableAnimation
{
animationDisableCount ++;
if (animationDisableCount == 1)
{
[CATransaction setDisableActions:YES];
}
}
#pragma mark -
#pragma mark View management
- (NSArray *)indexesForVisibleItems
{
return [[itemViews allKeys] sortedArrayUsingSelector:@selector(compare:)];
}
- (NSArray *)visibleItemViews
{
NSArray *indexes = [self indexesForVisibleItems];
return [itemViews objectsForKeys:indexes notFoundMarker:[NSNull null]];
}
- (UIView *)itemViewAtIndex:(NSInteger)index
{
return [itemViews objectForKey:[NSNumber numberWithInteger:index]];
}
- (UIView *)currentItemView
{
return [self itemViewAtIndex:self.currentItemIndex];
}
- (NSInteger)indexOfItemView:(UIView *)view
{
NSInteger index = [[itemViews allValues] indexOfObject:view];
if (index != NSNotFound)
{
return [[[itemViews allKeys] objectAtIndex:index] integerValue];
}
return NSNotFound;
}
- (NSInteger)indexOfItemViewOrSubview:(UIView *)view
{
NSInteger index = [self indexOfItemView:view];
if (index == NSNotFound && view != nil && view != contentView)
{
return [self indexOfItemViewOrSubview:view.superview];
}
return index;
}
- (void)setItemView:(UIView *)view forIndex:(NSInteger)index
{
[(NSMutableDictionary *)itemViews setObject:view forKey:[NSNumber numberWithInteger:index]];
}
- (void)removeViewAtIndex:(NSInteger)index
{
NSMutableDictionary *newItemViews = [NSMutableDictionary dictionaryWithCapacity:[itemViews count] - 1];
for (NSNumber *number in [self indexesForVisibleItems])
{
NSInteger i = [number integerValue];
if (i < index)
{
[newItemViews setObject:[itemViews objectForKey:number] forKey:number];
}
else if (i > index)
{
[newItemViews setObject:[itemViews objectForKey:number] forKey:[NSNumber numberWithInteger:i - 1]];
}
}
self.itemViews = newItemViews;
}
- (void)insertView:(UIView *)view atIndex:(NSInteger)index
{
NSMutableDictionary *newItemViews = [NSMutableDictionary dictionaryWithCapacity:[itemViews count] + 1];
for (NSNumber *number in [self indexesForVisibleItems])
{
NSInteger i = [number integerValue];
if (i < index)
{
[newItemViews setObject:[itemViews objectForKey:number] forKey:number];
}
else
{
[newItemViews setObject:[itemViews objectForKey:number] forKey:[NSNumber numberWithInteger:i + 1]];
}
}
if (view)
{
[self setItemView:view forIndex:index];
}
self.itemViews = newItemViews;
}
#pragma mark -
#pragma mark View layout
- (CGFloat)alphaForItemWithOffset:(CGFloat)offset
{
switch (type)
{
case iCarouselTypeTimeMachine:
case iCarouselTypeInvertedTimeMachine:
{
if (type == iCarouselTypeInvertedTimeMachine)
{
offset = -offset;
}
#ifdef ICAROUSEL_MACOS
if (vertical)
{
//invert again
offset = -offset;
}
#endif
return 1.0f - fminf(fmaxf(offset, 0.0f), 1.0f);
}
case iCarouselTypeCustom:
{
if ([delegate respondsToSelector:@selector(carousel:itemAlphaForOffset:)])
{
return [delegate carousel:self itemAlphaForOffset:offset];
}
//else, fall through to default
}
default:
{
return 1.0f;
}
}
}
- (CGFloat)valueForTransformOption:(iCarouselTranformOption)option withDefault:(CGFloat)value
{
if ([delegate respondsToSelector:@selector(carousel:valueForTransformOption:withDefault:)])
{
return [delegate carousel:self valueForTransformOption:option withDefault:value];
}
return value;
}
- (CATransform3D)transformForItemView:(UIView *)view withOffset:(CGFloat)offset
{
//set up base transform
CATransform3D transform = CATransform3DIdentity;
transform.m34 = perspective;
transform = CATransform3DTranslate(transform, -viewpointOffset.width, -viewpointOffset.height, 0.0f);
//perform transform
switch (type)
{
case iCarouselTypeCustom:
{
if ([delegate respondsToSelector:@selector(carousel:itemTransformForOffset:baseTransform:)])
{
return [delegate carousel:self itemTransformForOffset:offset baseTransform:transform];
}
//deprecated code path
else if ([delegate respondsToSelector:@selector(carousel:transformForItemView:withOffset:)])
{
NSLog(@"Delegate method carousel:transformForItemView:withOffset: is deprecated, use carousel:transformForItemAtIndex:withOffset:baseTransform: instead.");
return [delegate carousel:self transformForItemView:view withOffset:offset];
}
//else, fall through to linear transform
}
case iCarouselTypeLinear:
{
if (vertical)
{
return CATransform3DTranslate(transform, 0.0f, offset * itemWidth, 0.0f);
}
else
{
return CATransform3DTranslate(transform, offset * itemWidth, 0.0f, 0.0f);
}
}
case iCarouselTypeRotary:
case iCarouselTypeInvertedRotary:
{
NSInteger count = [self valueForTransformOption:iCarouselTranformOptionCount withDefault:
MIN(numberOfVisibleItems, numberOfItems + numberOfPlaceholdersToShow)];
CGFloat arc = [self valueForTransformOption:iCarouselTranformOptionArc withDefault:M_PI * 2.0f];
CGFloat radius = [self valueForTransformOption:iCarouselTranformOptionRadius withDefault:fmaxf(itemWidth / 2.0f, itemWidth / 2.0f / tanf(arc/2.0f/count))];
CGFloat angle = [self valueForTransformOption:iCarouselTranformOptionAngle withDefault:offset / count * arc];
if (type == iCarouselTypeInvertedRotary)
{
radius = -radius;
angle = -angle;
}
if (vertical)
{
return CATransform3DTranslate(transform, 0.0f, radius * sin(angle), radius * cos(angle) - radius);
}
else
{
return CATransform3DTranslate(transform, radius * sin(angle), 0.0f, radius * cos(angle) - radius);
}
}
case iCarouselTypeCylinder:
case iCarouselTypeInvertedCylinder:
{
NSInteger count = [self valueForTransformOption:iCarouselTranformOptionCount withDefault:
MIN(numberOfVisibleItems, numberOfItems + numberOfPlaceholdersToShow+DEFAULT_SHAPE)];
CGFloat arc = [self valueForTransformOption:iCarouselTranformOptionArc withDefault:M_PI * 2.0f];
CGFloat radius = [self valueForTransformOption:iCarouselTranformOptionRadius withDefault:fmaxf(0.01f, itemWidth / 2.0f / tanf(arc/2.0f/count))];
CGFloat angle = [self valueForTransformOption:iCarouselTranformOptionAngle withDefault:offset / count * arc];
if (type == iCarouselTypeInvertedCylinder)
{
radius = -radius;
angle = -angle;
}
if (vertical)
{
transform = CATransform3DTranslate(transform, 0.0f, 0.0f, -radius);
transform = CATransform3DRotate(transform, angle, -1.0f, 0.0f, 0.0f);
return CATransform3DTranslate(transform, 0.0f, 0.0f, radius + 0.01f);
}
else
{
transform = CATransform3DTranslate(transform, 0.0f, 0.0f, -radius);
transform = CATransform3DRotate(transform, angle, 0.0f, 1.0f, 0.0f);
return CATransform3DTranslate(transform, 0.0f, 0.0f, radius + 0.01f);
}
}
case iCarouselTypeWheel:
{
CGFloat arc = [self valueForTransformOption:iCarouselTranformOptionArc withDefault: 11.0f];
CGFloat radius = [self valueForTransformOption:iCarouselTranformOptionRadius withDefault:itemWidth * 3];
CGFloat angle = [self valueForTransformOption:iCarouselTranformOptionAngle withDefault:arc / 30];
if (vertical)
{
transform = CATransform3DTranslate(transform, -radius, 0.0f, 0.0f);
transform = CATransform3DRotate(transform, angle * offset, 0.0f, 0.0f, 1.0f);
return CATransform3DTranslate(transform, radius, 0.0f, offset * 0.01f);
}
else
{
transform = CATransform3DTranslate(transform, 0.0f, radius, 0.0f);
transform = CATransform3DRotate(transform, angle * offset, 0.0f, 0.0f, 1.0f);
return CATransform3DTranslate(transform, 0.0f, -radius, offset * 0.01f);
}
}
case iCarouselTypeInvertedWheel:
{
// NSInteger count = [self valueForTransformOption:iCarouselTranformOptionCount withDefault:
// MIN(numberOfVisibleItems, numberOfItems + numberOfPlaceholdersToShow)];
CGFloat arc = [self valueForTransformOption:iCarouselTranformOptionArc withDefault: 12.0f];
CGFloat radius = [self valueForTransformOption:iCarouselTranformOptionRadius withDefault:itemWidth * 3];
CGFloat angle = [self valueForTransformOption:iCarouselTranformOptionAngle withDefault:arc / 30];
if (type == iCarouselTypeInvertedWheel)
{
radius = -radius;
angle = -angle;
}
CGFloat tilt = [self valueForTransformOption:iCarouselTranformOptionTilt withDefault:0.7f];
CGFloat spacing = [self valueForTransformOption:iCarouselTranformOptionSpacing withDefault:0.25f]; // should be ~ 1/scrollSpeed;
CGFloat clampedOffset = fmaxf(-1.0f, fminf(1.0f, offset));
CGFloat x = (clampedOffset * 0.5f * tilt + offset * spacing) * itemWidth;
CGFloat z = fabsf(clampedOffset) * -itemWidth * 3.0f;
if (vertical)
{
transform = CATransform3DTranslate(transform, 0.0f, x, z+10);
transform = CATransform3DTranslate(transform, -radius, 0.0f, 0.0f);
transform = CATransform3DRotate(transform, angle * offset, 0.0f, 0.0f, 1.0f);
return CATransform3DTranslate(transform, radius, 0.0f, offset * 0.01f);
}
else
{
transform = CATransform3DTranslate(transform, 0.0f, radius, 0.0f);
transform = CATransform3DRotate(transform, angle * offset, 0.0f, 0.0f, 1.0f);
return CATransform3DTranslate(transform, 0.0f, -radius, offset * 0.01f);
}
}
case iCarouselTypeCoverFlow:
case iCarouselTypeCoverFlow2:
{
CGFloat tilt = [self valueForTransformOption:iCarouselTranformOptionTilt withDefault:1.0f];
CGFloat spacing = [self valueForTransformOption:iCarouselTranformOptionSpacing withDefault:0.25f]; // should be ~ 1/scrollSpeed;
CGFloat clampedOffset = fmaxf(-1.0f, fminf(1.0f, offset));
if (type == iCarouselTypeCoverFlow2)
{
if (toggle >= 0.0f)
{
if (offset <= -0.5f)
{
clampedOffset = -1.0f;
}
else if (offset <= 0.5f)
{
clampedOffset = -toggle;
}
else if (offset <= 1.5f)
{
clampedOffset = 1.0f - toggle;
}
}
else
{
if (offset > 0.5f)
{
clampedOffset = 1.0f;
}
else if (offset > -0.5f)
{
clampedOffset = -toggle;
}
else if (offset > -1.5f)
{
clampedOffset = - 1.0f - toggle;
}
}
}
CGFloat x = (clampedOffset * 0.5f * tilt + offset * spacing) * itemWidth;
CGFloat z = fabsf(clampedOffset) * -itemWidth * 0.5f;
if (vertical)
{
transform = CATransform3DTranslate(transform, 0.0f, x, z);
return CATransform3DRotate(transform, -clampedOffset * M_PI_2 * tilt, -1.0f, 0.0f, 0.0f);
}
else
{
transform = CATransform3DTranslate(transform, x, 0.0f, z);
return CATransform3DRotate(transform, -clampedOffset * M_PI_2 * tilt, 0.0f, 1.0f, 0.0f);
}
}
case iCarouselTypeTimeMachine:
case iCarouselTypeInvertedTimeMachine:
{
CGFloat tilt = [self valueForTransformOption:iCarouselTranformOptionTilt withDefault:0.3f];
CGFloat spacing = [self valueForTransformOption:iCarouselTranformOptionSpacing withDefault:1.0f];
if (type == iCarouselTypeInvertedTimeMachine)
{
tilt = -tilt;
offset = -offset;
}
if (vertical)
{
#ifdef ICAROUSEL_MACOS
//invert again
tilt = -tilt;
offset = -offset;
#endif
return CATransform3DTranslate(transform, 0.0f, offset * itemWidth * tilt, offset * itemWidth * spacing);
}
else
{
return CATransform3DTranslate(transform, offset * itemWidth * tilt, 0.0f, offset * itemWidth * spacing);
}
}
default:
{
//shouldn't ever happen
return CATransform3DIdentity;
}
}
}
#ifdef ICAROUSEL_IOS
NSComparisonResult compareViewDepth(UIView *view1, UIView *view2, iCarousel *self)
{
CATransform3D t1 = view1.superview.layer.transform;
CATransform3D t2 = view2.superview.layer.transform;
CGFloat z1 = t1.m13 + t1.m23 + t1.m33 + t1.m43;
CGFloat z2 = t2.m13 + t2.m23 + t2.m33 + t2.m43;
CGFloat difference = z1 - z2;
if (difference == 0.0f)
{
CATransform3D t3 = [self currentItemView].superview.layer.transform;
CGFloat x1 = t1.m11 + t1.m21 + t1.m31 + t1.m41;
CGFloat x2 = t2.m11 + t2.m21 + t2.m31 + t2.m41;
CGFloat x3 = t3.m11 + t3.m21 + t3.m31 + t3.m41;
difference = fabsf(x2 - x3) - fabsf(x1 - x3);
}
return (difference < 0.0f)? NSOrderedAscending: NSOrderedDescending;
}
- (void)depthSortViews
{
for (UIView *view in [[itemViews allValues] sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))compareViewDepth context:(__AH_BRIDGE void *)self])
{
[contentView addSubview:view.superview];
}
}
#else
- (void)depthSortViews
{
//does nothing on Mac OS
}
#endif
- (CGFloat)offsetForItemAtIndex:(NSInteger)index
{
//calculate relative position
CGFloat itemOffset = itemWidth? (scrollOffset / itemWidth): 0.0f;
CGFloat offset = index - itemOffset;
if (shouldWrap)
{
if (offset > numberOfItems/2)
{
offset -= numberOfItems;
}
else if (offset < -numberOfItems/2)
{
offset += numberOfItems;
}
}
//handle special case for one item
if (numberOfItems + numberOfPlaceholdersToShow == 1)
{
offset = 0.0f;
}
#ifdef ICAROUSEL_MACOS
if (vertical)
{
//invert transform
offset = -offset;
}
#endif
return offset;
}
- (UIView *)containView:(UIView *)view
{
UIView *container = AH_AUTORELEASE([[UIView alloc] initWithFrame:view.frame]);
#ifdef ICAROUSEL_IOS
//add tap gesture recogniser
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTap:)];
tapGesture.delegate = (id <UIGestureRecognizerDelegate>)self;
[container addGestureRecognizer:tapGesture];
AH_RELEASE(tapGesture);
#endif
[container addSubview:view];
return container;
}
- (void)transformItemView:(UIView *)view atIndex:(NSInteger)index
{
view.superview.bounds = view.bounds;
//calculate offset
CGFloat offset = [self offsetForItemAtIndex:index];
#ifdef ICAROUSEL_IOS
////////////////////////////////////////////////////
// 위치 잡기
//////////////////////////////////////////////////////
//center view
view.center = CGPointMake(view.bounds.size.width/2.0f, view.bounds.size.height/2.0f);
view.superview.center = CGPointMake(self.bounds.size.width/2.0f + contentOffset.width,
self.bounds.size.height/2.0f + contentOffset.height);
//update alpha
view.superview.alpha = [self alphaForItemWithOffset:offset];
#else
//center view
[view setFrameOrigin:NSMakePoint(0.0f, 0.0f)];
[view.superview setFrameOrigin:NSMakePoint(self.bounds.size.width/2.0f + contentOffset.width,
self.bounds.size.height/2.0f + contentOffset.height)];
view.superview.layer.anchorPoint = CGPointMake(0.5f, 0.5f);
//update alpha
[view.superview setAlphaValue:[self alphaForItemWithOffset:offset]];
#endif
//update backface visibility
view.superview.layer.doubleSided = view.layer.doubleSided;
//special-case logic for iCarouselTypeCoverFlow2
CGFloat clampedOffset = fmaxf(-1.0f, fminf(1.0f, offset));
if (decelerating || (scrolling && !didDrag) || (scrollOffset - [self clampedOffset:scrollOffset]) != 0.0f)
{
if (offset > 0)
{
toggle = (offset <= 0.5f)? -clampedOffset: (1.0f - clampedOffset);
}
else
{
toggle = (offset > -0.5f)? -clampedOffset: (- 1.0f - clampedOffset);
}
}
//calculate transform
CATransform3D transform = [self transformForItemView:view withOffset:offset];
//transform view
view.superview.layer.transform = transform;
}
//for iOS
- (void)layoutSubviews
{
contentView.frame = self.bounds;
[self layOutItemViews];
}
//for Mac OS
- (void)resizeSubviewsWithOldSize:(NSSize)oldSize
{
[self disableAnimation];
[self layoutSubviews];
[self enableAnimation];
}
- (void)transformItemViews
{
for (NSNumber *number in itemViews)
{
NSInteger index = [number integerValue];
UIView *view = [itemViews objectForKey:number];
[self transformItemView:view atIndex:index];
#ifdef ICAROUSEL_IOS
view.userInteractionEnabled = (!centerItemWhenSelected || index == self.currentItemIndex);
#endif
}
}
- (void)updateItemWidth
{
if ([delegate respondsToSelector:@selector(carouselItemWidth:)])
{
itemWidth = [delegate carouselItemWidth:self];
}
else if (numberOfItems > 0)
{
if ([itemViews count] == 0)
{
[self loadViewAtIndex:0];
}
UIView *itemView = [[itemViews allValues] lastObject];
itemWidth = vertical? itemView.bounds.size.height: itemView.bounds.size.width;
}
else if (numberOfPlaceholders > 0)
{
if ([itemViews count] == 0)
{
[self loadViewAtIndex:-1];
}
UIView *itemView = [[itemViews allValues] lastObject];
itemWidth = vertical? itemView.bounds.size.height: itemView.bounds.size.width;
}
}
- (void)layOutItemViews
{
//bail out if not set up yet
if (!dataSource || !contentView)
{
return;
}
//record current item width
CGFloat prevItemWidth = itemWidth;
//update wrap
if ([delegate respondsToSelector:@selector(carouselShouldWrap:)])
{
shouldWrap = [delegate carouselShouldWrap:self];
}
else
{
switch (type)
{
case iCarouselTypeRotary:
case iCarouselTypeInvertedRotary:
case iCarouselTypeCylinder:
case iCarouselTypeInvertedCylinder:
case iCarouselTypeWheel:
case iCarouselTypeInvertedWheel:
{
shouldWrap = YES;
break;
}
default:
{
shouldWrap = NO;
break;
}
}
}
//no placeholders on wrapped carousels
numberOfPlaceholdersToShow = shouldWrap? 0: numberOfPlaceholders;
//set item width
[self updateItemWidth];
//update offset multiplier
if ([delegate respondsToSelector:@selector(carouselOffsetMultiplier:)])
{
offsetMultiplier = [delegate carouselOffsetMultiplier:self];
}
else
{
switch (type)
{
case iCarouselTypeCoverFlow:
case iCarouselTypeCoverFlow2:
{
offsetMultiplier = 2.0f;
break;
}
default:
{
offsetMultiplier = 1.0f;
break;
}
}
}
//adjust scroll offset
if (prevItemWidth)
{
scrollOffset = itemWidth? (scrollOffset / prevItemWidth * itemWidth): 0.0f;
}
else
{
//prevent false index changed event
previousItemIndex = self.currentItemIndex;
}
//align
if (!scrolling && !decelerating)
{
if (scrollToItemBoundary)
{
[self scrollToItemAtIndex:self.currentItemIndex animated:YES];
}
else
{
scrollOffset = [self clampedOffset:scrollOffset];
}
}
//update views
[self didScroll];
}
#pragma mark -
#pragma mark View queing
- (void)queueItemView:(UIView *)view
{
if (view)
{
[itemViewPool addObject:view];
}
}
- (void)queuePlaceholderView:(UIView *)view
{
if (view)
{
[placeholderViewPool addObject:view];
}
}
- (UIView *)dequeueItemView
{
UIView *view = AH_RETAIN([itemViewPool anyObject]);
if (view)
{
[itemViewPool removeObject:view];
}
return AH_AUTORELEASE(view);
}
- (UIView *)dequeuePlaceholderView
{
UIView *view = AH_RETAIN([placeholderViewPool anyObject]);
if (view)
{
[placeholderViewPool removeObject:view];
}
return AH_AUTORELEASE(view);
}
#pragma mark -
#pragma mark View loading
- (UIView *)loadViewAtIndex:(NSInteger)index withContainerView:(UIView *)containerView
{
[self disableAnimation];
// NSLog(@"aaaaaaaaaaa");
UIView *view = nil;
if (index < 0)
{
if ([dataSource respondsToSelector:@selector(carousel:placeholderViewAtIndex:reusingView:)])
{
view = [dataSource carousel:self placeholderViewAtIndex:(int)ceilf((CGFloat)numberOfPlaceholdersToShow/2.0f) + index reusingView:[self dequeuePlaceholderView]];
}
//deprecated code path
else if ([dataSource respondsToSelector:@selector(carousel:placeholderViewAtIndex:)])
{
NSLog(@"DataSource method carousel:placeholderViewAtIndex: is deprecated, use carousel:placeholderViewAtIndex:reusingView: instead.");
view = [dataSource carousel:self placeholderViewAtIndex:(int)ceilf((CGFloat)numberOfPlaceholdersToShow/2.0f) + index];
}
}
else if (index >= numberOfItems)
{
if ([dataSource respondsToSelector:@selector(carousel:placeholderViewAtIndex:reusingView:)])
{
view = [dataSource carousel:self placeholderViewAtIndex:numberOfPlaceholdersToShow/2.0f + index - numberOfItems reusingView:[self dequeuePlaceholderView]];
}
//deprecated code path
else if ([dataSource respondsToSelector:@selector(carousel:placeholderViewAtIndex:)])
{
NSLog(@"DataSource method carousel:placeholderViewAtIndex: is deprecated, use carousel:placeholderViewAtIndex:reusingView: instead.");
view = [dataSource carousel:self placeholderViewAtIndex:numberOfPlaceholdersToShow/2.0f + index - numberOfItems];
}
}
else if ([dataSource respondsToSelector:@selector(carousel:viewForItemAtIndex:reusingView:)])
{
view = [dataSource carousel:self viewForItemAtIndex:index reusingView:[self dequeueItemView]];
}
//deprecated code path
else
{
NSLog(@"DataSource method carousel:viewForItemAtIndex: is deprecated, use carousel:viewForItemAtIndex:reusingView: instead.");
view = [dataSource carousel:self viewForItemAtIndex:index];
}
if (view == nil)
{
view = AH_AUTORELEASE([[UIView alloc] init]);
}
[self setItemView:view forIndex:index];
if (containerView)
{
UIView *oldItemView = [containerView.subviews lastObject];
if (index < 0 || index >= numberOfItems)
{
[self queuePlaceholderView:view];
}
else
{
[self queueItemView:view];
}
[oldItemView removeFromSuperview];
containerView.frame = view.frame;
[containerView addSubview:view];
}
else
{
[contentView addSubview:[self containView:view]];
}
[self transformItemView:view atIndex:index];
[self enableAnimation];
return view;
}
- (UIView *)loadViewAtIndex:(NSInteger)index
{
return [self loadViewAtIndex:index withContainerView:nil];
}
- (void)loadUnloadViews
{
//calculate visible view indices
NSMutableSet *visibleIndices = [NSMutableSet setWithCapacity:numberOfVisibleItems];
NSInteger min = -(int)ceilf((CGFloat)numberOfPlaceholdersToShow/2.0f);
NSInteger max = numberOfItems - 1 + numberOfPlaceholdersToShow/2;
NSInteger count = MIN(numberOfVisibleItems, numberOfItems + numberOfPlaceholdersToShow);
NSInteger offset = self.currentItemIndex - numberOfVisibleItems/2;
if (!shouldWrap)
{
offset = MAX(min, MIN(max - count + 1, offset));
}
for (NSInteger i = 0; i < count; i++)
{
NSInteger index = i + offset;
if (shouldWrap)
{
index = [self clampedIndex:index];
}
[visibleIndices addObject:[NSNumber numberWithInteger:index]];
}
//remove offscreen views
for (NSNumber *number in [itemViews allKeys])
{
if (![visibleIndices containsObject:number])
{
UIView *view = [itemViews objectForKey:number];
if ([number integerValue] < 0 || [number integerValue] >= numberOfItems)
{
[self queuePlaceholderView:view];
}
else
{
[self queueItemView:view];
}
[view.superview removeFromSuperview];
[(NSMutableDictionary *)itemViews removeObjectForKey:number];
}
}
//add onscreen views
for (NSNumber *number in visibleIndices)
{
UIView *view = [itemViews objectForKey:number];
if (view == nil)
{
[self loadViewAtIndex:[number integerValue]];
}
}
}
- (void)reloadData
{
//remove old views
for (UIView *view in [self.itemViews allValues])
{
[view.superview removeFromSuperview];
}
//bail out if not set up yet
if (!dataSource || !contentView)
{
return;
}
//get number of items and placeholders
numberOfItems = [dataSource numberOfItemsInCarousel:self];
if ([dataSource respondsToSelector:@selector(numberOfPlaceholdersInCarousel:)])
{
numberOfPlaceholders = [dataSource numberOfPlaceholdersInCarousel:self];
}
//get number of visible items
numberOfVisibleItems = numberOfItems + numberOfPlaceholders;
if ([dataSource respondsToSelector:@selector(numberOfVisibleItemsInCarousel:)])
{
numberOfVisibleItems = [dataSource numberOfVisibleItemsInCarousel:self];
}
//reset view pools
self.itemViews = [NSMutableDictionary dictionaryWithCapacity:numberOfVisibleItems];
self.itemViewPool = [NSMutableSet setWithCapacity:numberOfVisibleItems];
self.placeholderViewPool = [NSMutableSet setWithCapacity:numberOfVisibleItems];
//layout views
[self disableAnimation];
[self layOutItemViews];
[self depthSortViews];
[self performSelector:@selector(depthSortViews) withObject:nil afterDelay:0.0f];
[self enableAnimation];
if (numberOfItems > 0 && scrollOffset < 0.0f)
{
[self scrollToItemAtIndex:0 animated:(numberOfPlaceholders > 0)];
}
}
#pragma mark -
#pragma mark Scrolling
- (NSInteger)clampedIndex:(NSInteger)index
{
if (shouldWrap)
{
if (numberOfItems == 0)
{
return 0;
}
return index - floorf((CGFloat)index / (CGFloat)numberOfItems) * numberOfItems;
}
else
{
return MIN(MAX(index, 0), numberOfItems - 1);
}
}
- (CGFloat)clampedOffset:(CGFloat)offset
{
if (shouldWrap)
{
if (numberOfItems == 0)
{
return 0.0f;
}
CGFloat contentWidth = numberOfItems * itemWidth;
CGFloat clampedOffset = contentWidth? (offset - floorf(offset / contentWidth) * contentWidth): 0.0f;
return clampedOffset;
}
else
{
return fminf(fmaxf(0.0f, offset), numberOfItems * itemWidth - itemWidth);
}
}
- (NSInteger)currentItemIndex
{
return itemWidth? [self clampedIndex:roundf(scrollOffset / itemWidth)]: 0.0f;
}
- (NSInteger)minScrollDistanceFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex
{
NSInteger directDistance = toIndex - fromIndex;
if (shouldWrap)
{
NSInteger wrappedDistance = MIN(toIndex, fromIndex) + numberOfItems - MAX(toIndex, fromIndex);
if (fromIndex < toIndex)
{
wrappedDistance = -wrappedDistance;
}
return (ABS(directDistance) <= ABS(wrappedDistance))? directDistance: wrappedDistance;
}
return directDistance;
}
- (CGFloat)minScrollDistanceFromOffset:(CGFloat)fromOffset toOffset:(CGFloat)toOffset
{
CGFloat directDistance = toOffset - fromOffset;
if (shouldWrap)
{
CGFloat wrappedDistance = fminf(toOffset, fromOffset) + numberOfItems*itemWidth - fmaxf(toOffset, fromOffset);
if (fromOffset < toOffset)
{
wrappedDistance = -wrappedDistance;
}
return (fabsf(directDistance) <= fabsf(wrappedDistance))? directDistance: wrappedDistance;
}
return directDistance;
}
- (void)scrollByNumberOfItems:(NSInteger)itemCount duration:(NSTimeInterval)duration
{
if (duration > 0.0)
{
scrolling = YES;
startTime = CACurrentMediaTime();
startOffset = scrollOffset;
scrollDuration = duration;
previousItemIndex = roundf(scrollOffset/itemWidth);
if (itemCount > 0)
{
endOffset = itemWidth? ((floorf(startOffset / itemWidth) + itemCount) * itemWidth): 0.0f;
}
else if (itemCount < 0)
{
endOffset = itemWidth? ((ceilf(startOffset / itemWidth) + itemCount) * itemWidth): 0.0f;
}
else
{
endOffset = itemWidth? (roundf(startOffset / itemWidth) * itemWidth): 0.0f;
}
if (!shouldWrap)
{
endOffset = [self clampedOffset:endOffset];
}
if ([delegate respondsToSelector:@selector(carouselWillBeginScrollingAnimation:)])
{
[delegate carouselWillBeginScrollingAnimation:self];
}
[self startAnimation];
}
else
{
scrolling = NO;
decelerating = NO;
[self disableAnimation];
scrollOffset = itemWidth * [self clampedIndex:previousItemIndex + itemCount];
previousItemIndex = previousItemIndex + itemCount;
[self didScroll];
[self depthSortViews];
[self enableAnimation];
}
}
- (void)scrollToItemAtIndex:(NSInteger)index duration:(NSTimeInterval)duration
{
[self scrollByNumberOfItems:[self minScrollDistanceFromIndex:roundf(scrollOffset/itemWidth) toIndex:index] duration:duration];
}
- (void)scrollToItemAtIndex:(NSInteger)index animated:(BOOL)animated
{
[self scrollToItemAtIndex:index duration:animated? SCROLL_DURATION: 0];
}
- (void)removeItemAtIndex:(NSInteger)index animated:(BOOL)animated
{
index = [self clampedIndex:index];
UIView *itemView = [self itemViewAtIndex:index];
if (animated)
{
#ifdef ICAROUSEL_IOS
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.1];
[UIView setAnimationDelegate:itemView.superview];
[UIView setAnimationDidStopSelector:@selector(removeFromSuperview)];
[self performSelector:@selector(queueItemView:) withObject:itemView afterDelay:0.1];
itemView.superview.layer.opacity = 0.0f;
[UIView commitAnimations];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:INSERT_DURATION];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(depthSortViews)];
[self removeViewAtIndex:index];
numberOfItems --;
if (![dataSource respondsToSelector:@selector(numberOfVisibleItemsInCarousel:)])
{
numberOfVisibleItems --;
}
scrollOffset = itemWidth * self.currentItemIndex;
[self didScroll];
[UIView commitAnimations];
#else
[CATransaction begin];
[CATransaction setAnimationDuration:0.1];
[CATransaction setCompletionBlock:^{
[self queueItemView:itemView];
[itemView.superview removeFromSuperview];
}];
itemView.superview.layer.opacity = 0.0f;
[CATransaction commit];
[CATransaction begin];
[CATransaction setAnimationDuration:INSERT_DURATION];
[CATransaction setCompletionBlock:^{
[self depthSortViews];
}];
[self removeViewAtIndex:index];
numberOfItems --;
scrollOffset = itemWidth * self.currentItemIndex;
[self didScroll];
[CATransaction commit];
#endif
}
else
{
[self disableAnimation];
[self queueItemView:itemView];
[itemView.superview removeFromSuperview];
[self removeViewAtIndex:index];
numberOfItems --;
scrollOffset = itemWidth * self.currentItemIndex;
[self didScroll];
[self depthSortViews];
[self enableAnimation];
}
}
- (void)fadeInItemView:(UIView *)itemView
{
NSInteger index = [self indexOfItemView:itemView];
CGFloat offset = [self offsetForItemAtIndex:index];
CGFloat alpha = [self alphaForItemWithOffset:offset];
#ifdef ICAROUSEL_IOS
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.1f];
itemView.superview.layer.opacity = alpha;
[UIView commitAnimations];
#else
[CATransaction begin];
[CATransaction setAnimationDuration:0.1f];
itemView.superview.layer.opacity = alpha;
[CATransaction commit];
#endif
}
- (void)insertItemAtIndex:(NSInteger)index animated:(BOOL)animated
{
numberOfItems ++;
if (![dataSource respondsToSelector:@selector(numberOfVisibleItemsInCarousel:)])
{
numberOfVisibleItems ++;
}
index = [self clampedIndex:index];
[self insertView:nil atIndex:index];
UIView *itemView = [self loadViewAtIndex:index];
itemView.superview.layer.opacity = 0.0f;
if (itemWidth == 0)
{
[self updateItemWidth];
}
if (animated)
{
#ifdef ICAROUSEL_IOS
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:INSERT_DURATION];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(loadUnloadViews)];
[self transformItemViews];
[UIView commitAnimations];
#else
[CATransaction begin];
[CATransaction setAnimationDuration:INSERT_DURATION];
[CATransaction setCompletionBlock:^{
[self loadUnloadViews];
}];
[self transformItemViews];
[CATransaction commit];
#endif
[self performSelector:@selector(fadeInItemView:) withObject:itemView afterDelay:INSERT_DURATION - 0.1f];
}
else
{
[self disableAnimation];
[self transformItemViews];
[self enableAnimation];
itemView.superview.layer.opacity = 1.0f;
}
if (scrollOffset < 0.0f)
{
[self scrollToItemAtIndex:0 animated:(animated && numberOfPlaceholders)];
}
}
- (void)reloadItemAtIndex:(NSInteger)index animated:(BOOL)animated
{
//get container view
UIView *containerView = [[self itemViewAtIndex:index] superview];
if (animated)
{
//fade transition
CATransition *transition = [CATransition animation];
transition.duration = INSERT_DURATION;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade;
[containerView.layer addAnimation:transition forKey:nil];
}
//reload view
[self loadViewAtIndex:index withContainerView:containerView];
}
#pragma mark -
#pragma mark Animation
- (void)startAnimation
{
if (!timer)
{
if (useDisplayLink)
{
#ifdef ICAROUSEL_IOS
#ifndef USING_CHAMELEON
//support for Chameleon
timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(step)];
[timer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
#endif
#else
CVDisplayLinkCreateWithActiveCGDisplays((void *)&timer);
CVDisplayLinkSetOutputCallback((__AH_BRIDGE CVDisplayLinkRef)timer, (CVDisplayLinkOutputCallback)&displayLinkCallback, (__AH_BRIDGE void *)self);
CVDisplayLinkStart((__AH_BRIDGE CVDisplayLinkRef)timer);
#endif
}
//use timer if display link
//disabled or unavailable
if (!timer)
{
timer = [NSTimer timerWithTimeInterval:1.0/60.0
target:self
selector:@selector(step)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
}
}
- (void)stopAnimation
{
// NSLog(@"event stop");
// NSLog(@"%d",self.currentItemIndex);
// [delegate carouselCurrnetImgIndex:self.currentItemIndex];
#ifdef ICAROUSEL_IOS
[timer invalidate];
#else
if ([timer isKindOfClass:[NSTimer class]])
{
[timer invalidate];
}
else
{
CVDisplayLinkStop((__AH_BRIDGE CVDisplayLinkRef)timer);
CVDisplayLinkRelease((__AH_BRIDGE CVDisplayLinkRef)timer);
}
#endif
timer = nil;
[delegate carouselCurrnetImgIndex:self.currentItemIndex];
// [delegate carouselCurrnetImgView:self.currentItemView];
}
- (CGFloat)decelerationDistance
{
CGFloat acceleration = -startVelocity * DECELERATION_MULTIPLIER * (1.0f - decelerationRate);
return -powf(startVelocity, 2.0f) / (2.0f * acceleration);
}
- (BOOL)shouldDecelerate
{
return (fabsf(startVelocity) > itemWidth * SCROLL_SPEED_THRESHOLD) &&
(fabsf([self decelerationDistance]) > itemWidth * DECELERATE_THRESHOLD);
}
- (BOOL)shouldScroll
{
return (fabsf(startVelocity) > itemWidth * SCROLL_SPEED_THRESHOLD) &&
(fabsf(scrollOffset/itemWidth - self.currentItemIndex) > SCROLL_DISTANCE_THRESHOLD);
}
- (void)startDecelerating
{
CGFloat distance = [self decelerationDistance];
startOffset = scrollOffset;
endOffset = startOffset + distance;
if (stopAtItemBoundary)
{
if (distance > 0.0f)
{
endOffset = itemWidth? (ceilf(endOffset / itemWidth) * itemWidth): 0.0f;
}
else
{
endOffset = itemWidth? (floorf(endOffset / itemWidth) * itemWidth): 0.0f;
}
}
if (!shouldWrap)
{
if (bounces)
{
endOffset = fmaxf(itemWidth * -bounceDistance,
fminf((numberOfItems - 1.0f + bounceDistance) * itemWidth, endOffset));
}
else
{
endOffset = [self clampedOffset:endOffset];
}
}
distance = endOffset - startOffset;
startTime = CACurrentMediaTime();
scrollDuration = fabsf(distance) / fabsf(0.5f * startVelocity);
if (distance != 0.0f)
{
decelerating = YES;
[self startAnimation];
}
}
- (CGFloat)easeInOut:(CGFloat)time
{
return (time < 0.5f)? 0.5f * powf(time * 2.0f, 3.0f): 0.5f * powf(time * 2.0f - 2.0f, 3.0f) + 1.0f;
}
- (void)step
{
[self disableAnimation];
NSTimeInterval currentTime = CACurrentMediaTime();
if (toggle != 0.0f)
{
CGFloat toggleDuration = fminf(1.0f, fmaxf(0.0f, itemWidth / fabsf(startVelocity)));
toggleDuration = MIN_TOGGLE_DURATION + (MAX_TOGGLE_DURATION - MIN_TOGGLE_DURATION) * toggleDuration;
NSTimeInterval time = fminf(1.0f, (currentTime - toggleTime) / toggleDuration);
CGFloat delta = [self easeInOut:time];
toggle = (toggle < 0.0f)? (delta - 1.0f): (1.0f - delta);
[self didScroll];
}
if (scrolling)
{
NSTimeInterval time = fminf(1.0f, (currentTime - startTime) / scrollDuration);
CGFloat delta = [self easeInOut:time];
scrollOffset = startOffset + (endOffset - startOffset) * delta;
[self didScroll];
if (time == 1.0f)
{
scrolling = NO;
[self depthSortViews];
if ([delegate respondsToSelector:@selector(carouselDidEndScrollingAnimation:)])
{
[delegate carouselDidEndScrollingAnimation:self];
}
}
}
else if (decelerating)
{
CGFloat time = fminf(scrollDuration, currentTime - startTime);
CGFloat acceleration = -startVelocity/scrollDuration;
CGFloat distance = startVelocity * time + 0.5f * acceleration * powf(time, 2.0f);
scrollOffset = startOffset + distance;
[self didScroll];
if (time == (CGFloat)scrollDuration)
{
decelerating = NO;
if ([delegate respondsToSelector:@selector(carouselDidEndDecelerating:)])
{
[delegate carouselDidEndDecelerating:self];
}
if (scrollToItemBoundary || (scrollOffset - [self clampedOffset:scrollOffset]) != 0.0f)
{
if (fabsf(scrollOffset/itemWidth - self.currentItemIndex) < 0.01f)
{
//call scroll to trigger events for legacy support reasons
//even though technically we don't need to scroll at all
[self scrollToItemAtIndex:self.currentItemIndex duration:0.01];
}
else
{
[self scrollToItemAtIndex:self.currentItemIndex animated:YES];
}
}
else
{
CGFloat difference = (CGFloat)self.currentItemIndex - scrollOffset/itemWidth;
if (difference > 0.5)
{
difference = difference - 1.0f;
}
else if (difference < -0.5)
{
difference = 1.0 + difference;
}
toggleTime = currentTime - MAX_TOGGLE_DURATION * fabsf(difference);
toggle = fmaxf(-1.0f, fminf(1.0f, -difference));
}
}
}
else if (toggle == 0.0f)
{
[self stopAnimation];
}
[self enableAnimation];
}
//for iOS
- (void)didMoveToSuperview
{
if (self.superview)
{
[self reloadData];
[self startAnimation];
}
else
{
[self stopAnimation];
}
}
//for Mac OS
- (void)viewDidMoveToSuperview
{
[self didMoveToSuperview];
}
- (void)didScroll
{
if (shouldWrap || !bounces)
{
scrollOffset = [self clampedOffset:scrollOffset];
}
else
{
CGFloat min = -bounceDistance * itemWidth;
CGFloat max = (fmaxf(numberOfItems - 1, 0.0f) + bounceDistance) * itemWidth;
if (scrollOffset < min)
{
scrollOffset = min;
startVelocity = 0.0f;
}
else if (scrollOffset > max)
{
scrollOffset = max;
startVelocity = 0.0f;
}
}
//check if index has changed
NSInteger currentIndex = roundf(scrollOffset/itemWidth);
NSInteger difference = [self minScrollDistanceFromIndex:previousItemIndex toIndex:currentIndex];
if (difference)
{
toggleTime = CACurrentMediaTime();
toggle = fmaxf(-1.0f, fminf(1.0f, -(CGFloat)difference));
#ifdef ICAROUSEL_MACOS
if (vertical)
{
//invert toggle
toggle = -toggle;
}
#endif
[self startAnimation];
}
[self loadUnloadViews];
[self transformItemViews];
if ([delegate respondsToSelector:@selector(carouselDidScroll:)])
{
[delegate carouselDidScroll:self];
}
//notify delegate of change index
if ([self clampedIndex:previousItemIndex] != self.currentItemIndex &&
[delegate respondsToSelector:@selector(carouselCurrentItemIndexUpdated:)])
{
[delegate carouselCurrentItemIndexUpdated:self];
}
//update previous index
previousItemIndex = currentIndex;
}
#ifdef ICAROUSEL_IOS
#pragma mark -
#pragma mark Gestures and taps
- (NSInteger)viewOrSuperviewIndex:(UIView *)view
{
if (view == nil || view == contentView)
{
return NSNotFound;
}
NSInteger index = [self indexOfItemView:view];
if (index == NSNotFound)
{
return [self viewOrSuperviewIndex:view.superview];
}
return index;
}
- (BOOL)viewOrSuperview:(UIView *)view isKindOfClass:(Class)class
{
if (view == nil || view == contentView)
{
return NO;
}
else if ([view isKindOfClass:class])
{
return YES;
}
return [self viewOrSuperview:view.superview isKindOfClass:class];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gesture shouldReceiveTouch:(UITouch *)touch
{
if ([gesture isKindOfClass:[UITapGestureRecognizer class]])
{
//handle tap
NSInteger index = [self viewOrSuperviewIndex:touch.view];
if (index == NSNotFound && centerItemWhenSelected)
{
//view is a container view
index = [self viewOrSuperviewIndex:[touch.view.subviews lastObject]];
}
if (index != NSNotFound)
{
if ([delegate respondsToSelector:@selector(carousel:shouldSelectItemAtIndex:)])
{
if (![delegate carousel:self shouldSelectItemAtIndex:index])
{
return NO;
}
}
if ([self viewOrSuperview:touch.view isKindOfClass:[UIControl class]] ||
[self viewOrSuperview:touch.view isKindOfClass:[UITableViewCell class]])
{
return NO;
}
}
}
else if ([gesture isKindOfClass:[UIPanGestureRecognizer class]])
{
if ([self viewOrSuperview:touch.view isKindOfClass:[UISlider class]] ||
[self viewOrSuperview:touch.view isKindOfClass:[UISwitch class]] ||
!scrollEnabled)
{
return NO;
}
}
return YES;
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gesture
{
if ([gesture isKindOfClass:[UIPanGestureRecognizer class]])
{
//ignore vertical swipes
UIPanGestureRecognizer *panGesture = (UIPanGestureRecognizer *)gesture;
CGPoint translation = [panGesture translationInView:self];
if (ignorePerpendicularSwipes)
{
if (vertical)
{
return fabsf(translation.x) <= fabsf(translation.y);
}
else
{
return fabsf(translation.x) >= fabsf(translation.y);
}
}
}
return YES;
}
- (void)didTap:(UITapGestureRecognizer *)tapGesture
{
NSInteger index = [self indexOfItemView:[tapGesture.view.subviews lastObject]];
if (centerItemWhenSelected && index != self.currentItemIndex)
{
[self scrollToItemAtIndex:index animated:YES];
}
if(centerItemWhenSelected && index == self.currentItemIndex)
{
if ([delegate respondsToSelector:@selector(carousel:didSelectItemAtIndex:)])
{
[delegate carousel:self didSelectItemAtIndex:index];
}
}
}
- (void)didPan:(UIPanGestureRecognizer *)panGesture
{
if (scrollEnabled)
{
switch (panGesture.state)
{
case UIGestureRecognizerStateBegan:
{
dragging = YES;
scrolling = NO;
decelerating = NO;
previousTranslation = vertical? [panGesture translationInView:self].y: [panGesture translationInView:self].x;
if ([delegate respondsToSelector:@selector(carouselWillBeginDragging:)])
{
[delegate carouselWillBeginDragging:self];
}
break;
}
case UIGestureRecognizerStateEnded:
case UIGestureRecognizerStateCancelled:
{
dragging = NO;
didDrag = YES;
if ([self shouldDecelerate])
{
didDrag = NO;
[self startDecelerating];
}
if ([delegate respondsToSelector:@selector(carouselDidEndDragging:willDecelerate:)])
{
[delegate carouselDidEndDragging:self willDecelerate:decelerating];
}
if (!decelerating && (scrollToItemBoundary || (scrollOffset - [self clampedOffset:scrollOffset]) != 0.0f))
{
if (fabsf(scrollOffset/itemWidth - self.currentItemIndex) < 0.01f)
{
//call scroll to trigger events for legacy support reasons
//even though technically we don't need to scroll at all
[self scrollToItemAtIndex:self.currentItemIndex duration:0.01];
}
else if ([self shouldScroll])
{
NSInteger direction = (int)(startVelocity / fabsf(startVelocity));
[self scrollToItemAtIndex:self.currentItemIndex + direction animated:YES];
}
else
{
[self scrollToItemAtIndex:self.currentItemIndex animated:YES];
}
}
else if ([delegate respondsToSelector:@selector(carouselWillBeginDecelerating:)])
{
[delegate carouselWillBeginDecelerating:self];
}
break;
}
default:
{
CGFloat translation = (vertical? [panGesture translationInView:self].y: [panGesture translationInView:self].x) - previousTranslation;
CGFloat factor = 1.0f;
if (!shouldWrap && bounces)
{
factor = 1.0f - fminf(fabsf(scrollOffset - [self clampedOffset:scrollOffset]) / itemWidth, bounceDistance) / bounceDistance;
}
previousTranslation = vertical? [panGesture translationInView:self].y: [panGesture translationInView:self].x;
startVelocity = -(vertical? [panGesture velocityInView:self].y: [panGesture velocityInView:self].x) * factor * scrollSpeed;
scrollOffset -= translation * factor * offsetMultiplier;
[self didScroll];
}
}
}
}
#else
#pragma mark -
#pragma mark Mouse control
- (void)mouseDown:(NSEvent *)theEvent
{
startVelocity = 0.0f;
}
- (void)mouseDragged:(NSEvent *)theEvent
{
if (scrollEnabled)
{
if (!dragging)
{
dragging = YES;
if ([delegate respondsToSelector:@selector(carouselWillBeginDragging:)])
{
[delegate carouselWillBeginDragging:self];
}
}
scrolling = NO;
decelerating = NO;
CGFloat translation = vertical? [theEvent deltaY]: [theEvent deltaX];
CGFloat factor = 1.0f;
if (!shouldWrap && bounces)
{
factor = 1.0f - fminf(fabsf(scrollOffset - [self clampedOffset:scrollOffset]) / itemWidth, bounceDistance) / bounceDistance;
}
NSTimeInterval thisTime = [theEvent timestamp];
startVelocity = -(translation / (thisTime - startTime)) * factor * scrollSpeed;
startTime = thisTime;
scrollOffset -= translation * factor * offsetMultiplier;
[self disableAnimation];
[self didScroll];
[self enableAnimation];
}
}
- (void)mouseUp:(NSEvent *)theEvent
{
if (scrollEnabled)
{
dragging = NO;
didDrag = YES;
if ([self shouldDecelerate])
{
didDrag = NO;
[self startDecelerating];
}
if ([delegate respondsToSelector:@selector(carouselDidEndDragging:willDecelerate:)])
{
[delegate carouselDidEndDragging:self willDecelerate:decelerating];
}
if (!decelerating)
{
if ([self shouldScroll])
{
NSInteger direction = (int)(startVelocity / fabsf(startVelocity));
[self scrollToItemAtIndex:self.currentItemIndex + direction animated:YES];
}
else
{
[self scrollToItemAtIndex:self.currentItemIndex animated:YES];
}
}
else if ([delegate respondsToSelector:@selector(carouselWillBeginDecelerating:)])
{
[delegate carouselWillBeginDecelerating:self];
}
}
}
#pragma mark -
#pragma mark Scrollwheel control
- (void)scrollWheel:(NSEvent *)theEvent
{
[self mouseDragged:theEvent];
//the iCarousel deceleration system conflicts with the built-in momentum
//scrolling for scrollwheel events. need to find a way to trigger the appropriate
//events, and also detect when user has disabled momentum scrolling in system prefs
dragging = NO;
decelerating = NO;
if ([delegate respondsToSelector:@selector(carouselDidEndDragging:willDecelerate:)])
{
[delegate carouselDidEndDragging:self willDecelerate:decelerating];
}
[self scrollToItemAtIndex:self.currentItemIndex animated:YES];
}
#pragma mark -
#pragma mark Keyboard control
- (BOOL)acceptsFirstResponder
{
return YES;
}
- (void)keyDown:(NSEvent *)theEvent
{
NSString *characters = [theEvent charactersIgnoringModifiers];
if (scrollEnabled && !scrolling && [characters length])
{
if (vertical)
{
switch ([characters characterAtIndex:0])
{
case NSUpArrowFunctionKey:
{
[self scrollToItemAtIndex:self.currentItemIndex-1 animated:YES];
break;
}
case NSDownArrowFunctionKey:
{
[self scrollToItemAtIndex:self.currentItemIndex+1 animated:YES];
break;
}
}
}
else
{
switch ([characters characterAtIndex:0])
{
case NSLeftArrowFunctionKey:
{
[self scrollToItemAtIndex:self.currentItemIndex-1 animated:YES];
break;
}
case NSRightArrowFunctionKey:
{
[self scrollToItemAtIndex:self.currentItemIndex+1 animated:YES];
break;
}
}
}
}
}
#endif
@end | 009-20120511-zi | trunk/Zinipad/iCarousel.m | Objective-C | gpl3 | 65,752 |
//
// MbochureMainView.h
// Zinipad
//
// Created by ZeLkOvA on 12. 5. 24..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "viewPDF.h"
@interface MbochureMainView : UIViewController
{
viewPDF *myPDFView;
}
@property (nonatomic, retain) viewPDF *myPDFView;
@end
| 009-20120511-zi | trunk/Zinipad/MbochureMainView.h | Objective-C | gpl3 | 326 |
//
// iCarouselColor.h
//
// Version 1.6.3 beta
//
// Created by Nick Lockwood on 01/04/2011.
// Copyright 2010 Charcoal Design
//
// Distributed under the permissive zlib License
// Get the latest version from either of these locations:
//
// http://charcoaldesign.co.uk/source/cocoa#icarousel
// https://github.com/nicklockwood/iCarousel
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
//
// ARC Helper
//
// Version 1.3
//
// Created by Nick Lockwood on 05/01/2012.
// Copyright 2012 Charcoal Design
//
// Distributed under the permissive zlib license
// Get the latest version from here:
//
// https://gist.github.com/1563325
//
#ifndef AH_RETAIN
#if __has_feature(objc_arc)
#define AH_RETAIN(x) (x)
#define AH_RELEASE(x) (void)(x)
#define AH_AUTORELEASE(x) (x)
#define AH_SUPER_DEALLOC (void)(0)
#define __AH_BRIDGE __bridge
#else
#define __AH_WEAK
#define AH_WEAK assign
#define AH_RETAIN(x) [(x) retain]
#define AH_RELEASE(x) [(x) release]
#define AH_AUTORELEASE(x) [(x) autorelease]
#define AH_SUPER_DEALLOC [super dealloc]
#define __AH_BRIDGE
#endif
#endif
// Weak reference support
#ifndef AH_WEAK
#if defined __IPHONE_OS_VERSION_MIN_REQUIRED
#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3
#define __AH_WEAK __weak
#define AH_WEAK weak
#else
#define __AH_WEAK __unsafe_unretained
#define AH_WEAK unsafe_unretained
#endif
#elif defined __MAC_OS_X_VERSION_MIN_REQUIRED
#if __MAC_OS_X_VERSION_MIN_REQUIRED > __MAC_10_6
#define __AH_WEAK __weak
#define AH_WEAK weak
#else
#define __AH_WEAK __unsafe_unretained
#define AH_WEAK unsafe_unretained
#endif
#endif
#endif
// ARC Helper ends
#import <Availability.h>
#ifdef USING_CHAMELEON
#define ICAROUSEL_IOS
#elif defined __IPHONE_OS_VERSION_MAX_ALLOWED
#define ICAROUSEL_IOS
typedef CGRect SRect;
typedef CGSize SSize;
#else
#define ICAROUSEL_MACOS
#endif
#import <QuartzCore/QuartzCore.h>
#ifdef ICAROUSEL_IOS
#import <UIKit/UIKit.h>
#else
#import <Cocoa/Cocoa.h>
typedef NSView UIView;
#endif
typedef enum
{
iCarouselColorTypeWheel = 0,
iCarouselFloorTypeLinear
}
iCarouselColorType;
typedef enum
{
iCarouselColorTranformOptionCount = 0,
iCarouselColorTranformOptionArc,
iCarouselColorTranformOptionAngle,
iCarouselColorTranformOptionRadius,
iCarouselColorTranformOptionTilt,
iCarouselColorTranformOptionSpacing
}
iCarouselColorTranformOption;
@protocol iCarouselColorDataSource, iCarouselColorDelegate;
@interface iCarouselColor : UIView
//required for 32-bit Macs
//#ifdef __i386__
{
@private
id<iCarouselColorDelegate> delegate;
id<iCarouselColorDataSource> dataSourceColor;
iCarouselColorType type;
CGFloat perspective;
NSInteger numberOfItems;
NSInteger numberOfPlaceholders;
NSInteger numberOfPlaceholdersToShow;
NSInteger numberOfVisibleItems;
UIView *contentView;
NSDictionary *itemViews;
NSMutableSet *itemViewPool;
NSMutableSet *placeholderViewPool;
NSInteger previousItemIndex;
CGFloat itemWidth;
CGFloat scrollOffset;
CGFloat offsetMultiplier;
CGFloat startVelocity;
id __unsafe_unretained timer;
BOOL decelerating;
BOOL scrollEnabled;
CGFloat decelerationRate;
BOOL bounces;
CGSize contentOffset;
CGSize viewpointOffset;
CGFloat startOffset;
CGFloat endOffset;
NSTimeInterval scrollDuration;
NSTimeInterval startTime;
BOOL scrolling;
CGFloat previousTranslation;
BOOL centerItemWhenSelected;
BOOL shouldWrap;
BOOL dragging;
BOOL didDrag;
CGFloat scrollSpeed;
CGFloat bounceDistance;
NSTimeInterval toggleTime;
CGFloat toggle;
BOOL stopAtItemBoundary;
BOOL scrollToItemBoundary;
BOOL useDisplayLink;
BOOL vertical;
BOOL ignorePerpendicularSwipes;
NSInteger animationDisableCount;
}
//#endif
@property (nonatomic, retain) id<iCarouselColorDataSource> dataSourceColor;
@property (nonatomic, retain) id<iCarouselColorDelegate> delegate;
@property (nonatomic, assign) iCarouselColorType type;
@property (nonatomic, assign) CGFloat perspective;
@property (nonatomic, assign) CGFloat decelerationRate;
@property (nonatomic, assign) CGFloat scrollSpeed;
@property (nonatomic, assign) CGFloat bounceDistance;
@property (nonatomic, assign) BOOL scrollEnabled;
@property (nonatomic, assign) BOOL bounces;
@property (nonatomic, readonly) CGFloat scrollOffset;
@property (nonatomic, readonly) CGFloat offsetMultiplier;
@property (nonatomic, assign) CGSize contentOffset;
@property (nonatomic, assign) CGSize viewpointOffset;
@property (nonatomic, readonly) NSInteger numberOfItems;
@property (nonatomic, readonly) NSInteger numberOfPlaceholders;
@property (nonatomic, readonly) NSInteger currentItemIndex;
@property (nonatomic, strong, readonly) UIView *currentItemView;
@property (nonatomic, strong, readonly) NSArray *indexesForVisibleItems;
@property (nonatomic, readonly) NSInteger numberOfVisibleItems;
@property (nonatomic, strong, readonly) NSArray *visibleItemViews;
@property (nonatomic, readonly) CGFloat itemWidth;
@property (nonatomic, strong, readonly) UIView *contentView;
@property (nonatomic, readonly) CGFloat toggle;
@property (nonatomic, assign) BOOL stopAtItemBoundary;
@property (nonatomic, assign) BOOL scrollToItemBoundary;
@property (nonatomic, assign) BOOL useDisplayLink;
@property (nonatomic, assign, getter = isVertical) BOOL vertical;
@property (nonatomic, assign) BOOL ignorePerpendicularSwipes;
- (void)scrollByNumberOfItems:(NSInteger)itemCount duration:(NSTimeInterval)duration;
- (void)scrollToItemAtIndex:(NSInteger)index duration:(NSTimeInterval)duration;
- (void)scrollToItemAtIndex:(NSInteger)index animated:(BOOL)animated;
- (void)removeItemAtIndex:(NSInteger)index animated:(BOOL)animated;
//- (void)insertItemAtIndex:(NSInteger)index animated:(BOOL)animated;
- (void)reloadItemAtIndex:(NSInteger)index animated:(BOOL)animated;
- (UIView *)itemViewAtIndex:(NSInteger)index;
- (NSInteger)indexOfItemView:(UIView *)view;
- (NSInteger)indexOfItemViewOrSubview:(UIView *)view;
- (CGFloat)offsetForItemAtIndex:(NSInteger)index;
- (void)reloadDataColor;
#ifdef ICAROUSEL_IOS
@property (nonatomic, assign) BOOL centerItemWhenSelected;
#endif
@end
@protocol iCarouselColorDataSource <NSObject>
- (NSUInteger)numberOfItemsInCarouselColor:(iCarouselColor *)carousel;
- (UIView *)carouselColor:(iCarouselColor *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view;
@optional
- (NSUInteger)numberOfPlaceholdersInCarouselColor:(iCarouselColor *)carousel;
- (UIView *)carouselColor:(iCarouselColor *)carousel placeholderViewAtIndex:(NSUInteger)index reusingView:(UIView *)view;
- (NSUInteger)numberOfVisibleItemsInCarouselColor:(iCarouselColor *)carousel;
//deprecated, use carousel:viewForItemAtIndex:reusingView: and carousel:placeholderViewAtIndex:reusingView: instead
- (UIView *)carouselColor:(iCarouselColor *)carousel viewForItemAtIndex:(NSUInteger)index __deprecated;
- (UIView *)carouselColor:(iCarouselColor *)carousel placeholderViewAtIndex:(NSUInteger)index __deprecated;
@end
@protocol iCarouselColorDelegate <NSObject>
@optional
- (void)carouselWillBeginScrollingAnimation:(iCarouselColor *)carousel;
- (void)carouselDidEndScrollingAnimation:(iCarouselColor *)carousel;
- (void)carouselDidScroll:(iCarouselColor *)carousel;
- (void)carouselCurrentItemIndexUpdated:(iCarouselColor *)carousel;
- (void)carouselWillBeginDragging:(iCarouselColor *)carousel;
- (void)carouselDidEndDragging:(iCarouselColor *)carousel willDecelerate:(BOOL)decelerate;
- (void)carouselWillBeginDecelerating:(iCarouselColor *)carousel;
- (void)carouselDidEndDecelerating:(iCarouselColor *)carousel;
- (CGFloat)carouselItemWidthColor:(iCarouselColor *)carousel;
- (CGFloat)carouselOffsetMultiplier:(iCarouselColor *)carousel;
- (BOOL)carouselShouldWrapColor:(iCarouselColor *)carousel;
- (CGFloat)carouselColor:(iCarouselColor *)carousel itemAlphaForOffset:(CGFloat)offset;
- (CATransform3D)carouselColor:(iCarouselColor *)carousel itemTransformForOffset:(CGFloat)offset baseTransform:(CATransform3D)transform;
- (CGFloat)carouselColor:(iCarouselColor *)carousel valueForTransformOption:(iCarouselColorTranformOption)option withDefault:(CGFloat)value;
- (void)carouselCurrnetImgIndexColor:(int)_imgIndex;
//deprecated, use transformForItemAtIndex:withOffset:baseTransform: instead
- (CATransform3D)carousel:(iCarouselColor *)carousel transformForItemView:(UIView *)view withOffset:(CGFloat)offset __deprecated;
#ifdef ICAROUSEL_IOS
- (BOOL)carouselColor:(iCarouselColor *)carousel shouldSelectItemAtIndex:(NSInteger)index;
- (void)carouselColor:(iCarouselColor *)carousel didSelectItemAtIndex:(NSInteger)index;
#endif
@end
| 009-20120511-zi | trunk/Zinipad/iCarouselColor.h | Objective-C | gpl3 | 9,500 |
//
// SmartSearchView.m
// Zinipad
//
// Created by ZeLkOvA on 12. 5. 23..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import "SmartSearchView.h"
@interface SmartSearchView ()
@end
@implementation SmartSearchView
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton* BackButtonPressed = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[BackButtonPressed setFrame:CGRectMake(10, 10 , 100, 36)];
[BackButtonPressed setTitle:[NSString stringWithFormat:@"이전"] forState:UIControlStateNormal];
[BackButtonPressed setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[BackButtonPressed setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[BackButtonPressed setTitleEdgeInsets:UIEdgeInsetsMake(5, 45, 5, 5)];
[BackButtonPressed addTarget:self action:@selector(BackButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:BackButtonPressed];
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void)BackButtonPressed:(id)sender
{
[self.navigationController popViewControllerAnimated:YES];
}
@end
| 009-20120511-zi | trunk/Zinipad/SmartSearchView.m | Objective-C | gpl3 | 1,646 |
#import "DatabaseManager.h"
@implementation DatabaseManager
// DB 관련변수
static sqlite3* database;
static BOOL dbState;
// 데이터베이스 초기화
+ (void) connectDatabse {
// database 접속 관련 변수
BOOL success;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"ZinDataBase.sqlite"];
NSString* dbPath = [documentsDirectory stringByAppendingPathComponent:@"ZinDataBase.sqlite"];
// Document 폴더에 database 유무 확인
success = [fileManager fileExistsAtPath:dbPath];
// Resources 에서 database 카피
if (!success) {
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
}
if (!success) {
// NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
NSLog(@"Database failed");
return;
}
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK){
dbState = YES;
}
}
+ (void) closeDatabse {
sqlite3_close(database);
}
// 리스트
+ (NSMutableArray *) customerList {
[self connectDatabse];
// 셀렉트
NSMutableArray* list = [NSMutableArray array];
if (dbState == YES) {
// NSString* query = @"SELECT C_time, C_name,C_phone,C_mail,C_expanse,C_memo,C_item,C_imgName FROM customerTb";
NSString* query = @"SELECT * FROM customerTb";
// const char* sqlStatement = "SELECT * FROM customerTb";
// NSLog(@"%@", sqlStatement);
const char *sql = [query cStringUsingEncoding:1];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
NSMutableDictionary* dic = [NSMutableDictionary dictionary];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)] forKey:@"seq"];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)] forKey:@"C_date"];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)] forKey:@"C_time"];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)] forKey:@"C_name"];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 4)] forKey:@"C_phone"];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 5)] forKey:@"C_mail"];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 6)] forKey:@"C_expanse"];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 7)] forKey:@"C_memo"];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 8)] forKey:@"C_item"];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 9)] forKey:@"C_wallPaperImgName"];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 10)] forKey:@"C_FlooringImgName"];
[list addObject:dic];
}
}
sqlite3_finalize(statement);
}
[self closeDatabse];
return list;
}
// 리스트
+ (NSMutableArray *) selectedColorList:(NSInteger)colorCode category:(NSInteger)categoryCode
{
[self connectDatabse];
NSMutableArray* list = [NSMutableArray array];
if (dbState == YES) {
NSString* str = [self searchColorName:colorCode];
NSString* query1 = @"SELECT * FROM wallpaperTb WHERE W_category ='";
NSString* query2 = [NSString stringWithFormat:@"%d' AND W_color LIKE '%%", categoryCode];
NSString* query3 = [NSString stringWithFormat:@"%@%%'", str];
NSString* query = [NSString stringWithFormat:@"%@%@%@", query1, query2, query3];
NSLog(@"%@", query);
const char *sql = [query cStringUsingEncoding:1];
//
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
NSMutableDictionary* dic = [NSMutableDictionary dictionary];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)] forKey:@"W_model"];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)] forKey:@"W_name"];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)] forKey:@"W_img_thumb"];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 4)] forKey:@"W_img_original"];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 5)] forKey:@"W_description"];
[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 9)] forKey:@"W_category"];
[list addObject:dic];
}
}
sqlite3_finalize(statement);
}
[self closeDatabse];
return list;
}
////// Util /////
+(NSArray *) spliteString:(NSString*)_words
{
NSArray* list = [NSArray array];
list = [_words componentsSeparatedByString:@"|"];
return list;
}
+ (NSString*) searchColorName:(NSInteger)code
{
NSMutableArray* colorList = [[NSMutableArray alloc] init];
[colorList addObject:@"gold"];
[colorList addObject:@"gray"];
[colorList addObject:@"green"];
[colorList addObject:@"red"];
[colorList addObject:@"beige"];
[colorList addObject:@"black"];
[colorList addObject:@"blue"];
[colorList addObject:@"brown"];
[colorList addObject:@"silver"];
[colorList addObject:@"lightgreen"];
[colorList addObject:@"yellow"];
[colorList addObject:@"ivory"];
[colorList addObject:@"wine"];
[colorList addObject:@"khaki"];
[colorList addObject:@"cobalt"];
[colorList addObject:@"purple"];
[colorList addObject:@"pink"];
[colorList addObject:@"white"];
[colorList addObject:@"etc"];
NSString* strColor = [colorList objectAtIndex:code];
return strColor;
}
- (void)dealloc {
[DatabaseManager closeDatabse];
[super dealloc];
}
@end
| 009-20120511-zi | trunk/Zinipad/DatabaseManager.m | Objective-C | gpl3 | 6,524 |
//
// SmartCounselRecordView.m
// Zinipad
//
// Created by ZeLkOvA on 12. 6. 7..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import "SmartCounselRecordView.h"
@interface SmartCounselRecordView ()
@end
@implementation SmartCounselRecordView
@synthesize leftMenuScrollView;
@synthesize wallPaperView;
@synthesize flooringView;
@synthesize NameTextField;
@synthesize PhoneTextField;
@synthesize EmailTextField;
@synthesize MemoTextField;
-(void)viewWillAppear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:self.view.window];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
// [super viewWillAppear:YES];
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
_currentTextField = textField;
}
-(BOOL)textFieldShouldReturn:(UITextField*)textFieldView
{
[textFieldView resignFirstResponder];
return YES;
}
-(void)textFieldDidEndEditing:(UITextField*)textFieldView
{
_currentTextField = nil;
}
-(void)keyboardDidShow:(NSNotification *)notification
{
if (_isKeyboardShow)
{
return;
}
NSDictionary* info = [notification userInfo];
NSValue* aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [self.view convertRect:[aValue CGRectValue] fromView:nil];
CGRect viewFrame = [leftMenuScrollView frame];
viewFrame.size.height = viewFrame.size.height - keyboardRect.size.height;
leftMenuScrollView.frame = viewFrame;
CGRect textFieldRect = [_currentTextField frame];
[leftMenuScrollView scrollRectToVisible:CGRectMake(textFieldRect.origin.x, textFieldRect.origin.y+300, textFieldRect.size.width, textFieldRect.size.height) animated:YES];
_isKeyboardShow = YES;
}
-(void)keyboardDidHide:(NSNotification *)notification
{
NSDictionary* info = [notification userInfo];
NSValue* aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [self.view convertRect:[aValue CGRectValue] fromView:nil];
CGRect viewFrame = [leftMenuScrollView frame];
viewFrame.size.height += keyboardRect.size.height;
// NSLog(@"%f key",keyboardRect.size.height);
leftMenuScrollView.frame = viewFrame;
[leftMenuScrollView scrollRectToVisible:viewFrame animated:YES];
_isKeyboardShow = NO;
}
-(void)viewDidDisappear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
nPriceValue = -1;
nItemType = 0;
// 데이터 베이스
// Do any additional setup after loading the view.
UIButton* BackButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[BackButton setFrame:CGRectMake(20, 20, 70, 40)];
[BackButton setTitle:[NSString stringWithFormat:@"이전"] forState:UIControlStateNormal];
[BackButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[BackButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[BackButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[BackButton addTarget:self action:@selector(BackButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:BackButton];
[self leftSelectView];
}
-(void)BackButtonPressed:(id)sender
{
[self.navigationController popViewControllerAnimated:YES];
}
-(void)leftSelectView
{
leftMenuScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(20, 70, 400, 748-90)];
[leftMenuScrollView setBackgroundColor:[UIColor blackColor]];
[leftMenuScrollView setContentSize:CGSizeMake(400, 748)];
[self.view addSubview:leftMenuScrollView];
UIButton* PriceLowButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[PriceLowButton setFrame:CGRectMake(40, 40, 70, 40)];
[PriceLowButton setTitle:[NSString stringWithFormat:@"알뜰"] forState:UIControlStateNormal];
[PriceLowButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[PriceLowButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[PriceLowButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[PriceLowButton addTarget:self action:@selector(PriceButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[PriceLowButton setTag:0];
[leftMenuScrollView addSubview:PriceLowButton];
UIButton* PriceMidButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[PriceMidButton setFrame:CGRectMake(140, 40, 70, 40)];
[PriceMidButton setTitle:[NSString stringWithFormat:@"합리"] forState:UIControlStateNormal];
[PriceMidButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[PriceMidButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[PriceMidButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[PriceMidButton addTarget:self action:@selector(PriceButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[PriceMidButton setTag:1];
[leftMenuScrollView addSubview:PriceMidButton];
UIButton* PriceTopButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[PriceTopButton setFrame:CGRectMake(240, 40, 70, 40)];
[PriceTopButton setTitle:[NSString stringWithFormat:@"친환경"] forState:UIControlStateNormal];
[PriceTopButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[PriceTopButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[PriceTopButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[PriceTopButton addTarget:self action:@selector(PriceButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[PriceTopButton setTag:2];
[leftMenuScrollView addSubview:PriceTopButton];
UIButton* WallpaperButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[WallpaperButton setFrame:CGRectMake(40, 140, 120, 60)];
[WallpaperButton setTitle:[NSString stringWithFormat:@"벽지"] forState:UIControlStateNormal];
[WallpaperButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[WallpaperButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[WallpaperButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[WallpaperButton addTarget:self action:@selector(WallpaperOrFlooringButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[WallpaperButton setTag:10];
[leftMenuScrollView addSubview:WallpaperButton];
UIButton* FlooringButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[FlooringButton setFrame:CGRectMake(180, 140, 120, 60)];
[FlooringButton setTitle:[NSString stringWithFormat:@"바닥재"] forState:UIControlStateNormal];
[FlooringButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[FlooringButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[FlooringButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[FlooringButton addTarget:self action:@selector(WallpaperOrFlooringButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[FlooringButton setTag:11];
[leftMenuScrollView addSubview:FlooringButton];
if(nItemType == 0)
[self wallpaperViewSelect];
else
{
}
}
-(void)wallpaperViewSelect
{
self.wallPaperView = [[UIView alloc] initWithFrame:CGRectMake(10, 240, 380, 500)];
UIButton* WallpaperBaseButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[WallpaperBaseButton setFrame:CGRectMake(20, 40, 60, 50)];
[WallpaperBaseButton setTitle:[NSString stringWithFormat:@"베이스"] forState:UIControlStateNormal];
[WallpaperBaseButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[WallpaperBaseButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[WallpaperBaseButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[WallpaperBaseButton addTarget:self action:@selector(WallpaperUseButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[WallpaperBaseButton setTag:20];
[wallPaperView addSubview:WallpaperBaseButton];
UIButton* WallpaperPointButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[WallpaperPointButton setFrame:CGRectMake(90, 40, 60, 50)];
[WallpaperPointButton setTitle:[NSString stringWithFormat:@"포인트"] forState:UIControlStateNormal];
[WallpaperPointButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[WallpaperPointButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[WallpaperPointButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[WallpaperPointButton addTarget:self action:@selector(WallpaperUseButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[WallpaperPointButton setTag:21];
[wallPaperView addSubview:WallpaperPointButton];
UIButton* WallpaperCeilButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[WallpaperCeilButton setFrame:CGRectMake(160, 40, 60, 50)];
[WallpaperCeilButton setTitle:[NSString stringWithFormat:@"천장"] forState:UIControlStateNormal];
[WallpaperCeilButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[WallpaperCeilButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[WallpaperCeilButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[WallpaperCeilButton addTarget:self action:@selector(WallpaperUseButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[WallpaperCeilButton setTag:22];
[wallPaperView addSubview:WallpaperCeilButton];
UIButton* WallpaperFullWidthButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[WallpaperFullWidthButton setFrame:CGRectMake(230, 40, 60, 50)];
[WallpaperFullWidthButton setTitle:[NSString stringWithFormat:@"전폭"] forState:UIControlStateNormal];
[WallpaperFullWidthButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[WallpaperFullWidthButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[WallpaperFullWidthButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[WallpaperFullWidthButton addTarget:self action:@selector(WallpaperUseButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[WallpaperFullWidthButton setTag:23];
[wallPaperView addSubview:WallpaperFullWidthButton];
UIButton* WallpaperBandButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[WallpaperBandButton setFrame:CGRectMake(300, 40, 60, 50)];
[WallpaperBandButton setTitle:[NSString stringWithFormat:@"띠벽지"] forState:UIControlStateNormal];
[WallpaperBandButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[WallpaperBandButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[WallpaperBandButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[WallpaperBandButton addTarget:self action:@selector(WallpaperUseButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[WallpaperBandButton setTag:24];
[wallPaperView addSubview:WallpaperBandButton];
UIButton* AllColorButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[AllColorButton setFrame:CGRectMake(10, 140, 50, 50)];
[AllColorButton setTitle:[NSString stringWithFormat:@"전체"] forState:UIControlStateNormal];
[AllColorButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[AllColorButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[AllColorButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[AllColorButton addTarget:self action:@selector(ColorButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[AllColorButton setTag:30];
[wallPaperView addSubview:AllColorButton];
int buttonWidth = 50/2;
int buttonHeight = 50/2;
int buttonMarignRight = 5;
int buttonMarginBottom = 5;
int rowCount = 9;
int buttonX = 0;
int buttonY = 0;
for(int i = 0; i < 18; i++)
{
UIButton* ColorButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonX = (i % rowCount) * (buttonWidth + buttonMarignRight) + 80;
buttonY = (buttonHeight + buttonMarginBottom) * (i / rowCount) + 137;
[ColorButton setFrame:CGRectMake(buttonX, buttonY, buttonWidth, buttonHeight)];
[ColorButton setTag:31+i];
[ColorButton addTarget:self action:@selector(ColorButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[wallPaperView addSubview:ColorButton];
}
self.NameTextField = [[UITextField alloc] initWithFrame:CGRectMake(150, 220, 200, 30)];
[self.NameTextField setBackgroundColor:[UIColor whiteColor]];
[self.NameTextField setDelegate:self];
[self.NameTextField setBackgroundColor:[UIColor colorWithRed:0.94f green:0.94f blue:0.94f alpha:1.0f]];
[self.NameTextField setTextColor:[UIColor colorWithRed:0.42f green:0.42f blue:0.42f alpha:1.0f]];
[self.NameTextField setBorderStyle:UITextBorderStyleLine];
[self.NameTextField setFont:[UIFont systemFontOfSize:20]];
[wallPaperView addSubview:self.NameTextField];
self.PhoneTextField = [[UITextField alloc] initWithFrame:CGRectMake(150, 270, 200, 30)];
[self.PhoneTextField setBackgroundColor:[UIColor whiteColor]];
[self.PhoneTextField setDelegate:self];
[self.PhoneTextField setBackgroundColor:[UIColor colorWithRed:0.94f green:0.94f blue:0.94f alpha:1.0f]];
[self.PhoneTextField setTextColor:[UIColor colorWithRed:0.42f green:0.42f blue:0.42f alpha:1.0f]];
[self.PhoneTextField setBorderStyle:UITextBorderStyleLine];
[self.PhoneTextField setFont:[UIFont systemFontOfSize:20]];
[wallPaperView addSubview:self.PhoneTextField];
self.EmailTextField = [[UITextField alloc] initWithFrame:CGRectMake(150, 320, 200, 30)];
[self.EmailTextField setBackgroundColor:[UIColor whiteColor]];
[self.EmailTextField setDelegate:self];
[self.EmailTextField setBackgroundColor:[UIColor colorWithRed:0.94f green:0.94f blue:0.94f alpha:1.0f]];
[self.EmailTextField setTextColor:[UIColor colorWithRed:0.42f green:0.42f blue:0.42f alpha:1.0f]];
[self.EmailTextField setBorderStyle:UITextBorderStyleLine];
[self.EmailTextField setFont:[UIFont systemFontOfSize:20]];
[wallPaperView addSubview:self.EmailTextField];
self.MemoTextField = [[UITextView alloc] initWithFrame:CGRectMake(150, 370, 200, 130)];
[self.MemoTextField setBackgroundColor:[UIColor whiteColor]];
// [self.MemoTextField setDelegate:self];
[self.MemoTextField setBackgroundColor:[UIColor colorWithRed:0.94f green:0.94f blue:0.94f alpha:1.0f]];
[self.MemoTextField setTextColor:[UIColor colorWithRed:0.42f green:0.42f blue:0.42f alpha:1.0f]];
// [self.MemoTextField setBorderStyle:UITextBorderStyleLine];
[self.MemoTextField setFont:[UIFont systemFontOfSize:20]];
[wallPaperView addSubview:self.MemoTextField];
[leftMenuScrollView addSubview:wallPaperView];
}
-(void)PriceButtonPressed:(id)sender
{
}
-(void)WallpaperOrFlooringButtonPressed:(id)sender
{
}
-(void)WallpaperUseButtonPressed:(id)sender
{
}
-(void)ColorButtonPressed:(id)sender
{
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return NO;
}
@end
| 009-20120511-zi | trunk/Zinipad/SmartCounselRecordView.m | Objective-C | gpl3 | 16,207 |
//
// RootViewController.m
// MyTreeViewPrototype
//
// Created by Jon Limjap on 4/21/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "TreeView.h"
#import "MyTreeViewCell.h"
#import "KakaoLinkCenter.h"
@implementation TreeView
@synthesize Trdelegate;
@synthesize treeNode;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
self.treeNode = [[MyTreeNode alloc] initWithValue:@"Root"];
MyTreeNode *node1 = [[MyTreeNode alloc] initWithValue:@"주택용 바닥재 - 마루"];
[treeNode addChild:node1];
MyTreeNode *node1a = [[MyTreeNode alloc] initWithValue:@"지아마루 - 프레스티지"];
MyTreeNode *node1b = [[MyTreeNode alloc] initWithValue:@"지아마루 - 7"];
MyTreeNode *node1c = [[MyTreeNode alloc] initWithValue:@"원목마루"];
MyTreeNode *node1d = [[MyTreeNode alloc] initWithValue:@"녹차마루"];
MyTreeNode *node1e = [[MyTreeNode alloc] initWithValue:@"강그린마루"];
MyTreeNode *node1f = [[MyTreeNode alloc] initWithValue:@"포르테마루 - 광폭"];
MyTreeNode *node1g = [[MyTreeNode alloc] initWithValue:@"포르테마루 - 소폭"];
[node1 addChild:node1a];
[node1 addChild:node1b];
[node1 addChild:node1c];
[node1 addChild:node1d];
[node1 addChild:node1e];
[node1 addChild:node1f];
[node1 addChild:node1g];
MyTreeNode *node2 = [[MyTreeNode alloc] initWithValue:@"주택용 바닥재 - PVC시트"];
[treeNode addChild:node2];
MyTreeNode *node2a = [[MyTreeNode alloc] initWithValue:@"소리잠"];
MyTreeNode *node2b = [[MyTreeNode alloc] initWithValue:@"휴앤미"];
MyTreeNode *node2c = [[MyTreeNode alloc] initWithValue:@"네이쳐라이프"];
MyTreeNode *node2d = [[MyTreeNode alloc] initWithValue:@"자연애2.5"];
MyTreeNode *node2e = [[MyTreeNode alloc] initWithValue:@"자연애2.2"];
MyTreeNode *node2f = [[MyTreeNode alloc] initWithValue:@"자연애1.8"];
MyTreeNode *node2g = [[MyTreeNode alloc] initWithValue:@"뉴청맥1.8"];
[node2 addChild:node2a];
[node2 addChild:node2b];
[node2 addChild:node2c];
[node2 addChild:node2d];
[node2 addChild:node2e];
[node2 addChild:node2f];
[node2 addChild:node2g];
MyTreeNode *node3 = [[MyTreeNode alloc] initWithValue:@"주택용 바닥재 - PVC타일"];
[treeNode addChild:node3];
MyTreeNode *node3a = [[MyTreeNode alloc] initWithValue:@"하우스"];
[node3 addChild:node3a];
node1.inclusive = NO;
node2.inclusive = NO;
node3.inclusive = NO;
// node1b.inclusive = NO;
MyTreeNode *node4 = [[MyTreeNode alloc] initWithValue:@"상업용 바닥재 - PVC타일"];
[treeNode addChild:node4];
node4.inclusive = NO;
MyTreeNode *node4a = [[MyTreeNode alloc] initWithValue:@"데코타일 파인플러스"];
MyTreeNode *node4b = [[MyTreeNode alloc] initWithValue:@"데코타일 에코노"];
MyTreeNode *node4c = [[MyTreeNode alloc] initWithValue:@"하우스 이지"];
MyTreeNode *node4d = [[MyTreeNode alloc] initWithValue:@"VIP타일 인레이드"];
MyTreeNode *node4e = [[MyTreeNode alloc] initWithValue:@"VIP타일 마블/포스트"];
MyTreeNode *node4f = [[MyTreeNode alloc] initWithValue:@"전도성타일"];
MyTreeNode *node4g = [[MyTreeNode alloc] initWithValue:@"VCT타일-갤런트/GR"];
MyTreeNode *node4h = [[MyTreeNode alloc] initWithValue:@"디럭스타일"];
MyTreeNode *node4i = [[MyTreeNode alloc] initWithValue:@"기능성타일-OA타일"];
[node4 addChild:node4a];
[node4 addChild:node4b];
[node4 addChild:node4c];
[node4 addChild:node4d];
[node4 addChild:node4e];
[node4 addChild:node4f];
[node4 addChild:node4g];
[node4 addChild:node4h];
[node4 addChild:node4i];
MyTreeNode *node5 = [[MyTreeNode alloc] initWithValue:@"상업용 바닥재 - PVC시트"];
[treeNode addChild:node5];
node5.inclusive = NO;
MyTreeNode *node5a = [[MyTreeNode alloc] initWithValue:@"우븐"];
MyTreeNode *node5b = [[MyTreeNode alloc] initWithValue:@"지아플로어 호모젠"];
MyTreeNode *node5c = [[MyTreeNode alloc] initWithValue:@"엘스트롱 유나이트"];
MyTreeNode *node5d = [[MyTreeNode alloc] initWithValue:@"엘스트롱 클레버"];
MyTreeNode *node5e = [[MyTreeNode alloc] initWithValue:@"엘스트롱 노블아트"];
MyTreeNode *node5f = [[MyTreeNode alloc] initWithValue:@"네이쳐라이프"];
MyTreeNode *node5g = [[MyTreeNode alloc] initWithValue:@"와이드"];
MyTreeNode *node5h = [[MyTreeNode alloc] initWithValue:@"EQ플로어"];
MyTreeNode *node5i = [[MyTreeNode alloc] initWithValue:@"렉스코트"];
MyTreeNode *node5j = [[MyTreeNode alloc] initWithValue:@"SD메탈/트랜스"];
[node5 addChild:node5a];
[node5 addChild:node5b];
[node5 addChild:node5c];
[node5 addChild:node5d];
[node5 addChild:node5e];
[node5 addChild:node5f];
[node5 addChild:node5g];
[node5 addChild:node5h];
[node5 addChild:node5i];
[node5 addChild:node5j];
MyTreeNode *node6 = [[MyTreeNode alloc] initWithValue:@"상업용 바닥재 - 카펫타일"];
[treeNode addChild:node6];
node6.inclusive = NO;
MyTreeNode *node6a = [[MyTreeNode alloc] initWithValue:@"Style"];
MyTreeNode *node6b = [[MyTreeNode alloc] initWithValue:@"L1000"];
MyTreeNode *node6c = [[MyTreeNode alloc] initWithValue:@"L9300"];
MyTreeNode *node6d = [[MyTreeNode alloc] initWithValue:@"L9600"];
MyTreeNode *node6e = [[MyTreeNode alloc] initWithValue:@"L9700"];
MyTreeNode *node6f = [[MyTreeNode alloc] initWithValue:@"L3300"];
MyTreeNode *node6g = [[MyTreeNode alloc] initWithValue:@"L7000"];
[node6 addChild:node6a];
[node6 addChild:node6b];
[node6 addChild:node6c];
[node6 addChild:node6d];
[node6 addChild:node6e];
[node6 addChild:node6f];
[node6 addChild:node6g];
MyTreeNode *node7 = [[MyTreeNode alloc] initWithValue:@"상업용 바닥재 - 스톤타일"];
[treeNode addChild:node7];
node7.inclusive = NO;
MyTreeNode *node7a = [[MyTreeNode alloc] initWithValue:@"마블"];
MyTreeNode *node7b = [[MyTreeNode alloc] initWithValue:@"폴리싱"];
[node7 addChild:node7a];
[node7 addChild:node7b];
MyTreeNode *node9 = [[MyTreeNode alloc] initWithValue:@"MY샘플북"];
[treeNode addChild:node9];
// MyTreeNode *node8 = [[MyTreeNode alloc] initWithValue:@""];
// [treeNode addChild:node8];
// MyTreeNode *node4 = [[MyTreeNode alloc] initWithValue:@"MY샘플북"];
// [treeNode addChild:node4];
// MyTreeNode *node2a1 = [[MyTreeNode alloc] initWithValue:@"Node2a1"];
// [node2a addChild:node2a1];
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// descendantCount = descendantCount +1;
NSLog(@"%d",[treeNode descendantCount]);
// self.contentSizeForViewInPopover = CGSizeMake(self.view.frame.size.width, [treeNode descendantCount]*44 + 100);
if(section == 0)
return [self.treeNode descendantCount];
else return 0;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
MyTreeNode *node = [[treeNode flattenElements] objectAtIndex:indexPath.row + 1];
// MyTreeViewCell *cell = [[MyTreeViewCell alloc] initWithStyle:UITableViewCellStyleDefault
// reuseIdentifier:CellIdentifier
// level:[node levelDepth] - 1
// expanded:node.inclusive];
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if([node.value isEqualToString:@"포르테마루 - 소폭"])
{
if([node levelDepth] - 1 != 0)
{
UIImage* aaa = [UIImage imageNamed:@"bg_lnb_b"];
UIImageView* aaaa = [[UIImageView alloc] initWithImage:aaa];
aaaa.frame = CGRectMake(0, 0, 188, 61);
[cell addSubview:aaaa];
}
}
else
{
UIImage* bbb = [UIImage imageNamed:@"bg_lnb_m"];
UIImageView* bbbb = [[UIImageView alloc] initWithImage:bbb];
bbbb.frame = CGRectMake(0, 0, 188, 50);
[cell addSubview:bbbb];
}
if([node levelDepth] - 1 == 0)
{
UIFont *font;
font = [UIFont boldSystemFontOfSize:14];
UILabel *newLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, cell.frame.size.width, cell.frame.size.height)];
newLabel.text = node.value;
newLabel.font = font;
newLabel.backgroundColor = [UIColor clearColor];
[cell addSubview:newLabel];
}
else
{
UIFont *font;
font = [UIFont systemFontOfSize:12];
UILabel *newLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, cell.frame.size.width, cell.frame.size.height)];
newLabel.text = node.value;
newLabel.font = font;
newLabel.backgroundColor = [UIColor clearColor];
[cell addSubview:newLabel];
}
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[cell setSelected:NO animated:NO];
// [tableView reloadData];
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
MyTreeNode *node = [[treeNode flattenElements] objectAtIndex:indexPath.row + 1];
if (!node.hasChildren)
{
[self.Trdelegate TreeViewSelect:indexPath.row haschilden:YES];
[tableView reloadData];
// UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
// [cell setSelected:NO animated:NO];
return;
}
else
{
node.inclusive = !node.inclusive;
[treeNode flattenElementsWithCacheRefresh:YES];
[self.Trdelegate TreeViewSelect:indexPath.row haschilden:NO];
[tableView reloadData];
// UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
// [cell setSelected:NO animated:NO];
}
/////
//
// NSString *message = @"카카오링크를 사용하여 메시지를 전달해보세요."; // 메세지
// NSString *referenceURLString = @"http://link.kakao.com"; // 링크 넘기기
// NSString *appBundleID = @"com.example.app";
// NSString *appVersion = @"2.0";
// NSString *appName = @"example"; // 제목
//
// if ([[KakaoLinkCenter defaultCenter] canOpenKakaoLink]) {
// [[KakaoLinkCenter defaultCenter] openKakaoLinkWithURL:referenceURLString
// appVersion:appVersion
// appBundleID:appBundleID
// appName:appName
// message:message];
// } else {
// // 카카오톡이 설치되어 있지 않은 경우에 대한 처리
// NSLog(@"카카오톡 없음요");
// }
// NSLog(@"%d",indexPath.row);
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
| 009-20120511-zi | trunk/Zinipad/TreeView.m | Objective-C | gpl3 | 12,171 |
//
// iCarousel.m
//
// Version 1.6.3 beta
//
// Created by Nick Lockwood on 01/04/2011.
// Copyright 2010 Charcoal Design
//
// Distributed under the permissive zlib License
// Get the latest version from either of these locations:
//
// http://charcoaldesign.co.uk/source/cocoa#icarousel
// https://github.com/nicklockwood/iCarousel
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
#import "iCarouselColor.h"
#define MIN_TOGGLE_DURATION 0.2f
#define MAX_TOGGLE_DURATION 0.4f
#define SCROLL_DURATION 1.0f
#define INSERT_DURATION 0.4f
#define DECELERATE_THRESHOLD 0.1f
#define SCROLL_SPEED_THRESHOLD 1.0f
#define SCROLL_DISTANCE_THRESHOLD 0.1f
#define DECELERATION_MULTIPLIER 30.0f
#define DEFAULT_FAN_COUNT 10
#define DEFAULT_SHAPE 20
#define DEFAULT_SHAPE_Wheel 10
@interface iCarouselColor ()
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) NSDictionary *itemViews;
@property (nonatomic, strong) NSMutableSet *itemViewPool;
@property (nonatomic, strong) NSMutableSet *placeholderViewPool;
@property (nonatomic, assign) NSInteger previousItemIndex;
@property (nonatomic, assign) NSInteger numberOfPlaceholdersToShow;
@property (nonatomic, assign) NSInteger numberOfVisibleItems;
@property (nonatomic, assign) CGFloat itemWidth;
@property (nonatomic, assign) CGFloat scrollOffset;
@property (nonatomic, assign) CGFloat offsetMultiplier;
@property (nonatomic, assign) CGFloat startOffset;
@property (nonatomic, assign) CGFloat endOffset;
@property (nonatomic, assign) NSTimeInterval scrollDuration;
@property (nonatomic, assign) BOOL scrolling;
@property (nonatomic, assign) NSTimeInterval startTime;
@property (nonatomic, assign) CGFloat startVelocity;
@property (nonatomic, unsafe_unretained) id timer;
@property (nonatomic, assign) BOOL decelerating;
@property (nonatomic, assign) CGFloat previousTranslation;
@property (nonatomic, assign) BOOL shouldWrap;
@property (nonatomic, assign) BOOL dragging;
@property (nonatomic, assign) BOOL didDrag;
@property (nonatomic, assign) NSTimeInterval toggleTime;
@property (nonatomic, assign) NSInteger animationDisableCount;
NSComparisonResult compareViewDepthColor(UIView *view1, UIView *view2, iCarouselColor *self);
- (void)step;
- (void)didMoveToSuperview;
- (void)layOutItemViews;
- (UIView *)loadViewAtIndex:(NSInteger)index;
- (NSInteger)clampedIndex:(NSInteger)index;
- (CGFloat)clampedOffset:(CGFloat)offset;
- (void)transformItemView:(UIView *)view atIndex:(NSInteger)index;
- (void)startAnimation;
- (void)stopAnimation;
- (void)enableAnimation;
- (void)disableAnimation;
- (void)didScroll;
@end
@implementation iCarouselColor
@synthesize dataSourceColor;
@synthesize delegate;
@synthesize type;
@synthesize perspective;
@synthesize numberOfItems;
@synthesize numberOfPlaceholders;
@synthesize numberOfPlaceholdersToShow;
@synthesize numberOfVisibleItems;
@synthesize contentView;
@synthesize itemViews;
@synthesize itemViewPool;
@synthesize placeholderViewPool;
@synthesize previousItemIndex;
@synthesize itemWidth;
@synthesize scrollOffset;
@synthesize offsetMultiplier;
@synthesize startVelocity;
@synthesize timer;
@synthesize decelerating;
@synthesize scrollEnabled;
@synthesize decelerationRate;
@synthesize bounceDistance;
@synthesize bounces;
@synthesize contentOffset;
@synthesize viewpointOffset;
@synthesize startOffset;
@synthesize endOffset;
@synthesize scrollDuration;
@synthesize startTime;
@synthesize scrolling;
@synthesize previousTranslation;
@synthesize shouldWrap;
@synthesize vertical;
@synthesize dragging;
@synthesize didDrag;
@synthesize scrollSpeed;
@synthesize toggleTime;
@synthesize toggle;
@synthesize stopAtItemBoundary;
@synthesize scrollToItemBoundary;
@synthesize useDisplayLink;
@synthesize ignorePerpendicularSwipes;
@synthesize animationDisableCount;
#ifdef ICAROUSEL_IOS
@synthesize centerItemWhenSelected;
#else
CVReturn displayLinkCallback(CVDisplayLinkRef displayLink,
const CVTimeStamp *inNow,
const CVTimeStamp *inOutputTime,
CVOptionFlags flagsIn,
CVOptionFlags *flagsOut,
iCarouselColor *self)
{
[self performSelectorOnMainThread:@selector(step) withObject:nil waitUntilDone:NO];
return kCVReturnSuccess;
}
#endif
#pragma mark -
#pragma mark Initialisation
- (void)setUp
{
// NSLog(@"hereColor hmhmhmhmhmhmhmhm");
type = iCarouselColorTypeWheel;
// type = _type;
perspective = -1.0f/500.0f;
decelerationRate = 0.95f;
scrollEnabled = YES;
bounces = YES;
scrollOffset = 0.0f;
offsetMultiplier = 1.0f;
contentOffset = CGSizeZero;
viewpointOffset = CGSizeZero;
shouldWrap = NO;
scrollSpeed = 1.0f;
bounceDistance = 1.0f;
toggle = 0.0f;
stopAtItemBoundary = YES;
scrollToItemBoundary = YES;
useDisplayLink = YES;
ignorePerpendicularSwipes = YES;
contentView = [[UIView alloc] initWithFrame:self.bounds];
#ifdef ICAROUSEL_IOS
centerItemWhenSelected = YES;
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didPan:)];
panGesture.delegate = (id <UIGestureRecognizerDelegate>)self;
[contentView addGestureRecognizer:panGesture];
AH_RELEASE(panGesture);
#else
[contentView setWantsLayer:YES];
#endif
[self addSubview:contentView];
[self reloadDataColor];
}
#ifndef USING_CHAMELEON
- (id)initWithCoder:(NSCoder *)aDecoder
{
if ((self = [super initWithCoder:aDecoder]))
{
[self setUp];
[self didMoveToSuperview];
}
return self;
}
#endif
- (id)initWithFrame:(SRect)frame
{
if ((self = [super initWithFrame:frame]))
{
[self setUp];
}
return self;
}
- (void)dealloc
{
[self stopAnimation];
AH_RELEASE(contentView);
AH_RELEASE(itemViews);
AH_RELEASE(itemViewPool);
AH_RELEASE(placeholderViewPool);
AH_SUPER_DEALLOC;
}
- (void)setDataSource:(id<iCarouselColorDataSource>)_dataSource
{
if (dataSourceColor != _dataSource)
{
dataSourceColor = _dataSource;
if (dataSourceColor)
{
[self reloadDataColor];
}
}
}
- (void)setDelegate:(id<iCarouselColorDelegate>)_delegate
{
if (delegate != _delegate)
{
delegate = _delegate;
if (delegate && dataSourceColor)
{
[self layOutItemViews];
}
}
}
- (void)setType:(iCarouselColorType)_type
{
if (type != _type)
{
type = _type;
[self layOutItemViews];
}
}
- (void)setVertical:(BOOL)_vertical
{
if (vertical != _vertical)
{
vertical = _vertical;
[self layOutItemViews];
}
}
- (void)setNumberOfVisibleItems:(NSInteger)_numberOfVisibleItems
{
if (numberOfVisibleItems != _numberOfVisibleItems)
{
numberOfVisibleItems = _numberOfVisibleItems;
[self layOutItemViews];
}
}
- (void)setContentOffset:(CGSize)_contentOffset
{
if (!CGSizeEqualToSize(contentOffset, _contentOffset))
{
contentOffset = _contentOffset;
[self layOutItemViews];
}
}
- (void)setViewpointOffset:(CGSize)_viewpointOffset
{
if (!CGSizeEqualToSize(viewpointOffset, _viewpointOffset))
{
viewpointOffset = _viewpointOffset;
[self layOutItemViews];
}
}
- (void)setUseDisplayLinkIfAvailable:(BOOL)_useDisplayLink
{
if (useDisplayLink != _useDisplayLink)
{
useDisplayLink = _useDisplayLink;
if (timer)
{
[self stopAnimation];
[self startAnimation];
}
}
}
- (void)enableAnimation
{
animationDisableCount --;
if (animationDisableCount == 0)
{
[CATransaction setDisableActions:NO];
}
}
- (void)disableAnimation
{
animationDisableCount ++;
if (animationDisableCount == 1)
{
[CATransaction setDisableActions:YES];
}
}
#pragma mark -
#pragma mark View management
- (NSArray *)indexesForVisibleItems
{
return [[itemViews allKeys] sortedArrayUsingSelector:@selector(compare:)];
}
- (NSArray *)visibleItemViews
{
NSArray *indexes = [self indexesForVisibleItems];
return [itemViews objectsForKeys:indexes notFoundMarker:[NSNull null]];
}
- (UIView *)itemViewAtIndex:(NSInteger)index
{
return [itemViews objectForKey:[NSNumber numberWithInteger:index]];
}
- (UIView *)currentItemView
{
return [self itemViewAtIndex:self.currentItemIndex];
}
- (NSInteger)indexOfItemView:(UIView *)view
{
NSInteger index = [[itemViews allValues] indexOfObject:view];
if (index != NSNotFound)
{
return [[[itemViews allKeys] objectAtIndex:index] integerValue];
}
return NSNotFound;
}
- (NSInteger)indexOfItemViewOrSubview:(UIView *)view
{
NSInteger index = [self indexOfItemView:view];
if (index == NSNotFound && view != nil && view != contentView)
{
return [self indexOfItemViewOrSubview:view.superview];
}
return index;
}
- (void)setItemView:(UIView *)view forIndex:(NSInteger)index
{
[(NSMutableDictionary *)itemViews setObject:view forKey:[NSNumber numberWithInteger:index]];
}
- (void)removeViewAtIndex:(NSInteger)index
{
NSMutableDictionary *newItemViews = [NSMutableDictionary dictionaryWithCapacity:[itemViews count] - 1];
for (NSNumber *number in [self indexesForVisibleItems])
{
NSInteger i = [number integerValue];
if (i < index)
{
[newItemViews setObject:[itemViews objectForKey:number] forKey:number];
}
else if (i > index)
{
[newItemViews setObject:[itemViews objectForKey:number] forKey:[NSNumber numberWithInteger:i - 1]];
}
}
self.itemViews = newItemViews;
}
- (void)insertView:(UIView *)view atIndex:(NSInteger)index
{
NSMutableDictionary *newItemViews = [NSMutableDictionary dictionaryWithCapacity:[itemViews count] + 1];
for (NSNumber *number in [self indexesForVisibleItems])
{
NSInteger i = [number integerValue];
if (i < index)
{
[newItemViews setObject:[itemViews objectForKey:number] forKey:number];
}
else
{
[newItemViews setObject:[itemViews objectForKey:number] forKey:[NSNumber numberWithInteger:i + 1]];
}
}
if (view)
{
[self setItemView:view forIndex:index];
}
self.itemViews = newItemViews;
}
#pragma mark -
#pragma mark View layout
- (CGFloat)alphaForItemWithOffset:(CGFloat)offset
{
switch (type)
{
default:
{
return 1.0f;
}
}
}
- (CGFloat)valueForTransformOption:(iCarouselColorTranformOption)option withDefault:(CGFloat)value
{
if ([delegate respondsToSelector:@selector(carousel:valueForTransformOption:withDefault:)])
{
return [delegate carouselColor:self valueForTransformOption:option withDefault:value];
}
return value;
}
- (CATransform3D)transformForItemView:(UIView *)view withOffset:(CGFloat)offset
{
//set up base transform
CATransform3D transform = CATransform3DIdentity;
transform.m34 = perspective;
transform = CATransform3DTranslate(transform, -viewpointOffset.width, -viewpointOffset.height, 0.0f);
//perform transform
switch (type)
{
case iCarouselFloorTypeLinear:
{
CGFloat clampedOffset = fmaxf(-1.0f, fminf(1.0f, offset));
CGFloat z = fabsf(clampedOffset) * -itemWidth * 4.0f;
if (vertical)
{
transform = CATransform3DTranslate(transform, 0.0f, 0.0f, z);
return CATransform3DTranslate(transform, 0.0f, offset * itemWidth, 0.0f);
}
else
{
transform = CATransform3DTranslate(transform, 0.0f, 0.0f, z);
return CATransform3DTranslate(transform, offset * itemWidth, 0.0f, 0.0f);
}
}
case iCarouselColorTypeWheel:
{
CGFloat arc = [self valueForTransformOption:iCarouselColorTranformOptionArc withDefault: 12.0f];
CGFloat radius = [self valueForTransformOption:iCarouselColorTranformOptionRadius withDefault:itemWidth * 3];
CGFloat angle = [self valueForTransformOption:iCarouselColorTranformOptionAngle withDefault:arc / 30];
CGFloat tilt = [self valueForTransformOption:iCarouselColorTranformOptionTilt withDefault:0.7f];
CGFloat spacing = [self valueForTransformOption:iCarouselColorTranformOptionSpacing withDefault:0.25f]; // should be ~ 1/scrollSpeed;
CGFloat clampedOffset = fmaxf(-1.0f, fminf(1.0f, offset));
CGFloat x = (clampedOffset * 0.5f * tilt + offset * spacing) * itemWidth;
CGFloat z = fabsf(clampedOffset) * -itemWidth * 4.0f;
if (vertical)
{
transform = CATransform3DTranslate(transform, 0.0f, x, z);
transform = CATransform3DTranslate(transform, -radius, 0.0f, 0.0f);
transform = CATransform3DRotate(transform, angle * offset, 0.0f, 0.0f, 1.0f);
return CATransform3DTranslate(transform, radius, 0.0f, offset * 0.01f);
}
else
{
transform = CATransform3DTranslate(transform, 0.0f, radius, 0.0f);
transform = CATransform3DRotate(transform, angle * offset, 0.0f, 0.0f, 1.0f);
return CATransform3DTranslate(transform, 0.0f, -radius, offset * 0.01f);
}
}
default:
{
//shouldn't ever happen
return CATransform3DIdentity;
}
}
}
#ifdef ICAROUSEL_IOS
NSComparisonResult compareViewDepthColor(UIView *view1, UIView *view2, iCarouselColor *self)
{
CATransform3D t1 = view1.superview.layer.transform;
CATransform3D t2 = view2.superview.layer.transform;
CGFloat z1 = t1.m13 + t1.m23 + t1.m33 + t1.m43;
CGFloat z2 = t2.m13 + t2.m23 + t2.m33 + t2.m43;
CGFloat difference = z1 - z2;
if (difference == 0.0f)
{
CATransform3D t3 = [self currentItemView].superview.layer.transform;
CGFloat x1 = t1.m11 + t1.m21 + t1.m31 + t1.m41;
CGFloat x2 = t2.m11 + t2.m21 + t2.m31 + t2.m41;
CGFloat x3 = t3.m11 + t3.m21 + t3.m31 + t3.m41;
difference = fabsf(x2 - x3) - fabsf(x1 - x3);
}
return (difference < 0.0f)? NSOrderedAscending: NSOrderedDescending;
}
- (void)depthSortViews
{
for (UIView *view in [[itemViews allValues] sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))compareViewDepthColor context:(__AH_BRIDGE void *)self])
{
[contentView addSubview:view.superview];
}
}
#else
- (void)depthSortViews
{
//does nothing on Mac OS
}
#endif
- (CGFloat)offsetForItemAtIndex:(NSInteger)index
{
//calculate relative position
CGFloat itemOffset = itemWidth? (scrollOffset / itemWidth): 0.0f;
CGFloat offset = index - itemOffset;
if (shouldWrap)
{
if (offset > numberOfItems/2)
{
offset -= numberOfItems;
}
else if (offset < -numberOfItems/2)
{
offset += numberOfItems;
}
}
//handle special case for one item
if (numberOfItems + numberOfPlaceholdersToShow == 1)
{
offset = 0.0f;
}
#ifdef ICAROUSEL_MACOS
if (vertical)
{
//invert transform
offset = -offset;
}
#endif
return offset;
}
- (UIView *)containView:(UIView *)view
{
UIView *container = AH_AUTORELEASE([[UIView alloc] initWithFrame:view.frame]);
#ifdef ICAROUSEL_IOS
//add tap gesture recogniser
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTap:)];
tapGesture.delegate = (id <UIGestureRecognizerDelegate>)self;
[container addGestureRecognizer:tapGesture];
AH_RELEASE(tapGesture);
#endif
[container addSubview:view];
return container;
}
- (void)transformItemView:(UIView *)view atIndex:(NSInteger)index
{
view.superview.bounds = view.bounds;
//calculate offset
CGFloat offset = [self offsetForItemAtIndex:index];
#ifdef ICAROUSEL_IOS
////////////////////////////////////////////////////
// 위치 잡기
//////////////////////////////////////////////////////
//center view
view.center = CGPointMake(view.bounds.size.width/2.0f, view.bounds.size.height/2.0f);
view.superview.center = CGPointMake(self.bounds.size.width/2.0f + contentOffset.width,
self.bounds.size.height/2.0f + contentOffset.height);
//update alpha
view.superview.alpha = [self alphaForItemWithOffset:offset];
#else
//center view
[view setFrameOrigin:NSMakePoint(0.0f, 0.0f)];
[view.superview setFrameOrigin:NSMakePoint(self.bounds.size.width/2.0f + contentOffset.width,
self.bounds.size.height/2.0f + contentOffset.height)];
view.superview.layer.anchorPoint = CGPointMake(0.5f, 0.5f);
//update alpha
[view.superview setAlphaValue:[self alphaForItemWithOffset:offset]];
#endif
//update backface visibility
view.superview.layer.doubleSided = view.layer.doubleSided;
//special-case logic for iCarouselTypeCoverFlow2
CGFloat clampedOffset = fmaxf(-1.0f, fminf(1.0f, offset));
if (decelerating || (scrolling && !didDrag) || (scrollOffset - [self clampedOffset:scrollOffset]) != 0.0f)
{
if (offset > 0)
{
toggle = (offset <= 0.5f)? -clampedOffset: (1.0f - clampedOffset);
}
else
{
toggle = (offset > -0.5f)? -clampedOffset: (- 1.0f - clampedOffset);
}
}
//calculate transform
CATransform3D transform = [self transformForItemView:view withOffset:offset];
//transform view
view.superview.layer.transform = transform;
}
//for iOS
- (void)layoutSubviews
{
contentView.frame = self.bounds;
[self layOutItemViews];
}
//for Mac OS
- (void)resizeSubviewsWithOldSize:(SSize)oldSize
{
[self disableAnimation];
[self layoutSubviews];
[self enableAnimation];
}
- (void)transformItemViews
{
for (NSNumber *number in itemViews)
{
NSInteger index = [number integerValue];
UIView *view = [itemViews objectForKey:number];
[self transformItemView:view atIndex:index];
#ifdef ICAROUSEL_IOS
view.userInteractionEnabled = (!centerItemWhenSelected || index == self.currentItemIndex);
#endif
}
}
- (void)updateItemWidth
{
if ([delegate respondsToSelector:@selector(carouselItemWidthColor:)])
{
itemWidth = [delegate carouselItemWidthColor:self];
}
else if (numberOfItems > 0)
{
if ([itemViews count] == 0)
{
[self loadViewAtIndex:0];
}
UIView *itemView = [[itemViews allValues] lastObject];
itemWidth = vertical? itemView.bounds.size.height: itemView.bounds.size.width;
}
else if (numberOfPlaceholders > 0)
{
if ([itemViews count] == 0)
{
[self loadViewAtIndex:-1];
}
UIView *itemView = [[itemViews allValues] lastObject];
itemWidth = vertical? itemView.bounds.size.height: itemView.bounds.size.width;
}
}
- (void)layOutItemViews
{
//bail out if not set up yet
if (!dataSourceColor || !contentView)
{
return;
}
//record current item width
CGFloat prevItemWidth = itemWidth;
//update wrap
if ([delegate respondsToSelector:@selector(carouselShouldWrapColor:)])
{
shouldWrap = [delegate carouselShouldWrapColor:self];
}
else
{
switch (type)
{
case iCarouselColorTypeWheel:
{
shouldWrap = YES;
break;
}
default:
{
shouldWrap = NO;
break;
}
}
}
//no placeholders on wrapped carousels
numberOfPlaceholdersToShow = shouldWrap? 0: numberOfPlaceholders;
//set item width
[self updateItemWidth];
//update offset multiplier
if ([delegate respondsToSelector:@selector(carouselOffsetMultiplier:)])
{
offsetMultiplier = [delegate carouselOffsetMultiplier:self];
}
else
{
switch (type)
{
default:
{
offsetMultiplier = 1.0f;
break;
}
}
}
//adjust scroll offset
if (prevItemWidth)
{
scrollOffset = itemWidth? (scrollOffset / prevItemWidth * itemWidth): 0.0f;
}
else
{
//prevent false index changed event
previousItemIndex = self.currentItemIndex;
}
//align
if (!scrolling && !decelerating)
{
if (scrollToItemBoundary)
{
[self scrollToItemAtIndex:self.currentItemIndex animated:YES];
}
else
{
scrollOffset = [self clampedOffset:scrollOffset];
}
}
//update views
[self didScroll];
}
#pragma mark -
#pragma mark View queing
- (void)queueItemView:(UIView *)view
{
if (view)
{
[itemViewPool addObject:view];
}
}
- (void)queuePlaceholderView:(UIView *)view
{
if (view)
{
[placeholderViewPool addObject:view];
}
}
- (UIView *)dequeueItemView
{
UIView *view = AH_RETAIN([itemViewPool anyObject]);
if (view)
{
[itemViewPool removeObject:view];
}
return AH_AUTORELEASE(view);
}
- (UIView *)dequeuePlaceholderView
{
UIView *view = AH_RETAIN([placeholderViewPool anyObject]);
if (view)
{
[placeholderViewPool removeObject:view];
}
return AH_AUTORELEASE(view);
}
#pragma mark -
#pragma mark View loading
- (UIView *)loadViewAtIndex:(NSInteger)index withContainerView:(UIView *)containerView
{
[self disableAnimation];
NSLog(@"aaaaaaaaaaa");
UIView *view = nil;
if (index < 0)
{
if ([dataSourceColor respondsToSelector:@selector(carouselColor:placeholderViewAtIndex:reusingView:)])
{
view = [dataSourceColor carouselColor:self placeholderViewAtIndex:(int)ceilf((CGFloat)numberOfPlaceholdersToShow/2.0f) + index reusingView:[self dequeuePlaceholderView]];
}
//deprecated code path
else if ([dataSourceColor respondsToSelector:@selector(carouselColor:placeholderViewAtIndex:)])
{
NSLog(@"DataSource method carousel:placeholderViewAtIndex: is deprecated, use carousel:placeholderViewAtIndex:reusingView: instead.");
view = [dataSourceColor carouselColor:self placeholderViewAtIndex:(int)ceilf((CGFloat)numberOfPlaceholdersToShow/2.0f) + index];
}
}
else if (index >= numberOfItems)
{
if ([dataSourceColor respondsToSelector:@selector(carouselColor:placeholderViewAtIndex:reusingView:)])
{
view = [dataSourceColor carouselColor:self placeholderViewAtIndex:numberOfPlaceholdersToShow/2.0f + index - numberOfItems reusingView:[self dequeuePlaceholderView]];
}
//deprecated code path
else if ([dataSourceColor respondsToSelector:@selector(carouselColor:placeholderViewAtIndex:)])
{
NSLog(@"DataSource method carousel:placeholderViewAtIndex: is deprecated, use carousel:placeholderViewAtIndex:reusingView: instead.");
view = [dataSourceColor carouselColor:self placeholderViewAtIndex:numberOfPlaceholdersToShow/2.0f + index - numberOfItems];
}
}
else if ([dataSourceColor respondsToSelector:@selector(carouselColor:viewForItemAtIndex:reusingView:)])
{
NSLog(@"~~~~~~~~~~~~~~~~~~~~~~~~");
view = [dataSourceColor carouselColor:self viewForItemAtIndex:index reusingView:[self dequeueItemView]];
}
//deprecated code path
else
{
NSLog(@"DataSource method carousel:viewForItemAtIndex: is deprecated, use carousel:viewForItemAtIndex:reusingView: instead.");
view = [dataSourceColor carouselColor:self viewForItemAtIndex:index];
}
if (view == nil)
{
view = AH_AUTORELEASE([[UIView alloc] init]);
}
[self setItemView:view forIndex:index];
if (containerView)
{
UIView *oldItemView = [containerView.subviews lastObject];
if (index < 0 || index >= numberOfItems)
{
[self queuePlaceholderView:view];
}
else
{
[self queueItemView:view];
}
[oldItemView removeFromSuperview];
containerView.frame = view.frame;
[containerView addSubview:view];
}
else
{
[contentView addSubview:[self containView:view]];
}
[self transformItemView:view atIndex:index];
[self enableAnimation];
return view;
}
- (UIView *)loadViewAtIndex:(NSInteger)index
{
return [self loadViewAtIndex:index withContainerView:nil];
}
- (void)loadUnloadViews
{
//calculate visible view indices
NSMutableSet *visibleIndices = [NSMutableSet setWithCapacity:numberOfVisibleItems];
NSInteger min = -(int)ceilf((CGFloat)numberOfPlaceholdersToShow/2.0f);
NSInteger max = numberOfItems - 1 + numberOfPlaceholdersToShow/2;
NSInteger count = MIN(numberOfVisibleItems, numberOfItems + numberOfPlaceholdersToShow);
NSInteger offset = self.currentItemIndex - numberOfVisibleItems/2;
if (!shouldWrap)
{
offset = MAX(min, MIN(max - count + 1, offset));
}
for (NSInteger i = 0; i < count; i++)
{
NSInteger index = i + offset;
if (shouldWrap)
{
index = [self clampedIndex:index];
}
[visibleIndices addObject:[NSNumber numberWithInteger:index]];
}
//remove offscreen views
for (NSNumber *number in [itemViews allKeys])
{
if (![visibleIndices containsObject:number])
{
UIView *view = [itemViews objectForKey:number];
if ([number integerValue] < 0 || [number integerValue] >= numberOfItems)
{
[self queuePlaceholderView:view];
}
else
{
[self queueItemView:view];
}
[view.superview removeFromSuperview];
[(NSMutableDictionary *)itemViews removeObjectForKey:number];
}
}
//add onscreen views
for (NSNumber *number in visibleIndices)
{
UIView *view = [itemViews objectForKey:number];
if (view == nil)
{
[self loadViewAtIndex:[number integerValue]];
}
}
}
- (void)reloadDataColor
{
//remove old views
for (UIView *view in [self.itemViews allValues])
{
[view.superview removeFromSuperview];
}
//bail out if not set up yet
if (!dataSourceColor || !contentView)
{
return;
}
//get number of items and placeholders
numberOfItems = [dataSourceColor numberOfItemsInCarouselColor:self];
if ([dataSourceColor respondsToSelector:@selector(numberOfPlaceholdersInCarouselColor:)])
{
numberOfPlaceholders = [dataSourceColor numberOfPlaceholdersInCarouselColor:self];
}
//get number of visible items
numberOfVisibleItems = numberOfItems + numberOfPlaceholders;
if ([dataSourceColor respondsToSelector:@selector(numberOfVisibleItemsInCarouselColor:)])
{
numberOfVisibleItems = [dataSourceColor numberOfVisibleItemsInCarouselColor:self];
}
//reset view pools
self.itemViews = [NSMutableDictionary dictionaryWithCapacity:numberOfVisibleItems];
self.itemViewPool = [NSMutableSet setWithCapacity:numberOfVisibleItems];
self.placeholderViewPool = [NSMutableSet setWithCapacity:numberOfVisibleItems];
//layout views
[self disableAnimation];
[self layOutItemViews];
[self depthSortViews];
[self performSelector:@selector(depthSortViews) withObject:nil afterDelay:0.0f];
[self enableAnimation];
if (numberOfItems > 0 && scrollOffset < 0.0f)
{
[self scrollToItemAtIndex:0 animated:(numberOfPlaceholders > 0)];
}
}
#pragma mark -
#pragma mark Scrolling
- (NSInteger)clampedIndex:(NSInteger)index
{
if (shouldWrap)
{
if (numberOfItems == 0)
{
return 0;
}
return index - floorf((CGFloat)index / (CGFloat)numberOfItems) * numberOfItems;
}
else
{
return MIN(MAX(index, 0), numberOfItems - 1);
}
}
- (CGFloat)clampedOffset:(CGFloat)offset
{
if (shouldWrap)
{
if (numberOfItems == 0)
{
return 0.0f;
}
CGFloat contentWidth = numberOfItems * itemWidth;
CGFloat clampedOffset = contentWidth? (offset - floorf(offset / contentWidth) * contentWidth): 0.0f;
return clampedOffset;
}
else
{
return fminf(fmaxf(0.0f, offset), numberOfItems * itemWidth - itemWidth);
}
}
- (NSInteger)currentItemIndex
{
return itemWidth? [self clampedIndex:roundf(scrollOffset / itemWidth)]: 0.0f;
}
- (NSInteger)minScrollDistanceFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex
{
NSInteger directDistance = toIndex - fromIndex;
if (shouldWrap)
{
NSInteger wrappedDistance = MIN(toIndex, fromIndex) + numberOfItems - MAX(toIndex, fromIndex);
if (fromIndex < toIndex)
{
wrappedDistance = -wrappedDistance;
}
return (ABS(directDistance) <= ABS(wrappedDistance))? directDistance: wrappedDistance;
}
return directDistance;
}
- (CGFloat)minScrollDistanceFromOffset:(CGFloat)fromOffset toOffset:(CGFloat)toOffset
{
CGFloat directDistance = toOffset - fromOffset;
if (shouldWrap)
{
CGFloat wrappedDistance = fminf(toOffset, fromOffset) + numberOfItems*itemWidth - fmaxf(toOffset, fromOffset);
if (fromOffset < toOffset)
{
wrappedDistance = -wrappedDistance;
}
return (fabsf(directDistance) <= fabsf(wrappedDistance))? directDistance: wrappedDistance;
}
return directDistance;
}
- (void)scrollByNumberOfItems:(NSInteger)itemCount duration:(NSTimeInterval)duration
{
if (duration > 0.0)
{
scrolling = YES;
startTime = CACurrentMediaTime();
startOffset = scrollOffset;
scrollDuration = duration;
previousItemIndex = roundf(scrollOffset/itemWidth);
if (itemCount > 0)
{
endOffset = itemWidth? ((floorf(startOffset / itemWidth) + itemCount) * itemWidth): 0.0f;
}
else if (itemCount < 0)
{
endOffset = itemWidth? ((ceilf(startOffset / itemWidth) + itemCount) * itemWidth): 0.0f;
}
else
{
endOffset = itemWidth? (roundf(startOffset / itemWidth) * itemWidth): 0.0f;
}
if (!shouldWrap)
{
endOffset = [self clampedOffset:endOffset];
}
if ([delegate respondsToSelector:@selector(carouselWillBeginScrollingAnimation:)])
{
[delegate carouselWillBeginScrollingAnimation:self];
}
[self startAnimation];
}
else
{
scrolling = NO;
decelerating = NO;
[self disableAnimation];
scrollOffset = itemWidth * [self clampedIndex:previousItemIndex + itemCount];
previousItemIndex = previousItemIndex + itemCount;
[self didScroll];
[self depthSortViews];
[self enableAnimation];
}
}
- (void)scrollToItemAtIndex:(NSInteger)index duration:(NSTimeInterval)duration
{
[self scrollByNumberOfItems:[self minScrollDistanceFromIndex:roundf(scrollOffset/itemWidth) toIndex:index] duration:duration];
}
- (void)scrollToItemAtIndex:(NSInteger)index animated:(BOOL)animated
{
[self scrollToItemAtIndex:index duration:animated? SCROLL_DURATION: 0];
}
- (void)removeItemAtIndex:(NSInteger)index animated:(BOOL)animated
{
index = [self clampedIndex:index];
UIView *itemView = [self itemViewAtIndex:index];
if (animated)
{
#ifdef ICAROUSEL_IOS
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.1];
[UIView setAnimationDelegate:itemView.superview];
[UIView setAnimationDidStopSelector:@selector(removeFromSuperview)];
[self performSelector:@selector(queueItemView:) withObject:itemView afterDelay:0.1];
itemView.superview.layer.opacity = 0.0f;
[UIView commitAnimations];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:INSERT_DURATION];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(depthSortViews)];
[self removeViewAtIndex:index];
numberOfItems --;
if (![dataSourceColor respondsToSelector:@selector(numberOfVisibleItemsInCarouselColor:)])
{
numberOfVisibleItems --;
}
scrollOffset = itemWidth * self.currentItemIndex;
[self didScroll];
[UIView commitAnimations];
#else
[CATransaction begin];
[CATransaction setAnimationDuration:0.1];
[CATransaction setCompletionBlock:^{
[self queueItemView:itemView];
[itemView.superview removeFromSuperview];
}];
itemView.superview.layer.opacity = 0.0f;
[CATransaction commit];
[CATransaction begin];
[CATransaction setAnimationDuration:INSERT_DURATION];
[CATransaction setCompletionBlock:^{
[self depthSortViews];
}];
[self removeViewAtIndex:index];
numberOfItems --;
scrollOffset = itemWidth * self.currentItemIndex;
[self didScroll];
[CATransaction commit];
#endif
}
else
{
[self disableAnimation];
[self queueItemView:itemView];
[itemView.superview removeFromSuperview];
[self removeViewAtIndex:index];
numberOfItems --;
scrollOffset = itemWidth * self.currentItemIndex;
[self didScroll];
[self depthSortViews];
[self enableAnimation];
}
}
- (void)fadeInItemView:(UIView *)itemView
{
NSInteger index = [self indexOfItemView:itemView];
CGFloat offset = [self offsetForItemAtIndex:index];
CGFloat alpha = [self alphaForItemWithOffset:offset];
#ifdef ICAROUSEL_IOS
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.1f];
itemView.superview.layer.opacity = alpha;
[UIView commitAnimations];
#else
[CATransaction begin];
[CATransaction setAnimationDuration:0.1f];
itemView.superview.layer.opacity = alpha;
[CATransaction commit];
#endif
}
//- (void)insertItemAtIndex:(NSInteger)index animated:(BOOL)animated
//{
// numberOfItems ++;
// if (![dataSourceColor respondsToSelector:@selector(numberOfVisibleItemsInCarouselColor:)])
// {
// numberOfVisibleItems ++;
// }
//
// index = [self clampedIndex:index];
// [self insertView:nil atIndex:index];
// UIView *itemView = [self loadViewAtIndex:index];
// itemView.superview.layer.opacity = 0.0f;
//
// if (itemWidth == 0)
// {
// [self updateItemWidth];
// }
//
// if (animated)
// {
//
//#ifdef ICAROUSEL_IOS
//
// [UIView beginAnimations:nil context:nil];
// [UIView setAnimationDuration:INSERT_DURATION];
// [UIView setAnimationDelegate:self];
// [UIView setAnimationDidStopSelector:@selector(loadUnloadViews)];
// [self transformItemViews];
// [UIView commitAnimations];
//
//#else
//
// [CATransaction begin];
// [CATransaction setAnimationDuration:INSERT_DURATION];
// [CATransaction setCompletionBlock:^{
// [self loadUnloadViews];
// }];
// [self transformItemViews];
// [CATransaction commit];
//
//#endif
//
// [self performSelector:@selector(fadeInItemView:) withObject:itemView afterDelay:INSERT_DURATION - 0.1f];
// }
// else
// {
// [self disableAnimation];
// [self transformItemViews];
// [self enableAnimation];
// itemView.superview.layer.opacity = 1.0f;
// }
//
// if (scrollOffset < 0.0f)
// {
// [self scrollToItemAtIndex:0 animated:(animated && numberOfPlaceholders)];
// }
//}
- (void)reloadItemAtIndex:(NSInteger)index animated:(BOOL)animated
{
//get container view
UIView *containerView = [[self itemViewAtIndex:index] superview];
if (animated)
{
//fade transition
CATransition *transition = [CATransition animation];
transition.duration = INSERT_DURATION;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade;
[containerView.layer addAnimation:transition forKey:nil];
}
//reload view
[self loadViewAtIndex:index withContainerView:containerView];
}
#pragma mark -
#pragma mark Animation
- (void)startAnimation
{
if (!timer)
{
if (useDisplayLink)
{
#ifdef ICAROUSEL_IOS
#ifndef USING_CHAMELEON
//support for Chameleon
timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(step)];
[timer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
#endif
#else
CVDisplayLinkCreateWithActiveCGDisplays((void *)&timer);
CVDisplayLinkSetOutputCallback((__AH_BRIDGE CVDisplayLinkRef)timer, (CVDisplayLinkOutputCallback)&displayLinkCallback, (__AH_BRIDGE void *)self);
CVDisplayLinkStart((__AH_BRIDGE CVDisplayLinkRef)timer);
#endif
}
//use timer if display link
//disabled or unavailable
if (!timer)
{
timer = [NSTimer timerWithTimeInterval:1.0/60.0
target:self
selector:@selector(step)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
}
}
- (void)stopAnimation
{
// NSLog(@"event stop");
// NSLog(@"%d",self.currentItemIndex);
// [delegate carouselCurrnetImgIndex:self.currentItemIndex];
#ifdef ICAROUSEL_IOS
[timer invalidate];
#else
if ([timer isKindOfClass:[NSTimer class]])
{
[timer invalidate];
}
else
{
CVDisplayLinkStop((__AH_BRIDGE CVDisplayLinkRef)timer);
CVDisplayLinkRelease((__AH_BRIDGE CVDisplayLinkRef)timer);
}
#endif
timer = nil;
[delegate carouselCurrnetImgIndexColor:self.currentItemIndex];
// // [delegate carouselCurrnetImgView:self.currentItemView];
}
- (CGFloat)decelerationDistance
{
CGFloat acceleration = -startVelocity * DECELERATION_MULTIPLIER * (1.0f - decelerationRate);
return -powf(startVelocity, 2.0f) / (2.0f * acceleration);
}
- (BOOL)shouldDecelerate
{
return (fabsf(startVelocity) > itemWidth * SCROLL_SPEED_THRESHOLD) &&
(fabsf([self decelerationDistance]) > itemWidth * DECELERATE_THRESHOLD);
}
- (BOOL)shouldScroll
{
return (fabsf(startVelocity) > itemWidth * SCROLL_SPEED_THRESHOLD) &&
(fabsf(scrollOffset/itemWidth - self.currentItemIndex) > SCROLL_DISTANCE_THRESHOLD);
}
- (void)startDecelerating
{
CGFloat distance = [self decelerationDistance];
startOffset = scrollOffset;
endOffset = startOffset + distance;
if (stopAtItemBoundary)
{
if (distance > 0.0f)
{
endOffset = itemWidth? (ceilf(endOffset / itemWidth) * itemWidth): 0.0f;
}
else
{
endOffset = itemWidth? (floorf(endOffset / itemWidth) * itemWidth): 0.0f;
}
}
if (!shouldWrap)
{
if (bounces)
{
endOffset = fmaxf(itemWidth * -bounceDistance,
fminf((numberOfItems - 1.0f + bounceDistance) * itemWidth, endOffset));
}
else
{
endOffset = [self clampedOffset:endOffset];
}
}
distance = endOffset - startOffset;
startTime = CACurrentMediaTime();
scrollDuration = fabsf(distance) / fabsf(0.5f * startVelocity);
if (distance != 0.0f)
{
decelerating = YES;
[self startAnimation];
}
}
- (CGFloat)easeInOut:(CGFloat)time
{
return (time < 0.5f)? 0.5f * powf(time * 2.0f, 3.0f): 0.5f * powf(time * 2.0f - 2.0f, 3.0f) + 1.0f;
}
- (void)step
{
[self disableAnimation];
NSTimeInterval currentTime = CACurrentMediaTime();
if (toggle != 0.0f)
{
CGFloat toggleDuration = fminf(1.0f, fmaxf(0.0f, itemWidth / fabsf(startVelocity)));
toggleDuration = MIN_TOGGLE_DURATION + (MAX_TOGGLE_DURATION - MIN_TOGGLE_DURATION) * toggleDuration;
NSTimeInterval time = fminf(1.0f, (currentTime - toggleTime) / toggleDuration);
CGFloat delta = [self easeInOut:time];
toggle = (toggle < 0.0f)? (delta - 1.0f): (1.0f - delta);
[self didScroll];
}
if (scrolling)
{
NSTimeInterval time = fminf(1.0f, (currentTime - startTime) / scrollDuration);
CGFloat delta = [self easeInOut:time];
scrollOffset = startOffset + (endOffset - startOffset) * delta;
[self didScroll];
if (time == 1.0f)
{
scrolling = NO;
[self depthSortViews];
if ([delegate respondsToSelector:@selector(carouselDidEndScrollingAnimation:)])
{
[delegate carouselDidEndScrollingAnimation:self];
}
}
}
else if (decelerating)
{
CGFloat time = fminf(scrollDuration, currentTime - startTime);
CGFloat acceleration = -startVelocity/scrollDuration;
CGFloat distance = startVelocity * time + 0.5f * acceleration * powf(time, 2.0f);
scrollOffset = startOffset + distance;
[self didScroll];
if (time == (CGFloat)scrollDuration)
{
decelerating = NO;
if ([delegate respondsToSelector:@selector(carouselDidEndDecelerating:)])
{
[delegate carouselDidEndDecelerating:self];
}
if (scrollToItemBoundary || (scrollOffset - [self clampedOffset:scrollOffset]) != 0.0f)
{
if (fabsf(scrollOffset/itemWidth - self.currentItemIndex) < 0.01f)
{
//call scroll to trigger events for legacy support reasons
//even though technically we don't need to scroll at all
[self scrollToItemAtIndex:self.currentItemIndex duration:0.01];
}
else
{
[self scrollToItemAtIndex:self.currentItemIndex animated:YES];
}
}
else
{
CGFloat difference = (CGFloat)self.currentItemIndex - scrollOffset/itemWidth;
if (difference > 0.5)
{
difference = difference - 1.0f;
}
else if (difference < -0.5)
{
difference = 1.0 + difference;
}
toggleTime = currentTime - MAX_TOGGLE_DURATION * fabsf(difference);
toggle = fmaxf(-1.0f, fminf(1.0f, -difference));
}
}
}
else if (toggle == 0.0f)
{
[self stopAnimation];
}
[self enableAnimation];
}
//for iOS
- (void)didMoveToSuperview
{
if (self.superview)
{
[self reloadDataColor];
[self startAnimation];
}
else
{
[self stopAnimation];
}
}
//for Mac OS
- (void)viewDidMoveToSuperview
{
[self didMoveToSuperview];
}
- (void)didScroll
{
if (shouldWrap || !bounces)
{
scrollOffset = [self clampedOffset:scrollOffset];
}
else
{
CGFloat min = -bounceDistance * itemWidth;
CGFloat max = (fmaxf(numberOfItems - 1, 0.0f) + bounceDistance) * itemWidth;
if (scrollOffset < min)
{
scrollOffset = min;
startVelocity = 0.0f;
}
else if (scrollOffset > max)
{
scrollOffset = max;
startVelocity = 0.0f;
}
}
//check if index has changed
NSInteger currentIndex = roundf(scrollOffset/itemWidth);
NSInteger difference = [self minScrollDistanceFromIndex:previousItemIndex toIndex:currentIndex];
if (difference)
{
toggleTime = CACurrentMediaTime();
toggle = fmaxf(-1.0f, fminf(1.0f, -(CGFloat)difference));
#ifdef ICAROUSEL_MACOS
if (vertical)
{
//invert toggle
toggle = -toggle;
}
#endif
[self startAnimation];
}
[self loadUnloadViews];
[self transformItemViews];
if ([delegate respondsToSelector:@selector(carouselDidScroll:)])
{
[delegate carouselDidScroll:self];
}
//notify delegate of change index
if ([self clampedIndex:previousItemIndex] != self.currentItemIndex &&
[delegate respondsToSelector:@selector(carouselCurrentItemIndexUpdated:)])
{
[delegate carouselCurrentItemIndexUpdated:self];
}
//update previous index
previousItemIndex = currentIndex;
}
#ifdef ICAROUSEL_IOS
#pragma mark -
#pragma mark Gestures and taps
- (NSInteger)viewOrSuperviewIndex:(UIView *)view
{
if (view == nil || view == contentView)
{
return NSNotFound;
}
NSInteger index = [self indexOfItemView:view];
if (index == NSNotFound)
{
return [self viewOrSuperviewIndex:view.superview];
}
return index;
}
- (BOOL)viewOrSuperview:(UIView *)view isKindOfClass:(Class)class
{
if (view == nil || view == contentView)
{
return NO;
}
else if ([view isKindOfClass:class])
{
return YES;
}
return [self viewOrSuperview:view.superview isKindOfClass:class];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gesture shouldReceiveTouch:(UITouch *)touch
{
if ([gesture isKindOfClass:[UITapGestureRecognizer class]])
{
//handle tap
NSInteger index = [self viewOrSuperviewIndex:touch.view];
if (index == NSNotFound && centerItemWhenSelected)
{
//view is a container view
index = [self viewOrSuperviewIndex:[touch.view.subviews lastObject]];
}
if (index != NSNotFound)
{
if ([delegate respondsToSelector:@selector(carousel:shouldSelectItemAtIndex:)])
{
if (![delegate carouselColor:self shouldSelectItemAtIndex:index])
{
return NO;
}
}
if ([self viewOrSuperview:touch.view isKindOfClass:[UIControl class]] ||
[self viewOrSuperview:touch.view isKindOfClass:[UITableViewCell class]])
{
return NO;
}
}
}
else if ([gesture isKindOfClass:[UIPanGestureRecognizer class]])
{
if ([self viewOrSuperview:touch.view isKindOfClass:[UISlider class]] ||
[self viewOrSuperview:touch.view isKindOfClass:[UISwitch class]] ||
!scrollEnabled)
{
return NO;
}
}
return YES;
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gesture
{
if ([gesture isKindOfClass:[UIPanGestureRecognizer class]])
{
//ignore vertical swipes
UIPanGestureRecognizer *panGesture = (UIPanGestureRecognizer *)gesture;
CGPoint translation = [panGesture translationInView:self];
if (ignorePerpendicularSwipes)
{
if (vertical)
{
return fabsf(translation.x) <= fabsf(translation.y);
}
else
{
return fabsf(translation.x) >= fabsf(translation.y);
}
}
}
return YES;
}
- (void)didTap:(UITapGestureRecognizer *)tapGesture
{
NSInteger index = [self indexOfItemView:[tapGesture.view.subviews lastObject]];
if (centerItemWhenSelected && index != self.currentItemIndex)
{
[self scrollToItemAtIndex:index animated:YES];
}
if(centerItemWhenSelected && index == self.currentItemIndex)
{
if ([delegate respondsToSelector:@selector(carousel:didSelectItemAtIndex:)])
{
[delegate carouselColor:self didSelectItemAtIndex:index];
}
}
}
- (void)didPan:(UIPanGestureRecognizer *)panGesture
{
if (scrollEnabled)
{
switch (panGesture.state)
{
case UIGestureRecognizerStateBegan:
{
dragging = YES;
scrolling = NO;
decelerating = NO;
previousTranslation = vertical? [panGesture translationInView:self].y: [panGesture translationInView:self].x;
if ([delegate respondsToSelector:@selector(carouselWillBeginDragging:)])
{
[delegate carouselWillBeginDragging:self];
}
break;
}
case UIGestureRecognizerStateEnded:
case UIGestureRecognizerStateCancelled:
{
dragging = NO;
didDrag = YES;
if ([self shouldDecelerate])
{
didDrag = NO;
[self startDecelerating];
}
if ([delegate respondsToSelector:@selector(carouselDidEndDragging:willDecelerate:)])
{
[delegate carouselDidEndDragging:self willDecelerate:decelerating];
}
if (!decelerating && (scrollToItemBoundary || (scrollOffset - [self clampedOffset:scrollOffset]) != 0.0f))
{
if (fabsf(scrollOffset/itemWidth - self.currentItemIndex) < 0.01f)
{
//call scroll to trigger events for legacy support reasons
//even though technically we don't need to scroll at all
[self scrollToItemAtIndex:self.currentItemIndex duration:0.01];
}
else if ([self shouldScroll])
{
NSInteger direction = (int)(startVelocity / fabsf(startVelocity));
[self scrollToItemAtIndex:self.currentItemIndex + direction animated:YES];
}
else
{
[self scrollToItemAtIndex:self.currentItemIndex animated:YES];
}
}
else if ([delegate respondsToSelector:@selector(carouselWillBeginDecelerating:)])
{
[delegate carouselWillBeginDecelerating:self];
}
break;
}
default:
{
CGFloat translation = (vertical? [panGesture translationInView:self].y: [panGesture translationInView:self].x) - previousTranslation;
CGFloat factor = 1.0f;
if (!shouldWrap && bounces)
{
factor = 1.0f - fminf(fabsf(scrollOffset - [self clampedOffset:scrollOffset]) / itemWidth, bounceDistance) / bounceDistance;
}
previousTranslation = vertical? [panGesture translationInView:self].y: [panGesture translationInView:self].x;
startVelocity = -(vertical? [panGesture velocityInView:self].y: [panGesture velocityInView:self].x) * factor * scrollSpeed;
scrollOffset -= translation * factor * offsetMultiplier;
[self didScroll];
}
}
}
}
#else
#pragma mark -
#pragma mark Mouse control
- (void)mouseDown:(NSEvent *)theEvent
{
startVelocity = 0.0f;
}
- (void)mouseDragged:(NSEvent *)theEvent
{
if (scrollEnabled)
{
if (!dragging)
{
dragging = YES;
if ([delegate respondsToSelector:@selector(carouselWillBeginDragging:)])
{
[delegate carouselWillBeginDragging:self];
}
}
scrolling = NO;
decelerating = NO;
CGFloat translation = vertical? [theEvent deltaY]: [theEvent deltaX];
CGFloat factor = 1.0f;
if (!shouldWrap && bounces)
{
factor = 1.0f - fminf(fabsf(scrollOffset - [self clampedOffset:scrollOffset]) / itemWidth, bounceDistance) / bounceDistance;
}
NSTimeInterval thisTime = [theEvent timestamp];
startVelocity = -(translation / (thisTime - startTime)) * factor * scrollSpeed;
startTime = thisTime;
scrollOffset -= translation * factor * offsetMultiplier;
[self disableAnimation];
[self didScroll];
[self enableAnimation];
}
}
- (void)mouseUp:(NSEvent *)theEvent
{
if (scrollEnabled)
{
dragging = NO;
didDrag = YES;
if ([self shouldDecelerate])
{
didDrag = NO;
[self startDecelerating];
}
if ([delegate respondsToSelector:@selector(carouselDidEndDragging:willDecelerate:)])
{
[delegate carouselDidEndDragging:self willDecelerate:decelerating];
}
if (!decelerating)
{
if ([self shouldScroll])
{
NSInteger direction = (int)(startVelocity / fabsf(startVelocity));
[self scrollToItemAtIndex:self.currentItemIndex + direction animated:YES];
}
else
{
[self scrollToItemAtIndex:self.currentItemIndex animated:YES];
}
}
else if ([delegate respondsToSelector:@selector(carouselWillBeginDecelerating:)])
{
[delegate carouselWillBeginDecelerating:self];
}
}
}
#pragma mark -
#pragma mark Scrollwheel control
- (void)scrollWheel:(NSEvent *)theEvent
{
[self mouseDragged:theEvent];
//the iCarousel deceleration system conflicts with the built-in momentum
//scrolling for scrollwheel events. need to find a way to trigger the appropriate
//events, and also detect when user has disabled momentum scrolling in system prefs
dragging = NO;
decelerating = NO;
if ([delegate respondsToSelector:@selector(carouselDidEndDragging:willDecelerate:)])
{
[delegate carouselDidEndDragging:self willDecelerate:decelerating];
}
[self scrollToItemAtIndex:self.currentItemIndex animated:YES];
}
#pragma mark -
#pragma mark Keyboard control
- (BOOL)acceptsFirstResponder
{
return YES;
}
- (void)keyDown:(NSEvent *)theEvent
{
NSString *characters = [theEvent charactersIgnoringModifiers];
if (scrollEnabled && !scrolling && [characters length])
{
if (vertical)
{
switch ([characters characterAtIndex:0])
{
case NSUpArrowFunctionKey:
{
[self scrollToItemAtIndex:self.currentItemIndex-1 animated:YES];
break;
}
case NSDownArrowFunctionKey:
{
[self scrollToItemAtIndex:self.currentItemIndex+1 animated:YES];
break;
}
}
}
else
{
switch ([characters characterAtIndex:0])
{
case NSLeftArrowFunctionKey:
{
[self scrollToItemAtIndex:self.currentItemIndex-1 animated:YES];
break;
}
case NSRightArrowFunctionKey:
{
[self scrollToItemAtIndex:self.currentItemIndex+1 animated:YES];
break;
}
}
}
}
}
#endif
@end | 009-20120511-zi | trunk/Zinipad/iCarouselColor.m | Objective-C | gpl3 | 57,384 |
//
// SmartCounselRecordView.h
// Zinipad
//
// Created by ZeLkOvA on 12. 6. 7..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface SmartCounselRecordView : UIViewController<UITextFieldDelegate>
{
UIScrollView* leftMenuScrollView;
int nPriceValue;
int nItemType;
UIView* wallPaperView;
UIView* flooringView;
UITextField* NameTextField;
UITextField* PhoneTextField;
UITextField* EmailTextField;
UITextView* MemoTextField;
UITextField* _currentTextField;
BOOL _isKeyboardShow;
}
@property (nonatomic, retain) UIScrollView* leftMenuScrollView;
@property (nonatomic, retain) UIView* wallPaperView;
@property (nonatomic, retain) UIView* flooringView;
@property (nonatomic, retain) UITextField* NameTextField;
@property (nonatomic, retain) UITextField* PhoneTextField;
@property (nonatomic, retain) UITextField* EmailTextField;
@property (nonatomic, retain) UITextView* MemoTextField;
@end
| 009-20120511-zi | trunk/Zinipad/SmartCounselRecordView.h | Objective-C | gpl3 | 1,003 |
//
// SmartCounselMainView.h
// Zinipad
//
// Created by ZeLkOvA on 12. 5. 24..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface SmartCounselMainView : UIViewController
{
NSMutableArray* counselList;
UIScrollView* scrollView;
int SelectIndex;
UIView* PopupCustomerInfo;
}
@property (nonatomic, retain) NSMutableArray* counselList;
@property (nonatomic, retain) UIScrollView* scrollView;
@property (nonatomic, retain) UIView* PopupCustomerInfo;
@end
| 009-20120511-zi | trunk/Zinipad/SmartCounselMainView.h | Objective-C | gpl3 | 529 |
//
// viewPDF.m
// customPDFViewer
//
// Created by Andrew Cefalo on 3/22/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "viewPDF.h"
@implementation viewPDF
- (id)initWithFrame:(CGRect)frame FileName:(NSString*)name {
self = [super initWithFrame:(CGRect)frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
NSString *pathToPdfDoc = [[NSBundle mainBundle] pathForResource:name ofType:@"pdf"];
NSURL *pdfUrl = [NSURL fileURLWithPath:pathToPdfDoc];
document = CGPDFDocumentCreateWithURL((CFURLRef)pdfUrl);
currentPage = 1;
}
return self;
}
-(void)drawRect:(CGRect)inRect{
if(document) {
CGPDFPageRef page = CGPDFDocumentGetPage(document, currentPage);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
CGContextTranslateCTM(ctx, 0.0, [self bounds].size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);
CGContextConcatCTM(ctx, CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, [self bounds], 0, true));
CGContextDrawPDFPage(ctx, page);
CGContextRestoreGState(ctx);
}
}
-(void)increasePageNumber {
size_t pageCount = CGPDFDocumentGetNumberOfPages(document);
if (currentPage == pageCount) {
// do nothing
}
else {
currentPage++;
[self setNeedsDisplay];
}
}
-(void)decreasePageNumber {
if (currentPage == 1) {
// do nothing
}
else {
currentPage--;
[self setNeedsDisplay];
}
}
- (void)dealloc{
[super dealloc];
}
@end
| 009-20120511-zi | trunk/Zinipad/viewPDF.m | Objective-C | gpl3 | 1,624 |
//
// SampleBookMainView.m
// Zinipad
//
// Created by ZeLkOvA on 12. 5. 17..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import "SampleBookColorViewWallpaper.h"
#import "iCarouselColor.h"
//#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
//#define NUMBER_OF_ITEMS 6
#define NUMBER_OF_VISIBLE_ITEMS 7
#define ITEM_SPACING 50.0f
#define INCLUDE_PLACEHOLDERS YES
@interface SampleBookColorViewWallpaper() <UIActionSheetDelegate>
@property (nonatomic, assign) BOOL wrap;
@property (nonatomic, retain) NSMutableArray *items;
@end
@implementation SampleBookColorViewWallpaper
@synthesize carousel;
@synthesize wrap;
@synthesize items;
//@synthesize carouselColor;
- (void)setUpImg
{
//set up data
wrap = YES;
self.items = [NSMutableArray array];
// imgArray = [[NSMutableArray alloc] init];
// 이미지 가져와서 저장하기
[items addObject:@"a.png"];
[items addObject:@"b.png"];
[items addObject:@"c.png"];
[items addObject:@"a.png"];
[items addObject:@"b.png"];
[items addObject:@"c.png"];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
[self setUpImg];
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
[self InitColorCarousel];
}
-(void)InitColorCarousel
{
carouselColor = [[iCarouselColor alloc] init];
[carouselColor setFrame:CGRectMake(0,0,150,300)];
carouselColor.dataSourceColor = self;
carouselColor.delegate = self;
[self.view addSubview:carouselColor];
// carouselColor.delegate = self;
// carouselColor.dataSourceColor = self;
carouselColor.type = iCarouselColorTypeWheel;
carouselColor.vertical = !carouselColor.vertical;
}
- (void)carouselCurrnetImgIndexColor:(int)_imgIndex;
{
NSLog(@"ImgIndexColor awfafawfawfawfawdawfawfqga == %d",_imgIndex);
// UIImage* tileBGImage = [UIImage imageNamed:[items objectAtIndex:_imgIndex]];
// [detailImageView setImage:tileBGImage];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (NSUInteger)numberOfItemsInCarouselColor:(iCarouselColor *)carousel
{
return [items count];
}
- (NSUInteger)numberOfVisibleItemsInCarouselColor:(iCarouselColor *)carousel
{
//limit the number of items views loaded concurrently (for performance reasons)
//this also affects the appearance of circular-type carousels
return NUMBER_OF_VISIBLE_ITEMS;
}
- (UIView *)carouselColor:(iCarouselColor *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
if (view == nil)
{
NSLog(@"here %d",index);
view = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:[items objectAtIndex:index]]] autorelease];
[view setFrame:CGRectMake(0, 0, 80, 50)];
view.layer.doubleSided = YES; //prevent back side of view from showing
// label = [[[UILabel alloc] initWithFrame:view.bounds] autorelease];
// label.backgroundColor = [UIColor clearColor];
// label.textAlignment = UITextAlignmentCenter;
// label.font = [label.font fontWithSize:10];
// label.text = [NSString stringWithFormat:@"%d",count];
// [view addSubview:label];
// count++;
}
else
{
NSLog(@"here %d",index);
view = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:[items objectAtIndex:index]]] autorelease];
[view setFrame:CGRectMake(0, 0, 80, 50)];
view.layer.doubleSided = YES;
}
//
return view;
}
- (NSUInteger)numberOfPlaceholdersInCarouselColor:(iCarouselColor *)carousel
{
//note: placeholder views are only displayed on some carousels if wrapping is disabled
return 0;
}
- (CGFloat)carouselItemWidthColor:(iCarouselColor *)carousel
{
//usually this should be slightly wider than the item views
return ITEM_SPACING;
}
- (BOOL)carouselShouldWrapColor:(iCarouselColor *)carousel
{
return wrap;
}
-(void)dealloc
{
carouselColor.delegate = nil;
carouselColor.dataSourceColor = nil;
[carouselColor release];
[items release];
[super dealloc];
}
#pragma mark - Button Handler
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
@end
| 009-20120511-zi | trunk/Zinipad/SampleBookColorViewWallpaper.m | Objective-C | gpl3 | 4,987 |
//
// SampleBookViewFlooring.h
// Zinipad
//
// Created by ZeLkOvA on 12. 5. 23..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "iCarousel.h"
#import "iCarouselColor.h"
@interface SampleBookViewFlooring : UIViewController<iCarouselDataSource, iCarouselDelegate,iCarouselColorDataSource,iCarouselColorDelegate>
{
iCarousel* carousel;
iCarouselColor* floorList;
NSMutableArray* imgArray;
}
@property (nonatomic, retain) iCarousel *carousel;
@property (nonatomic, retain) iCarouselColor* floorList;
@property (nonatomic, retain) NSMutableArray* imgArray;
- (void)setUpImg;
@end
| 009-20120511-zi | trunk/Zinipad/SampleBookViewFlooring.h | Objective-C | gpl3 | 649 |
//
// iCarousel.h
//
// Version 1.6.3 beta
//
// Created by Nick Lockwood on 01/04/2011.
// Copyright 2010 Charcoal Design
//
// Distributed under the permissive zlib License
// Get the latest version from either of these locations:
//
// http://charcoaldesign.co.uk/source/cocoa#icarousel
// https://github.com/nicklockwood/iCarousel
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
//
// ARC Helper
//
// Version 1.3
//
// Created by Nick Lockwood on 05/01/2012.
// Copyright 2012 Charcoal Design
//
// Distributed under the permissive zlib license
// Get the latest version from here:
//
// https://gist.github.com/1563325
//
#ifndef AH_RETAIN
#if __has_feature(objc_arc)
#define AH_RETAIN(x) (x)
#define AH_RELEASE(x) (void)(x)
#define AH_AUTORELEASE(x) (x)
#define AH_SUPER_DEALLOC (void)(0)
#define __AH_BRIDGE __bridge
#else
#define __AH_WEAK
#define AH_WEAK assign
#define AH_RETAIN(x) [(x) retain]
#define AH_RELEASE(x) [(x) release]
#define AH_AUTORELEASE(x) [(x) autorelease]
#define AH_SUPER_DEALLOC [super dealloc]
#define __AH_BRIDGE
#endif
#endif
// Weak reference support
#ifndef AH_WEAK
#if defined __IPHONE_OS_VERSION_MIN_REQUIRED
#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3
#define __AH_WEAK __weak
#define AH_WEAK weak
#else
#define __AH_WEAK __unsafe_unretained
#define AH_WEAK unsafe_unretained
#endif
#elif defined __MAC_OS_X_VERSION_MIN_REQUIRED
#if __MAC_OS_X_VERSION_MIN_REQUIRED > __MAC_10_6
#define __AH_WEAK __weak
#define AH_WEAK weak
#else
#define __AH_WEAK __unsafe_unretained
#define AH_WEAK unsafe_unretained
#endif
#endif
#endif
// ARC Helper ends
#import <Availability.h>
#ifdef USING_CHAMELEON
#define ICAROUSEL_IOS
#elif defined __IPHONE_OS_VERSION_MAX_ALLOWED
#define ICAROUSEL_IOS
typedef CGRect NSRect;
typedef CGSize NSSize;
#else
#define ICAROUSEL_MACOS
#endif
#import <OpenGLES/EAGLDrawable.h>
#import <OpenGLES/EAGL.h>
#import <OpenGLES/ES1/gl.h>
#import <OpenGLES/ES1/glext.h>
#import <QuartzCore/QuartzCore.h>
#ifdef ICAROUSEL_IOS
#import <UIKit/UIKit.h>
#else
#import <Cocoa/Cocoa.h>
typedef NSView UIView;
#endif
typedef enum
{
iCarouselTypeLinear = 0,
iCarouselTypeRotary,
iCarouselTypeInvertedRotary,
iCarouselTypeCylinder,
iCarouselTypeInvertedCylinder,
iCarouselTypeWheel,
iCarouselTypeInvertedWheel,
iCarouselTypeCoverFlow,
iCarouselTypeCoverFlow2,
iCarouselTypeTimeMachine,
iCarouselTypeInvertedTimeMachine,
iCarouselTypeCustom
}
iCarouselType;
typedef enum
{
iCarouselTranformOptionCount = 0,
iCarouselTranformOptionArc,
iCarouselTranformOptionAngle,
iCarouselTranformOptionRadius,
iCarouselTranformOptionTilt,
iCarouselTranformOptionSpacing
}
iCarouselTranformOption;
@protocol iCarouselDataSource, iCarouselDelegate;
@interface iCarousel : UIView
//required for 32-bit Macs
#ifdef __i386__
{
@private
id<iCarouselDelegate> __AH_WEAK delegate;
id<iCarouselDataSource> __AH_WEAK dataSource;
iCarouselType type;
CGFloat perspective;
NSInteger numberOfItems;
NSInteger numberOfPlaceholders;
NSInteger numberOfPlaceholdersToShow;
NSInteger numberOfVisibleItems;
UIView *contentView;
NSDictionary *itemViews;
NSMutableSet *itemViewPool;
NSMutableSet *placeholderViewPool;
NSInteger previousItemIndex;
CGFloat itemWidth;
CGFloat scrollOffset;
CGFloat offsetMultiplier;
CGFloat startVelocity;
id __unsafe_unretained timer;
BOOL decelerating;
BOOL scrollEnabled;
CGFloat decelerationRate;
BOOL bounces;
CGSize contentOffset;
CGSize viewpointOffset;
CGFloat startOffset;
CGFloat endOffset;
NSTimeInterval scrollDuration;
NSTimeInterval startTime;
BOOL scrolling;
CGFloat previousTranslation;
BOOL centerItemWhenSelected;
BOOL shouldWrap;
BOOL dragging;
BOOL didDrag;
CGFloat scrollSpeed;
CGFloat bounceDistance;
NSTimeInterval toggleTime;
CGFloat toggle;
BOOL stopAtItemBoundary;
BOOL scrollToItemBoundary;
BOOL useDisplayLink;
BOOL vertical;
BOOL ignorePerpendicularSwipes;
NSInteger animationDisableCount;
}
#endif
@property (nonatomic, AH_WEAK) IBOutlet id<iCarouselDataSource> dataSource;
@property (nonatomic, AH_WEAK) IBOutlet id<iCarouselDelegate> delegate;
@property (nonatomic, assign) iCarouselType type;
@property (nonatomic, assign) CGFloat perspective;
@property (nonatomic, assign) CGFloat decelerationRate;
@property (nonatomic, assign) CGFloat scrollSpeed;
@property (nonatomic, assign) CGFloat bounceDistance;
@property (nonatomic, assign) BOOL scrollEnabled;
@property (nonatomic, assign) BOOL bounces;
@property (nonatomic, readonly) CGFloat scrollOffset;
@property (nonatomic, readonly) CGFloat offsetMultiplier;
@property (nonatomic, assign) CGSize contentOffset;
@property (nonatomic, assign) CGSize viewpointOffset;
@property (nonatomic, readonly) NSInteger numberOfItems;
@property (nonatomic, readonly) NSInteger numberOfPlaceholders;
@property (nonatomic, readonly) NSInteger currentItemIndex;
@property (nonatomic, strong, readonly) UIView *currentItemView;
@property (nonatomic, strong, readonly) NSArray *indexesForVisibleItems;
@property (nonatomic, readonly) NSInteger numberOfVisibleItems;
@property (nonatomic, strong, readonly) NSArray *visibleItemViews;
@property (nonatomic, readonly) CGFloat itemWidth;
@property (nonatomic, strong, readonly) UIView *contentView;
@property (nonatomic, readonly) CGFloat toggle;
@property (nonatomic, assign) BOOL stopAtItemBoundary;
@property (nonatomic, assign) BOOL scrollToItemBoundary;
@property (nonatomic, assign) BOOL useDisplayLink;
@property (nonatomic, assign, getter = isVertical) BOOL vertical;
@property (nonatomic, assign) BOOL ignorePerpendicularSwipes;
- (void)scrollByNumberOfItems:(NSInteger)itemCount duration:(NSTimeInterval)duration;
- (void)scrollToItemAtIndex:(NSInteger)index duration:(NSTimeInterval)duration;
- (void)scrollToItemAtIndex:(NSInteger)index animated:(BOOL)animated;
- (void)removeItemAtIndex:(NSInteger)index animated:(BOOL)animated;
- (void)insertItemAtIndex:(NSInteger)index animated:(BOOL)animated;
- (void)reloadItemAtIndex:(NSInteger)index animated:(BOOL)animated;
- (UIView *)itemViewAtIndex:(NSInteger)index;
- (NSInteger)indexOfItemView:(UIView *)view;
- (NSInteger)indexOfItemViewOrSubview:(UIView *)view;
- (CGFloat)offsetForItemAtIndex:(NSInteger)index;
- (void)reloadData;
#ifdef ICAROUSEL_IOS
@property (nonatomic, assign) BOOL centerItemWhenSelected;
#endif
@end
@protocol iCarouselDataSource <NSObject>
- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel;
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view;
@optional
- (NSUInteger)numberOfPlaceholdersInCarousel:(iCarousel *)carousel;
- (UIView *)carousel:(iCarousel *)carousel placeholderViewAtIndex:(NSUInteger)index reusingView:(UIView *)view;
- (NSUInteger)numberOfVisibleItemsInCarousel:(iCarousel *)carousel;
//deprecated, use carousel:viewForItemAtIndex:reusingView: and carousel:placeholderViewAtIndex:reusingView: instead
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index __deprecated;
- (UIView *)carousel:(iCarousel *)carousel placeholderViewAtIndex:(NSUInteger)index __deprecated;
@end
@protocol iCarouselDelegate <NSObject>
@optional
- (void)carouselWillBeginScrollingAnimation:(iCarousel *)carousel;
- (void)carouselDidEndScrollingAnimation:(iCarousel *)carousel;
- (void)carouselDidScroll:(iCarousel *)carousel;
- (void)carouselCurrentItemIndexUpdated:(iCarousel *)carousel;
- (void)carouselWillBeginDragging:(iCarousel *)carousel;
- (void)carouselDidEndDragging:(iCarousel *)carousel willDecelerate:(BOOL)decelerate;
- (void)carouselWillBeginDecelerating:(iCarousel *)carousel;
- (void)carouselDidEndDecelerating:(iCarousel *)carousel;
- (CGFloat)carouselItemWidth:(iCarousel *)carousel;
- (CGFloat)carouselOffsetMultiplier:(iCarousel *)carousel;
- (BOOL)carouselShouldWrap:(iCarousel *)carousel;
- (CGFloat)carousel:(iCarousel *)carousel itemAlphaForOffset:(CGFloat)offset;
- (CATransform3D)carousel:(iCarousel *)carousel itemTransformForOffset:(CGFloat)offset baseTransform:(CATransform3D)transform;
- (CGFloat)carousel:(iCarousel *)carousel valueForTransformOption:(iCarouselTranformOption)option withDefault:(CGFloat)value;
- (void)carouselCurrnetImgIndex:(int)_imgIndex;
//deprecated, use transformForItemAtIndex:withOffset:baseTransform: instead
- (CATransform3D)carousel:(iCarousel *)carousel transformForItemView:(UIView *)view withOffset:(CGFloat)offset __deprecated;
#ifdef ICAROUSEL_IOS
- (BOOL)carousel:(iCarousel *)carousel shouldSelectItemAtIndex:(NSInteger)index;
- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index;
#endif
@end
| 009-20120511-zi | trunk/Zinipad/iCarousel.h | Objective-C | gpl3 | 9,628 |
//
// Copyright 2011 Kakao Corp. All rights reserved.
// @author kakaolink@kakao.com
// @version 2.0
//
#import "KakaoLinkCenter.h"
//#import <YAJLiOS/YAJL.h>
static NSString *StringByAddingPercentEscapesForURLArgument(NSString *string) {
NSString *escapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8);
return [escapedString autorelease];
}
static NSString *HTTPArgumentsStringForParameters(NSDictionary *parameters) {
NSMutableArray *arguments = [NSMutableArray arrayWithCapacity:[parameters count]];
for (NSString *key in parameters) {
NSString *parameter = [NSString stringWithFormat:@"%@=%@",
StringByAddingPercentEscapesForURLArgument(key),
StringByAddingPercentEscapesForURLArgument([parameters objectForKey:key])];
[arguments addObject:parameter];
}
NSString *argumentsString = [arguments componentsJoinedByString:@"&"];
return argumentsString;
}
static KakaoLinkCenter *sharedCenter = nil;
static NSString *const KakaoLinkApiVerstion = @"2.0";
static NSString *const KakaoLinkURLBaseString = @"kakaolink://sendurl";
@implementation KakaoLinkCenter
+ (void)initialize {
@synchronized(self) {
static BOOL isInitialized = NO;
if (!isInitialized) {
sharedCenter = [[KakaoLinkCenter alloc] init];
}
}
}
- (void)dealloc {
[super dealloc];
}
- (id)init {
if ((self = [super init])) {
}
return self;
}
+ (KakaoLinkCenter *)defaultCenter {
return sharedCenter;
}
#pragma mark -
- (BOOL)canOpenKakaoLink {
NSURL *kakaoLinkTestURL = [NSURL URLWithString:KakaoLinkURLBaseString];
return [[UIApplication sharedApplication] canOpenURL:kakaoLinkTestURL];
}
- (NSString *)kakaoLinkURLStringForParameters:(NSDictionary *)parameters {
NSString *argumentsString = HTTPArgumentsStringForParameters(parameters);
NSString *URLString = [NSString stringWithFormat:@"%@?%@", KakaoLinkURLBaseString, argumentsString];
return URLString;
}
- (BOOL)openKakaoLinkWithURL:(NSString *)referenceURLString
appVersion:(NSString *)appVersion
appBundleID:(NSString *)appBundleID
appName:(NSString *)appName
message:(NSString *)message {
if (!referenceURLString || !message || !appVersion || !appBundleID ||!appName)
return NO;
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:4];
[parameters setObject:referenceURLString forKey:@"url"];
[parameters setObject:message forKey:@"msg"];
[parameters setObject:appVersion forKey:@"appver"];
[parameters setObject:appBundleID forKey:@"appid"];
[parameters setObject:appName forKey:@"appname"];
[parameters setObject:KakaoLinkApiVerstion forKey:@"apiver"];
[parameters setObject:@"link" forKey:@"type"];
return [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[self kakaoLinkURLStringForParameters:parameters]]];
}
- (BOOL)openKakaoAppLinkWithMessage:(NSString *)message
URL:(NSString *)referenceURLString
appBundleID:(NSString *)appBundleID
appVersion:(NSString *)appVersion
appName:(NSString *)appName
metaInfoArray:(NSArray *)metaInfoArray {
BOOL avalibleAppLink = !message || !appVersion || !appBundleID || !appName || !metaInfoArray || [metaInfoArray count] > 0;
if (!avalibleAppLink)
return NO;
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:7];
[parameters setObject:message forKey:@"msg"];
[parameters setObject:appVersion forKey:@"appver"];
[parameters setObject:appBundleID forKey:@"appid"];
[parameters setObject:appName forKey:@"appname"];
NSDictionary *appDataDictionary = [NSDictionary dictionaryWithObject:metaInfoArray forKey:@"metainfo"];
[parameters setObject:[appDataDictionary yajl_JSONString] forKey:@"metainfo"];
if (referenceURLString) {
[parameters setObject:referenceURLString forKey:@"url"];
}
[parameters setObject:@"app" forKey:@"type"];
[parameters setObject:KakaoLinkApiVerstion forKey:@"apiver"];
return [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[self kakaoLinkURLStringForParameters:parameters]]];
}
@end
| 009-20120511-zi | trunk/Zinipad/KakaoLinkCenter.m | Objective-C | gpl3 | 4,350 |
//
// RootViewController.h
// MyTreeViewPrototype
//
// Created by Jon Limjap on 4/21/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "MyTreeNode.h"
@protocol LeftTreeViewSelectDelegate
@required
-(void)leftTreeViewSelect:(NSInteger)selectedIndex haschilden:(BOOL)lastElement;
@end
@interface LeftTreeView : UITableViewController {
id<LeftTreeViewSelectDelegate> leftTrdelegate;
MyTreeNode *treeNode;
}
@property (nonatomic, retain) id<LeftTreeViewSelectDelegate> leftTrdelegate;
@end
| 009-20120511-zi | trunk/Zinipad/LeftTreeView.h | Objective-C | gpl3 | 549 |
/*
Copyright (C) 2007-2009 Stig Brautaset. All rights reserved.
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 the author 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.
*/
#import "SBJSON.h"
@implementation SBJSON
- (id)init {
self = [super init];
if (self) {
jsonWriter = [SBJsonWriter new];
jsonParser = [SBJsonParser new];
[self setMaxDepth:512];
}
return self;
}
- (void)dealloc {
[jsonWriter release];
[jsonParser release];
[super dealloc];
}
#pragma mark Writer
- (NSString *)stringWithObject:(id)obj {
NSString *repr = [jsonWriter stringWithObject:obj];
if (repr)
return repr;
[errorTrace release];
errorTrace = [[jsonWriter errorTrace] mutableCopy];
return nil;
}
/**
Returns a string containing JSON representation of the passed in value, or nil on error.
If nil is returned and @p error is not NULL, @p *error can be interrogated to find the cause of the error.
@param value any instance that can be represented as a JSON fragment
@param allowScalar wether to return json fragments for scalar objects
@param error used to return an error by reference (pass NULL if this is not desired)
@deprecated Given we bill ourselves as a "strict" JSON library, this method should be removed.
*/
- (NSString*)stringWithObject:(id)value allowScalar:(BOOL)allowScalar error:(NSError**)error {
NSString *json = allowScalar ? [jsonWriter stringWithFragment:value] : [jsonWriter stringWithObject:value];
if (json)
return json;
[errorTrace release];
errorTrace = [[jsonWriter errorTrace] mutableCopy];
if (error)
*error = [errorTrace lastObject];
return nil;
}
/**
Returns a string containing JSON representation of the passed in value, or nil on error.
If nil is returned and @p error is not NULL, @p error can be interrogated to find the cause of the error.
@param value any instance that can be represented as a JSON fragment
@param error used to return an error by reference (pass NULL if this is not desired)
@deprecated Given we bill ourselves as a "strict" JSON library, this method should be removed.
*/
- (NSString*)stringWithFragment:(id)value error:(NSError**)error {
return [self stringWithObject:value
allowScalar:YES
error:error];
}
/**
Returns a string containing JSON representation of the passed in value, or nil on error.
If nil is returned and @p error is not NULL, @p error can be interrogated to find the cause of the error.
@param value a NSDictionary or NSArray instance
@param error used to return an error by reference (pass NULL if this is not desired)
*/
- (NSString*)stringWithObject:(id)value error:(NSError**)error {
return [self stringWithObject:value
allowScalar:NO
error:error];
}
#pragma mark Parsing
- (id)objectWithString:(NSString *)repr {
id obj = [jsonParser objectWithString:repr];
if (obj)
return obj;
[errorTrace release];
errorTrace = [[jsonParser errorTrace] mutableCopy];
return nil;
}
/**
Returns the object represented by the passed-in string or nil on error. The returned object can be
a string, number, boolean, null, array or dictionary.
@param value the json string to parse
@param allowScalar whether to return objects for JSON fragments
@param error used to return an error by reference (pass NULL if this is not desired)
@deprecated Given we bill ourselves as a "strict" JSON library, this method should be removed.
*/
- (id)objectWithString:(id)value allowScalar:(BOOL)allowScalar error:(NSError**)error {
id obj = allowScalar ? [jsonParser fragmentWithString:value] : [jsonParser objectWithString:value];
if (obj)
return obj;
[errorTrace release];
errorTrace = [[jsonParser errorTrace] mutableCopy];
if (error)
*error = [errorTrace lastObject];
return nil;
}
/**
Returns the object represented by the passed-in string or nil on error. The returned object can be
a string, number, boolean, null, array or dictionary.
@param repr the json string to parse
@param error used to return an error by reference (pass NULL if this is not desired)
@deprecated Given we bill ourselves as a "strict" JSON library, this method should be removed.
*/
- (id)fragmentWithString:(NSString*)repr error:(NSError**)error {
return [self objectWithString:repr
allowScalar:YES
error:error];
}
/**
Returns the object represented by the passed-in string or nil on error. The returned object
will be either a dictionary or an array.
@param repr the json string to parse
@param error used to return an error by reference (pass NULL if this is not desired)
*/
- (id)objectWithString:(NSString*)repr error:(NSError**)error {
return [self objectWithString:repr
allowScalar:NO
error:error];
}
#pragma mark Properties - parsing
- (NSUInteger)maxDepth {
return jsonParser.maxDepth;
}
- (void)setMaxDepth:(NSUInteger)d {
jsonWriter.maxDepth = jsonParser.maxDepth = d;
}
#pragma mark Properties - writing
- (BOOL)humanReadable {
return jsonWriter.humanReadable;
}
- (void)setHumanReadable:(BOOL)x {
jsonWriter.humanReadable = x;
}
- (BOOL)sortKeys {
return jsonWriter.sortKeys;
}
- (void)setSortKeys:(BOOL)x {
jsonWriter.sortKeys = x;
}
@end
| 009-20120511-zi | trunk/Zinipad/JSON/SBJSON.m | Objective-C | gpl3 | 6,844 |
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
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 the author 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.
*/
#import "SBJsonBase.h"
NSString * SBJSONErrorDomain = @"org.brautaset.JSON.ErrorDomain";
@implementation SBJsonBase
@synthesize errorTrace;
@synthesize maxDepth;
- (id)init {
self = [super init];
if (self)
self.maxDepth = 512;
return self;
}
- (void)dealloc {
[errorTrace release];
[super dealloc];
}
- (void)addErrorWithCode:(NSUInteger)code description:(NSString*)str {
NSDictionary *userInfo;
if (!errorTrace) {
errorTrace = [NSMutableArray new];
userInfo = [NSDictionary dictionaryWithObject:str forKey:NSLocalizedDescriptionKey];
} else {
userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
str, NSLocalizedDescriptionKey,
[errorTrace lastObject], NSUnderlyingErrorKey,
nil];
}
NSError *error = [NSError errorWithDomain:SBJSONErrorDomain code:code userInfo:userInfo];
[self willChangeValueForKey:@"errorTrace"];
[errorTrace addObject:error];
[self didChangeValueForKey:@"errorTrace"];
}
- (void)clearErrorTrace {
[self willChangeValueForKey:@"errorTrace"];
[errorTrace release];
errorTrace = nil;
[self didChangeValueForKey:@"errorTrace"];
}
@end
| 009-20120511-zi | trunk/Zinipad/JSON/SBJsonBase.m | Objective-C | gpl3 | 2,753 |
/*
Copyright (C) 2007-2009 Stig Brautaset. All rights reserved.
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 the author 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.
*/
#import <Foundation/Foundation.h>
#import "SBJsonParser.h"
#import "SBJsonWriter.h"
/**
@brief Facade for SBJsonWriter/SBJsonParser.
Requests are forwarded to instances of SBJsonWriter and SBJsonParser.
*/
@interface SBJSON : SBJsonBase <SBJsonParser, SBJsonWriter> {
@private
SBJsonParser *jsonParser;
SBJsonWriter *jsonWriter;
}
/// Return the fragment represented by the given string
- (id)fragmentWithString:(NSString*)jsonrep
error:(NSError**)error;
/// Return the object represented by the given string
- (id)objectWithString:(NSString*)jsonrep
error:(NSError**)error;
/// Parse the string and return the represented object (or scalar)
- (id)objectWithString:(id)value
allowScalar:(BOOL)x
error:(NSError**)error;
/// Return JSON representation of an array or dictionary
- (NSString*)stringWithObject:(id)value
error:(NSError**)error;
/// Return JSON representation of any legal JSON value
- (NSString*)stringWithFragment:(id)value
error:(NSError**)error;
/// Return JSON representation (or fragment) for the given object
- (NSString*)stringWithObject:(id)value
allowScalar:(BOOL)x
error:(NSError**)error;
@end
| 009-20120511-zi | trunk/Zinipad/JSON/SBJSON.h | Objective-C | gpl3 | 2,797 |
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
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 the author 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.
*/
/**
@mainpage A strict JSON parser and generator for Objective-C
JSON (JavaScript Object Notation) is a lightweight data-interchange
format. This framework provides two apis for parsing and generating
JSON. One standard object-based and a higher level api consisting of
categories added to existing Objective-C classes.
Learn more on the http://code.google.com/p/json-framework project site.
This framework does its best to be as strict as possible, both in what it
accepts and what it generates. For example, it does not support trailing commas
in arrays or objects. Nor does it support embedded comments, or
anything else not in the JSON specification. This is considered a feature.
*/
#import "SBJSON.h"
#import "NSObject+SBJSON.h"
#import "NSString+SBJSON.h"
| 009-20120511-zi | trunk/Zinipad/JSON/JSON.h | Objective-C | gpl3 | 2,297 |
/*
Copyright (C) 2007-2009 Stig Brautaset. All rights reserved.
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 the author 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.
*/
#import "NSString+SBJSON.h"
#import "SBJsonParser.h"
@implementation NSString (NSString_SBJSON)
- (id)JSONFragmentValue
{
SBJsonParser *jsonParser = [SBJsonParser new];
id repr = [jsonParser fragmentWithString:self];
if (!repr)
NSLog(@"-JSONFragmentValue failed. Error trace is: %@", [jsonParser errorTrace]);
[jsonParser release];
return repr;
}
- (id)JSONValue
{
SBJsonParser *jsonParser = [SBJsonParser new];
id repr = [jsonParser objectWithString:self];
if (!repr)
NSLog(@"-JSONValue failed. Error trace is: %@", [jsonParser errorTrace]);
[jsonParser release];
return repr;
}
@end
| 009-20120511-zi | trunk/Zinipad/JSON/NSString+SBJSON.m | Objective-C | gpl3 | 2,173 |
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
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 the author 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.
*/
#import "SBJsonWriter.h"
@interface SBJsonWriter ()
- (BOOL)appendValue:(id)fragment into:(NSMutableString*)json;
- (BOOL)appendArray:(NSArray*)fragment into:(NSMutableString*)json;
- (BOOL)appendDictionary:(NSDictionary*)fragment into:(NSMutableString*)json;
- (BOOL)appendString:(NSString*)fragment into:(NSMutableString*)json;
- (NSString*)indent;
@end
@implementation SBJsonWriter
static NSMutableCharacterSet *kEscapeChars;
+ (void)initialize {
kEscapeChars = [[NSMutableCharacterSet characterSetWithRange: NSMakeRange(0,32)] retain];
[kEscapeChars addCharactersInString: @"\"\\"];
}
@synthesize sortKeys;
@synthesize humanReadable;
/**
@deprecated This exists in order to provide fragment support in older APIs in one more version.
It should be removed in the next major version.
*/
- (NSString*)stringWithFragment:(id)value {
[self clearErrorTrace];
depth = 0;
NSMutableString *json = [NSMutableString stringWithCapacity:128];
if ([self appendValue:value into:json])
return json;
return nil;
}
- (NSString*)stringWithObject:(id)value {
if ([value isKindOfClass:[NSDictionary class]] || [value isKindOfClass:[NSArray class]]) {
return [self stringWithFragment:value];
}
if ([value respondsToSelector:@selector(proxyForJson)]) {
NSString *tmp = [self stringWithObject:[value proxyForJson]];
if (tmp)
return tmp;
}
[self clearErrorTrace];
[self addErrorWithCode:EFRAGMENT description:@"Not valid type for JSON"];
return nil;
}
- (NSString*)indent {
return [@"\n" stringByPaddingToLength:1 + 2 * depth withString:@" " startingAtIndex:0];
}
- (BOOL)appendValue:(id)fragment into:(NSMutableString*)json {
if ([fragment isKindOfClass:[NSDictionary class]]) {
if (![self appendDictionary:fragment into:json])
return NO;
} else if ([fragment isKindOfClass:[NSArray class]]) {
if (![self appendArray:fragment into:json])
return NO;
} else if ([fragment isKindOfClass:[NSString class]]) {
if (![self appendString:fragment into:json])
return NO;
} else if ([fragment isKindOfClass:[NSNumber class]]) {
if ('c' == *[fragment objCType])
[json appendString:[fragment boolValue] ? @"true" : @"false"];
else
[json appendString:[fragment stringValue]];
} else if ([fragment isKindOfClass:[NSNull class]]) {
[json appendString:@"null"];
} else if ([fragment respondsToSelector:@selector(proxyForJson)]) {
[self appendValue:[fragment proxyForJson] into:json];
} else {
[self addErrorWithCode:EUNSUPPORTED description:[NSString stringWithFormat:@"JSON serialisation not supported for %@", [fragment class]]];
return NO;
}
return YES;
}
- (BOOL)appendArray:(NSArray*)fragment into:(NSMutableString*)json {
if (maxDepth && ++depth > maxDepth) {
[self addErrorWithCode:EDEPTH description: @"Nested too deep"];
return NO;
}
[json appendString:@"["];
BOOL addComma = NO;
for (id value in fragment) {
if (addComma)
[json appendString:@","];
else
addComma = YES;
if ([self humanReadable])
[json appendString:[self indent]];
if (![self appendValue:value into:json]) {
return NO;
}
}
depth--;
if ([self humanReadable] && [fragment count])
[json appendString:[self indent]];
[json appendString:@"]"];
return YES;
}
- (BOOL)appendDictionary:(NSDictionary*)fragment into:(NSMutableString*)json {
if (maxDepth && ++depth > maxDepth) {
[self addErrorWithCode:EDEPTH description: @"Nested too deep"];
return NO;
}
[json appendString:@"{"];
NSString *colon = [self humanReadable] ? @" : " : @":";
BOOL addComma = NO;
NSArray *keys = [fragment allKeys];
if (self.sortKeys)
keys = [keys sortedArrayUsingSelector:@selector(compare:)];
for (id value in keys) {
if (addComma)
[json appendString:@","];
else
addComma = YES;
if ([self humanReadable])
[json appendString:[self indent]];
if (![value isKindOfClass:[NSString class]]) {
[self addErrorWithCode:EUNSUPPORTED description: @"JSON object key must be string"];
return NO;
}
if (![self appendString:value into:json])
return NO;
[json appendString:colon];
if (![self appendValue:[fragment objectForKey:value] into:json]) {
[self addErrorWithCode:EUNSUPPORTED description:[NSString stringWithFormat:@"Unsupported value for key %@ in object", value]];
return NO;
}
}
depth--;
if ([self humanReadable] && [fragment count])
[json appendString:[self indent]];
[json appendString:@"}"];
return YES;
}
- (BOOL)appendString:(NSString*)fragment into:(NSMutableString*)json {
[json appendString:@"\""];
NSRange esc = [fragment rangeOfCharacterFromSet:kEscapeChars];
if ( !esc.length ) {
// No special chars -- can just add the raw string:
[json appendString:fragment];
} else {
NSUInteger length = [fragment length];
for (NSUInteger i = 0; i < length; i++) {
unichar uc = [fragment characterAtIndex:i];
switch (uc) {
case '"': [json appendString:@"\\\""]; break;
case '\\': [json appendString:@"\\\\"]; break;
case '\t': [json appendString:@"\\t"]; break;
case '\n': [json appendString:@"\\n"]; break;
case '\r': [json appendString:@"\\r"]; break;
case '\b': [json appendString:@"\\b"]; break;
case '\f': [json appendString:@"\\f"]; break;
default:
if (uc < 0x20) {
[json appendFormat:@"\\u%04x", uc];
} else {
CFStringAppendCharacters((CFMutableStringRef)json, &uc, 1);
}
break;
}
}
}
[json appendString:@"\""];
return YES;
}
@end
| 009-20120511-zi | trunk/Zinipad/JSON/SBJsonWriter.m | Objective-C | gpl3 | 7,974 |
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
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 the author 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.
*/
#import <Foundation/Foundation.h>
#import "SBJsonBase.h"
/**
@brief Options for the parser class.
This exists so the SBJSON facade can implement the options in the parser without having to re-declare them.
*/
@protocol SBJsonParser
/**
@brief Return the object represented by the given string.
Returns the object represented by the passed-in string or nil on error. The returned object can be
a string, number, boolean, null, array or dictionary.
@param repr the json string to parse
*/
- (id)objectWithString:(NSString *)repr;
@end
/**
@brief The JSON parser class.
JSON is mapped to Objective-C types in the following way:
@li Null -> NSNull
@li String -> NSMutableString
@li Array -> NSMutableArray
@li Object -> NSMutableDictionary
@li Boolean -> NSNumber (initialised with -initWithBool:)
@li Number -> NSDecimalNumber
Since Objective-C doesn't have a dedicated class for boolean values, these turns into NSNumber
instances. These are initialised with the -initWithBool: method, and
round-trip back to JSON properly. (They won't silently suddenly become 0 or 1; they'll be
represented as 'true' and 'false' again.)
JSON numbers turn into NSDecimalNumber instances,
as we can thus avoid any loss of precision. (JSON allows ridiculously large numbers.)
*/
@interface SBJsonParser : SBJsonBase <SBJsonParser> {
@private
const char *c;
}
@end
// don't use - exists for backwards compatibility with 2.1.x only. Will be removed in 2.3.
@interface SBJsonParser (Private)
- (id)fragmentWithString:(id)repr;
@end
| 009-20120511-zi | trunk/Zinipad/JSON/SBJsonParser.h | Objective-C | gpl3 | 3,083 |
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
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 the author 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.
*/
#import <Foundation/Foundation.h>
/**
@brief Adds JSON parsing methods to NSString
This is a category on NSString that adds methods for parsing the target string.
*/
@interface NSString (NSString_SBJSON)
/**
@brief Returns the object represented in the receiver, or nil on error.
Returns a a scalar object represented by the string's JSON fragment representation.
@deprecated Given we bill ourselves as a "strict" JSON library, this method should be removed.
*/
- (id)JSONFragmentValue;
/**
@brief Returns the NSDictionary or NSArray represented by the current string's JSON representation.
Returns the dictionary or array represented in the receiver, or nil on error.
Returns the NSDictionary or NSArray represented by the current string's JSON representation.
*/
- (id)JSONValue;
@end
| 009-20120511-zi | trunk/Zinipad/JSON/NSString+SBJSON.h | Objective-C | gpl3 | 2,326 |
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
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 the author 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.
*/
#import "SBJsonParser.h"
@interface SBJsonParser ()
- (BOOL)scanValue:(NSObject **)o;
- (BOOL)scanRestOfArray:(NSMutableArray **)o;
- (BOOL)scanRestOfDictionary:(NSMutableDictionary **)o;
- (BOOL)scanRestOfNull:(NSNull **)o;
- (BOOL)scanRestOfFalse:(NSNumber **)o;
- (BOOL)scanRestOfTrue:(NSNumber **)o;
- (BOOL)scanRestOfString:(NSMutableString **)o;
// Cannot manage without looking at the first digit
- (BOOL)scanNumber:(NSNumber **)o;
- (BOOL)scanHexQuad:(unichar *)x;
- (BOOL)scanUnicodeChar:(unichar *)x;
- (BOOL)scanIsAtEnd;
@end
#define skipWhitespace(c) while (isspace(*c)) c++
#define skipDigits(c) while (isdigit(*c)) c++
@implementation SBJsonParser
static char ctrl[0x22];
+ (void)initialize {
ctrl[0] = '\"';
ctrl[1] = '\\';
for (int i = 1; i < 0x20; i++)
ctrl[i+1] = i;
ctrl[0x21] = 0;
}
/**
@deprecated This exists in order to provide fragment support in older APIs in one more version.
It should be removed in the next major version.
*/
- (id)fragmentWithString:(id)repr {
[self clearErrorTrace];
if (!repr) {
[self addErrorWithCode:EINPUT description:@"Input was 'nil'"];
return nil;
}
depth = 0;
c = [repr UTF8String];
id o;
if (![self scanValue:&o]) {
return nil;
}
// We found some valid JSON. But did it also contain something else?
if (![self scanIsAtEnd]) {
[self addErrorWithCode:ETRAILGARBAGE description:@"Garbage after JSON"];
return nil;
}
NSAssert1(o, @"Should have a valid object from %@", repr);
return o;
}
- (id)objectWithString:(NSString *)repr {
id o = [self fragmentWithString:repr];
if (!o)
return nil;
// Check that the object we've found is a valid JSON container.
if (![o isKindOfClass:[NSDictionary class]] && ![o isKindOfClass:[NSArray class]]) {
[self addErrorWithCode:EFRAGMENT description:@"Valid fragment, but not JSON"];
return nil;
}
return o;
}
/*
In contrast to the public methods, it is an error to omit the error parameter here.
*/
- (BOOL)scanValue:(NSObject **)o
{
skipWhitespace(c);
switch (*c++) {
case '{':
return [self scanRestOfDictionary:(NSMutableDictionary **)o];
break;
case '[':
return [self scanRestOfArray:(NSMutableArray **)o];
break;
case '"':
return [self scanRestOfString:(NSMutableString **)o];
break;
case 'f':
return [self scanRestOfFalse:(NSNumber **)o];
break;
case 't':
return [self scanRestOfTrue:(NSNumber **)o];
break;
case 'n':
return [self scanRestOfNull:(NSNull **)o];
break;
case '-':
case '0'...'9':
c--; // cannot verify number correctly without the first character
return [self scanNumber:(NSNumber **)o];
break;
case '+':
[self addErrorWithCode:EPARSENUM description: @"Leading + disallowed in number"];
return NO;
break;
case 0x0:
[self addErrorWithCode:EEOF description:@"Unexpected end of string"];
return NO;
break;
default:
[self addErrorWithCode:EPARSE description: @"Unrecognised leading character"];
return NO;
break;
}
NSAssert(0, @"Should never get here");
return NO;
}
- (BOOL)scanRestOfTrue:(NSNumber **)o
{
if (!strncmp(c, "rue", 3)) {
c += 3;
*o = [NSNumber numberWithBool:YES];
return YES;
}
[self addErrorWithCode:EPARSE description:@"Expected 'true'"];
return NO;
}
- (BOOL)scanRestOfFalse:(NSNumber **)o
{
if (!strncmp(c, "alse", 4)) {
c += 4;
*o = [NSNumber numberWithBool:NO];
return YES;
}
[self addErrorWithCode:EPARSE description: @"Expected 'false'"];
return NO;
}
- (BOOL)scanRestOfNull:(NSNull **)o {
if (!strncmp(c, "ull", 3)) {
c += 3;
*o = [NSNull null];
return YES;
}
[self addErrorWithCode:EPARSE description: @"Expected 'null'"];
return NO;
}
- (BOOL)scanRestOfArray:(NSMutableArray **)o {
if (maxDepth && ++depth > maxDepth) {
[self addErrorWithCode:EDEPTH description: @"Nested too deep"];
return NO;
}
*o = [NSMutableArray arrayWithCapacity:8];
for (; *c ;) {
id v;
skipWhitespace(c);
if (*c == ']' && c++) {
depth--;
return YES;
}
if (![self scanValue:&v]) {
[self addErrorWithCode:EPARSE description:@"Expected value while parsing array"];
return NO;
}
[*o addObject:v];
skipWhitespace(c);
if (*c == ',' && c++) {
skipWhitespace(c);
if (*c == ']') {
[self addErrorWithCode:ETRAILCOMMA description: @"Trailing comma disallowed in array"];
return NO;
}
}
}
[self addErrorWithCode:EEOF description: @"End of input while parsing array"];
return NO;
}
- (BOOL)scanRestOfDictionary:(NSMutableDictionary **)o
{
if (maxDepth && ++depth > maxDepth) {
[self addErrorWithCode:EDEPTH description: @"Nested too deep"];
return NO;
}
*o = [NSMutableDictionary dictionaryWithCapacity:7];
for (; *c ;) {
id k, v;
skipWhitespace(c);
if (*c == '}' && c++) {
depth--;
return YES;
}
if (!(*c == '\"' && c++ && [self scanRestOfString:&k])) {
[self addErrorWithCode:EPARSE description: @"Object key string expected"];
return NO;
}
skipWhitespace(c);
if (*c != ':') {
[self addErrorWithCode:EPARSE description: @"Expected ':' separating key and value"];
return NO;
}
c++;
if (![self scanValue:&v]) {
NSString *string = [NSString stringWithFormat:@"Object value expected for key: %@", k];
[self addErrorWithCode:EPARSE description: string];
return NO;
}
[*o setObject:v forKey:k];
skipWhitespace(c);
if (*c == ',' && c++) {
skipWhitespace(c);
if (*c == '}') {
[self addErrorWithCode:ETRAILCOMMA description: @"Trailing comma disallowed in object"];
return NO;
}
}
}
[self addErrorWithCode:EEOF description: @"End of input while parsing object"];
return NO;
}
- (BOOL)scanRestOfString:(NSMutableString **)o
{
*o = [NSMutableString stringWithCapacity:16];
do {
// First see if there's a portion we can grab in one go.
// Doing this caused a massive speedup on the long string.
size_t len = strcspn(c, ctrl);
if (len) {
// check for
id t = [[NSString alloc] initWithBytesNoCopy:(char*)c
length:len
encoding:NSUTF8StringEncoding
freeWhenDone:NO];
if (t) {
[*o appendString:t];
[t release];
c += len;
}
}
if (*c == '"') {
c++;
return YES;
} else if (*c == '\\') {
unichar uc = *++c;
switch (uc) {
case '\\':
case '/':
case '"':
break;
case 'b': uc = '\b'; break;
case 'n': uc = '\n'; break;
case 'r': uc = '\r'; break;
case 't': uc = '\t'; break;
case 'f': uc = '\f'; break;
case 'u':
c++;
if (![self scanUnicodeChar:&uc]) {
[self addErrorWithCode:EUNICODE description: @"Broken unicode character"];
return NO;
}
c--; // hack.
break;
default:
[self addErrorWithCode:EESCAPE description: [NSString stringWithFormat:@"Illegal escape sequence '0x%x'", uc]];
return NO;
break;
}
CFStringAppendCharacters((CFMutableStringRef)*o, &uc, 1);
c++;
} else if (*c < 0x20) {
[self addErrorWithCode:ECTRL description: [NSString stringWithFormat:@"Unescaped control character '0x%x'", *c]];
return NO;
} else {
NSLog(@"should not be able to get here");
}
} while (*c);
[self addErrorWithCode:EEOF description:@"Unexpected EOF while parsing string"];
return NO;
}
- (BOOL)scanUnicodeChar:(unichar *)x
{
unichar hi, lo;
if (![self scanHexQuad:&hi]) {
[self addErrorWithCode:EUNICODE description: @"Missing hex quad"];
return NO;
}
if (hi >= 0xd800) { // high surrogate char?
if (hi < 0xdc00) { // yes - expect a low char
if (!(*c == '\\' && ++c && *c == 'u' && ++c && [self scanHexQuad:&lo])) {
[self addErrorWithCode:EUNICODE description: @"Missing low character in surrogate pair"];
return NO;
}
if (lo < 0xdc00 || lo >= 0xdfff) {
[self addErrorWithCode:EUNICODE description:@"Invalid low surrogate char"];
return NO;
}
hi = (hi - 0xd800) * 0x400 + (lo - 0xdc00) + 0x10000;
} else if (hi < 0xe000) {
[self addErrorWithCode:EUNICODE description:@"Invalid high character in surrogate pair"];
return NO;
}
}
*x = hi;
return YES;
}
- (BOOL)scanHexQuad:(unichar *)x
{
*x = 0;
for (int i = 0; i < 4; i++) {
unichar uc = *c;
c++;
int d = (uc >= '0' && uc <= '9')
? uc - '0' : (uc >= 'a' && uc <= 'f')
? (uc - 'a' + 10) : (uc >= 'A' && uc <= 'F')
? (uc - 'A' + 10) : -1;
if (d == -1) {
[self addErrorWithCode:EUNICODE description:@"Missing hex digit in quad"];
return NO;
}
*x *= 16;
*x += d;
}
return YES;
}
- (BOOL)scanNumber:(NSNumber **)o
{
const char *ns = c;
// The logic to test for validity of the number formatting is relicensed
// from JSON::XS with permission from its author Marc Lehmann.
// (Available at the CPAN: http://search.cpan.org/dist/JSON-XS/ .)
if ('-' == *c)
c++;
if ('0' == *c && c++) {
if (isdigit(*c)) {
[self addErrorWithCode:EPARSENUM description: @"Leading 0 disallowed in number"];
return NO;
}
} else if (!isdigit(*c) && c != ns) {
[self addErrorWithCode:EPARSENUM description: @"No digits after initial minus"];
return NO;
} else {
skipDigits(c);
}
// Fractional part
if ('.' == *c && c++) {
if (!isdigit(*c)) {
[self addErrorWithCode:EPARSENUM description: @"No digits after decimal point"];
return NO;
}
skipDigits(c);
}
// Exponential part
if ('e' == *c || 'E' == *c) {
c++;
if ('-' == *c || '+' == *c)
c++;
if (!isdigit(*c)) {
[self addErrorWithCode:EPARSENUM description: @"No digits after exponent"];
return NO;
}
skipDigits(c);
}
id str = [[NSString alloc] initWithBytesNoCopy:(char*)ns
length:c - ns
encoding:NSUTF8StringEncoding
freeWhenDone:NO];
[str autorelease];
if (str && (*o = [NSDecimalNumber decimalNumberWithString:str]))
return YES;
[self addErrorWithCode:EPARSENUM description: @"Failed creating decimal instance"];
return NO;
}
- (BOOL)scanIsAtEnd
{
skipWhitespace(c);
return !*c;
}
@end
| 009-20120511-zi | trunk/Zinipad/JSON/SBJsonParser.m | Objective-C | gpl3 | 14,032 |
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
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 the author 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.
*/
#import <Foundation/Foundation.h>
/**
@brief Adds JSON generation to Foundation classes
This is a category on NSObject that adds methods for returning JSON representations
of standard objects to the objects themselves. This means you can call the
-JSONRepresentation method on an NSArray object and it'll do what you want.
*/
@interface NSObject (NSObject_SBJSON)
/**
@brief Returns a string containing the receiver encoded as a JSON fragment.
This method is added as a category on NSObject but is only actually
supported for the following objects:
@li NSDictionary
@li NSArray
@li NSString
@li NSNumber (also used for booleans)
@li NSNull
@deprecated Given we bill ourselves as a "strict" JSON library, this method should be removed.
*/
- (NSString *)JSONFragment;
/**
@brief Returns a string containing the receiver encoded in JSON.
This method is added as a category on NSObject but is only actually
supported for the following objects:
@li NSDictionary
@li NSArray
*/
- (NSString *)JSONRepresentation;
@end
| 009-20120511-zi | trunk/Zinipad/JSON/NSObject+SBJSON.h | Objective-C | gpl3 | 2,561 |
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
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 the author 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.
*/
#import <Foundation/Foundation.h>
#import "SBJsonBase.h"
/**
@brief Options for the writer class.
This exists so the SBJSON facade can implement the options in the writer without having to re-declare them.
*/
@protocol SBJsonWriter
/**
@brief Whether we are generating human-readable (multiline) JSON.
Set whether or not to generate human-readable JSON. The default is NO, which produces
JSON without any whitespace. (Except inside strings.) If set to YES, generates human-readable
JSON with linebreaks after each array value and dictionary key/value pair, indented two
spaces per nesting level.
*/
@property BOOL humanReadable;
/**
@brief Whether or not to sort the dictionary keys in the output.
If this is set to YES, the dictionary keys in the JSON output will be in sorted order.
(This is useful if you need to compare two structures, for example.) The default is NO.
*/
@property BOOL sortKeys;
/**
@brief Return JSON representation (or fragment) for the given object.
Returns a string containing JSON representation of the passed in value, or nil on error.
If nil is returned and @p error is not NULL, @p *error can be interrogated to find the cause of the error.
@param value any instance that can be represented as a JSON fragment
*/
- (NSString*)stringWithObject:(id)value;
@end
/**
@brief The JSON writer class.
Objective-C types are mapped to JSON types in the following way:
@li NSNull -> Null
@li NSString -> String
@li NSArray -> Array
@li NSDictionary -> Object
@li NSNumber (-initWithBool:) -> Boolean
@li NSNumber -> Number
In JSON the keys of an object must be strings. NSDictionary keys need
not be, but attempting to convert an NSDictionary with non-string keys
into JSON will throw an exception.
NSNumber instances created with the +initWithBool: method are
converted into the JSON boolean "true" and "false" values, and vice
versa. Any other NSNumber instances are converted to a JSON number the
way you would expect.
*/
@interface SBJsonWriter : SBJsonBase <SBJsonWriter> {
@private
BOOL sortKeys, humanReadable;
}
@end
// don't use - exists for backwards compatibility. Will be removed in 2.3.
@interface SBJsonWriter (Private)
- (NSString*)stringWithFragment:(id)value;
@end
/**
@brief Allows generation of JSON for otherwise unsupported classes.
If you have a custom class that you want to create a JSON representation for you can implement
this method in your class. It should return a representation of your object defined
in terms of objects that can be translated into JSON. For example, a Person
object might implement it like this:
@code
- (id)jsonProxyObject {
return [NSDictionary dictionaryWithObjectsAndKeys:
name, @"name",
phone, @"phone",
email, @"email",
nil];
}
@endcode
*/
@interface NSObject (SBProxyForJson)
- (id)proxyForJson;
@end
| 009-20120511-zi | trunk/Zinipad/JSON/SBJsonWriter.h | Objective-C | gpl3 | 4,416 |
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
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 the author 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.
*/
#import "NSObject+SBJSON.h"
#import "SBJsonWriter.h"
@implementation NSObject (NSObject_SBJSON)
- (NSString *)JSONFragment {
SBJsonWriter *jsonWriter = [SBJsonWriter new];
NSString *json = [jsonWriter stringWithFragment:self];
if (!json)
NSLog(@"-JSONFragment failed. Error trace is: %@", [jsonWriter errorTrace]);
[jsonWriter release];
return json;
}
- (NSString *)JSONRepresentation {
SBJsonWriter *jsonWriter = [SBJsonWriter new];
NSString *json = [jsonWriter stringWithObject:self];
if (!json)
NSLog(@"-JSONRepresentation failed. Error trace is: %@", [jsonWriter errorTrace]);
[jsonWriter release];
return json;
}
@end
| 009-20120511-zi | trunk/Zinipad/JSON/NSObject+SBJSON.m | Objective-C | gpl3 | 2,206 |
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
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 the author 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.
*/
#import <Foundation/Foundation.h>
extern NSString * SBJSONErrorDomain;
enum {
EUNSUPPORTED = 1,
EPARSENUM,
EPARSE,
EFRAGMENT,
ECTRL,
EUNICODE,
EDEPTH,
EESCAPE,
ETRAILCOMMA,
ETRAILGARBAGE,
EEOF,
EINPUT
};
/**
@brief Common base class for parsing & writing.
This class contains the common error-handling code and option between the parser/writer.
*/
@interface SBJsonBase : NSObject {
NSMutableArray *errorTrace;
@protected
NSUInteger depth, maxDepth;
}
/**
@brief The maximum recursing depth.
Defaults to 512. If the input is nested deeper than this the input will be deemed to be
malicious and the parser returns nil, signalling an error. ("Nested too deep".) You can
turn off this security feature by setting the maxDepth value to 0.
*/
@property NSUInteger maxDepth;
/**
@brief Return an error trace, or nil if there was no errors.
Note that this method returns the trace of the last method that failed.
You need to check the return value of the call you're making to figure out
if the call actually failed, before you know call this method.
*/
@property(copy,readonly) NSArray* errorTrace;
/// @internal for use in subclasses to add errors to the stack trace
- (void)addErrorWithCode:(NSUInteger)code description:(NSString*)str;
/// @internal for use in subclasess to clear the error before a new parsing attempt
- (void)clearErrorTrace;
@end
| 009-20120511-zi | trunk/Zinipad/JSON/SBJsonBase.h | Objective-C | gpl3 | 2,946 |
//
// Util.m
// Zinipad
//
// Created by ZeLkOvA on 12. 6. 20..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import "Util.h"
#import "Reachability.h"
@implementation Util
{
}
/**
* 헥스코드를 UIColor로 변경
* @param hexValue 컬러코드 6자리
* @param alpha 투명도. 0~1
* @return UIColor로 변경된 값
*/
+(UIColor*)hex2RGB:(NSString *)hexValue andAlpha:(float)alpha
{
uint rDec;
uint gDec;
uint bDec;
NSString* r = [hexValue substringWithRange:NSMakeRange(1, 2)];
NSString* g = [hexValue substringWithRange:NSMakeRange(3, 2)];
NSString* b = [hexValue substringWithRange:NSMakeRange(5, 2)];
NSScanner* scan = [NSScanner scannerWithString:r];
[scan scanHexInt:&rDec];
scan = [NSScanner scannerWithString:g];
[scan scanHexInt:&gDec];
scan = [NSScanner scannerWithString:b];
[scan scanHexInt:&bDec];
return [UIColor colorWithRed:rDec/255.0f green:gDec/255.0f blue:bDec/255.0f alpha:alpha];
}
/**
* 현재 네트워크 접속 가능한지 체크
* @return 접속 가능 여부 BOOL 값
*/
+(BOOL)checkNetworkEnable
{
int result = [[Reachability reachabilityForInternetConnection] currentReachabilityStatus];
if(result == 0)
{
// 접속 불능
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"알림" message:@"네트워크에 접속할 수 없습니다" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return NO;
}
return YES;
}
/**
* post 방식으로 http 요청
* @param url 요청할 주소
* @param data 담겨져 보내질 데이터
* @return JSON 형식으로 넘어온 값을 NSDictionary로 변환한 값
*/
+(NSDictionary*)sendHTTPPost:(NSURL *)url sendData:(NSData *)data
{
if(![self checkNetworkEnable])
{
return nil;
}
NSString *postLength = [NSString stringWithFormat:@"%d",[data length]];;
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:data];
NSURLResponse* urlResponse = nil;
NSError* requestError;
NSData* responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError ];
NSString* jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"requestURL & Data : %@?%@", url, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
NSLog(@"returnString : %@", jsonString);
SBJSON* parser = [[SBJSON alloc] init];
NSDictionary* returnDictionary = [parser objectWithString:jsonString error:nil];
return returnDictionary;
}
/**
* post 방식으로 https 요청
* @param url 요청할 주소
* @param dataArray 담겨져 보내질 데이터 배열
* @return JSON 형식으로 넘어온 값을 NSDictionary로 변환한 값
*/
+(NSDictionary*)sendHTTPSPost:(NSURL *)url sendData:(NSArray *)dataArray
{
ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:url];
[request setValidatesSecureCertificate:NO];
for(int i = 0; i < [dataArray count] - 1; i++)
{
[request addPostValue:[dataArray objectAtIndex:i] forKey:[dataArray objectAtIndex:i+1]];
}
[request startSynchronous];
NSError* error = [request error];
NSString* responseString = [NSString string];
if(!error)
{
responseString = [request responseString];
NSLog(@"response : %@", responseString);
}
else
{
NSLog(@"error : %@", error);
}
SBJSON* parser = [[SBJSON alloc] init];
NSDictionary* returnDictionary = [parser objectWithString:responseString error:nil];
return returnDictionary;
}
/**
* get 방식으로 http 요청
* @param url 요청할 주소. 파라미터들 포함
* @return JSON 형식으로 넘어온 값을 NSDictionary로 변환한 값
*/
+(NSDictionary*)sendHTTPGetWithParameter:(NSURL*)url
{
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
[request setHTTPMethod: @"GET"];
NSError* requestError;
NSURLResponse* urlResponse = nil;
NSData* response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSString* jsonString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(@"returnString : %@", jsonString);
SBJSON* parser = [[SBJSON alloc] init];
NSDictionary* returnDictionary = [parser objectWithString:jsonString error:nil];
return returnDictionary;
}
/**
* get 방식으로 https 요청
* @param url 요청할 주소. 파라미터들 포함
* @return JSON 형식으로 넘어온 값을 NSDictionary로 변환한 값
*/
+(NSDictionary*)sendHTTPSGetWithParameter:(NSURL *)url
{
ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:url];
NSError* error = [request error];
NSString* responseString = [NSString string];
if(!error)
{
responseString = [request responseString];
NSLog(@"response : %@", responseString);
}
else
{
NSLog(@"error : %@", error);
}
SBJSON* parser = [[SBJSON alloc] init];
NSDictionary* returnDictionary = [parser objectWithString:responseString error:nil];
return returnDictionary;
}
/**
* 파일 쓰기
* @param dirName 파일 쓸 폴더 이름
* @param fileName 파일 이름
* @param data 파일에 쓸 내용
* @param isReplace 덮어씌울지 여부. NO일 경우 기존 내용 뒤에 이어서 씀
* @return 음슴
*/
+(void)writeFileAtDir:(NSString *)dirName andFileName:(NSString *)fileName andData:(NSString *)data isOverWrite:(BOOL)isReplace
{
NSString* pastData = @"";
if(isReplace == NO)
{
pastData = [self readFileAtDir:dirName andFileName:fileName];
}
NSArray* pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* docDir = [pathArray objectAtIndex:0];
NSString* dirPath = [docDir stringByAppendingPathComponent:dirName];
if(![[NSFileManager defaultManager] fileExistsAtPath:dirPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];
}
NSString* filePath = [dirPath stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
NSData* contentData = [[NSString stringWithFormat:@"%@%@", pastData, data] dataUsingEncoding:NSUTF8StringEncoding];
NSFileHandle* fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
[fileHandle writeData:contentData];
[fileHandle closeFile];
NSLog(@"file write end : %@", fileName);
}
/**
* 파일 읽기
* @param dirName 대상 폴더 이름
* @param fileName 파일 이름
* @return 파일 내용
*/
+(NSString*)readFileAtDir:(NSString *)dirName andFileName:(NSString *)fileName
{
NSArray* pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* docDir = [pathArray objectAtIndex:0];
NSString* dirPath = [docDir stringByAppendingPathComponent:dirName];
NSString* filePath = [dirPath stringByAppendingPathComponent:fileName];
NSString* fileData = [NSString string];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
fileData = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
}
else
{
NSLog(@"there is no %@", fileName);
return nil;
}
NSLog(@"file read end : %@ = %@", fileName, fileData);
return fileData;
}
/**
* 폴더에있는 파일명 리스트 요청
* @param dirName 대상 폴더 이름
* @return 파일명 리스트
*/
+(NSArray*)getFileList:(NSString*)dirName
{
NSArray* pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* docDir = [pathArray objectAtIndex:0];
NSString* dirPath = [docDir stringByAppendingPathComponent:dirName];
NSArray* fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dirPath error:NULL];
int count = [fileList count];
for(int i = 0; i < count; i++)
{
NSLog(@"%@", [fileList objectAtIndex:i]);
}
return fileList;
}
/**
* 파일 삭제
* @param dirName 대상 폴더 이름
* @param fileName 파일 이름
* @return 음슴
*/
+(void)deleteFileAtDir:(NSString*)dirName andFileName:(NSString*)fileName
{
NSArray* pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* docDir = [pathArray objectAtIndex:0];
NSString* dirPath = [docDir stringByAppendingPathComponent:dirName];
NSString* filePath = [dirPath stringByAppendingPathComponent:fileName];
if([[NSFileManager defaultManager] removeItemAtPath:filePath error:nil] != NO)
{
NSLog(@"file deleted : %@/%@", dirName, fileName);
}
else
{
NSLog(@"there is no %@/%@", dirName, fileName);
}
}
/**
* 폴더 안에있는 모든 파일 삭제
* @param dirName 대상 폴더 이름
* @return 음슴
*/
+(void)deleteAllFilesAtDir:(NSString*)dirName
{
NSArray* fileArray = [self getFileList:dirName];
int fileArrayCount = [fileArray count];
for(int i = 0; i < fileArrayCount; i++)
{
[self deleteFileAtDir:dirName andFileName:[fileArray objectAtIndex:i]];
}
}
/**
* 모달뷰 여러개 열어놨을때 가장 첫번째 모달뷰로 이동
* @param viewController 닫히기 시작하는 뷰컨트롤러 (보통 함수 호출하는 뷰컨트롤러)
* @return 음슴
*/
+(void)popModalsToFirstFrom:(UIViewController*)viewController
{
float iOSVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
if(iOSVersion >= 5.0)
{
if(viewController.presentingViewController.presentingViewController == nil)
{
return;
}
else
{
[Util popModalsToFirstFrom:viewController.presentingViewController]; // recursive call to this method
[viewController.presentingViewController dismissModalViewControllerAnimated:NO];
}
}
else
{
if(viewController.parentViewController.parentViewController == nil)
{
return;
}
else
{
[Util popModalsToFirstFrom:viewController.parentViewController]; // recursive call to this method
[viewController.parentViewController dismissModalViewControllerAnimated:NO];
}
}
}
/**
* 글자수에 따른 바이트 계산
* @param targetString 계산할 문자열
* @return 계산된 바이트 수
*/
+(int)getStringBytes:(NSString *)targetString
{
// 실제 바이트 상관없이 무조건 한글은 2, 영문/숫자는 1
int stringByte = 0;
stringByte = [targetString lengthOfBytesUsingEncoding:0x80000000 + kCFStringEncodingDOSKorean];
return stringByte;
}
/**
* 이미지 자르기
* @param targetImageName 타겟 이미지 이름
* @param targetX 잘라낼 부분의 x 시작 좌표
* @param targetY 잘라낼 부분의 y 시작 좌표
* @param targetWidth 잘라낼 부분의 가로 길이
* @param targetHeight 잘라낼 부분의 세로 길이
* @param resultX 리턴될 이미지뷰의 x위치
* @param resultY 리턴될 이미지뷰의 y위치
* @param resultWidth 리턴될 이미지뷰의 가로 길이
* @param resultHeight 리턴될 이미지뷰의 세로 길이
* @return 잘려져서 리사이즈 된 이미지뷰
*/
+(UIImageView *)cropImage:(NSString *)targetImageName targetX:(float)targetX targetY:(float)targetY targetWidth:(float)targetWidth targetHeight:(float)targetHeight resultX:(float)resultX resultY:(float)resultY resultWidth:(float)resultWidth resultHeight:(float)resultHeight
{
UIImage* image = [UIImage imageNamed:targetImageName];
UIImageView* imageView = [[UIImageView alloc] initWithImage:image];
// 잘라낼 영역
CGRect rect = CGRectMake(targetX, targetY, targetWidth, targetHeight);
// 잘라낸 부분으로 이미지 생성
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage* img = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
// 잘린이미지 화면에 출력
imageView = [[UIImageView alloc] initWithImage:img];
[imageView setFrame:CGRectMake(resultX, resultY, resultWidth, resultHeight)];
return imageView;
}
/**
* 이미지를 타일 형식으로 정해진 영역에 배치
* @param targetImageName 타겟 이미지 이름
* @param resultX 리턴될 이미지뷰의 x위치
* @param resultY 리턴될 이미지뷰의 y위치
* @param resultWidth 리턴될 이미지뷰의 가로 길이
* @param resultHeight 리턴될 이미지뷰의 세로 길이
* @return 이미지를 타일로 배치한 이미지뷰
*/
+(UIImageView *)tileImage:(NSString *)targetImageName resultX:(float)resultX resultY:(float)resultY resultWidth:(float)resultWidth resultHeight:(float)resultHeight
{
// 뷰에 이미지 타일로 배치
UIImage* image = [UIImage imageNamed:targetImageName];
UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(resultX, resultY, resultWidth, resultHeight)];
[imageView setImage:image];
CGSize imageViewSize = imageView.bounds.size;
UIGraphicsBeginImageContext(imageViewSize);
CGRect imageRect;
imageRect.origin = CGPointMake(0.0, 0.0);
imageRect.size = CGSizeMake(image.size.width, image.size.height);
CGContextRef imageContext = UIGraphicsGetCurrentContext();
CGContextScaleCTM(imageContext, 1.0f, -1.0f); // 이미지 뒤집히는거 바로잡음
CGContextDrawTiledImage(imageContext, imageRect, image.CGImage);
UIImage *finishedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
imageView.image = finishedImage;
return imageView;
}
+(NSInteger)findCategory:(int)_rootIndex sub:(int)_subIndex
{
NSInteger nCode;
if(_subIndex < 10)
nCode = [[NSString stringWithFormat:@"%d0%d",_rootIndex+1,_subIndex+1] intValue];
else
nCode = [[NSString stringWithFormat:@"%d%d",_rootIndex+1,_subIndex+1] intValue];
return nCode;
}
+(NSString*)findFloorRootCategoryName:(int)_index
{
NSString* str;
switch (_index) {
case 0:
str = @"마루";
break;
case 1:
str = @"시트";
break;
case 2:
str = @"타일";
break;
case 3:
str = @"타일";
break;
case 4:
str = @"시트";
break;
case 5:
str = @"카펫타일";
break;
case 6:
str = @"스톤타일";
break;
default:
break;
}
return str;
}
+(NSString*)findWallpaperRootCategoryName:(int)_index
{
NSString* str;
switch (_index) {
case 0:
str = @"프리미엄벽지";
break;
case 1:
str = @"실크벽지";
break;
case 2:
str = @"합지벽지";
break;
case 3:
str = @"벽타일";
break;
default:
break;
}
return str;
}
//-(UIImage*)CropImage:(UIBezierPath *)trackPath{
// CGContextRef mainViewContentContext;
// CGColorSpaceRef colorSpace;
//
// colorSpace = CGColorSpaceCreateDeviceRGB();
//
// // create a bitmap graphics context the size of the image
// mainViewContentContext = CGBitmapContextCreate(NULL, aImgView.frame.size.width, aImgView.frame.size.height, 8, aImgView.frame.size.width*4, colorSpace, kCGImageAlphaPremultipliedLast);
//
// // free the rgb colorspace
// CGColorSpaceRelease(colorSpace);
//
// //Translate and scale image
// CGContextTranslateCTM(mainViewContentContext, 0, aImgView.frame.size.height);
// CGContextScaleCTM(mainViewContentContext, 1.0, -1.0);
//
// //the mask
// CGContextAddPath(mainViewContentContext, trackPath.CGPath);
// CGContextClip(mainViewContentContext);
//
// //Translate and scale image
// CGContextTranslateCTM(mainViewContentContext, 0, aImgView.frame.size.height);
// CGContextScaleCTM(mainViewContentContext, 1.0, -1.0);
//
// //the main image
// CGContextDrawImage(mainViewContentContext, CGRectMake(0, 0, aImgView.frame.size.width, aImgView.frame.size.height), aImgView.image.CGImage);
//
// //the outline
// CGContextSetLineWidth(mainViewContentContext, 1);
// CGContextSetRGBStrokeColor(mainViewContentContext, 181.0/256, 181.0/256, 181.0/256, 1.0);
//
// // Create CGImageRef of the main view bitmap content, and then
// // release that bitmap context
// CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(mainViewContentContext);
// CGContextRelease(mainViewContentContext);
//
// // convert the finished resized image to a UIImage
// UIImage *newImage = [UIImage imageWithCGImage:mainViewContentBitmapContext];
//
// // image is retained by the property setting above, so we can
// // release the original
// CGImageRelease(mainViewContentBitmapContext);
//
// return newImage;
//}
//
@end
| 009-20120511-zi | trunk/Zinipad/Util.m | Objective-C | gpl3 | 17,965 |
//
// SmartCounselMainView.m
// Zinipad
//
// Created by ZeLkOvA on 12. 5. 24..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import "SmartCounselMainView.h"
#import "ZinMainViewController.h"
#import "SmartCounselRecordView.h"
#import "DatabaseManager.h"
@interface SmartCounselMainView ()
@end
@implementation SmartCounselMainView
@synthesize counselList;
@synthesize scrollView;
@synthesize PopupCustomerInfo;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self topMenuView];
[self leftMenuView];
[self ResultViewTopMenu];
self.counselList = [NSMutableArray array];
self.counselList = [DatabaseManager customerList];
SelectIndex = 0;
if([self.counselList count] == 0)
{
// UILabel* buttonSubLabel = [[UILabel alloc] init];
// [buttonSubLabel setTextAlignment:UITextAlignmentCenter];
// [buttonSubLabel setTextColor:[UIColor whiteColor]];
// [buttonSubLabel setFont:[UIFont systemFontOfSize:12.0f]];
// [buttonSubLabel setBackgroundColor:[UIColor clearColor]];
}
else
{
[self ResultMainView];
NSLog(@"%d",[self.counselList count]);
}
}
-(void)topMenuView
{
[self.view setBackgroundColor:[UIColor blackColor]];
UIButton* zinButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[zinButton setFrame:CGRectMake(10,10 ,100, 36)];
[zinButton setTitle:[NSString stringWithFormat:@"Z:IN"] forState:UIControlStateNormal];
[zinButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[zinButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[zinButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[zinButton addTarget:self action:@selector(zinButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:zinButton];
UIButton* zinSampleBookButton = [UIButton buttonWithType:UIButtonTypeCustom];
[zinSampleBookButton setFrame:CGRectMake(250,10 ,130, 36)];
[zinSampleBookButton setTitle:[NSString stringWithFormat:@"Z:IN 샘플북"] forState:UIControlStateNormal];
[zinSampleBookButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[zinSampleBookButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[zinSampleBookButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[zinSampleBookButton addTarget:self action:@selector(zinSampleBookButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:zinSampleBookButton];
UIButton* smartCounselButton = [UIButton buttonWithType:UIButtonTypeCustom];
[smartCounselButton setFrame:CGRectMake(380,10 ,150, 36)];
[smartCounselButton setTitle:[NSString stringWithFormat:@"Smart 삼담기록"] forState:UIControlStateNormal];
[smartCounselButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[smartCounselButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[smartCounselButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[smartCounselButton addTarget:self action:@selector(smartCounselButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:smartCounselButton];
UIButton* mBrochureButton = [UIButton buttonWithType:UIButtonTypeCustom];
[mBrochureButton setFrame:CGRectMake(550,10 ,130, 36)];
[mBrochureButton setTitle:[NSString stringWithFormat:@"M 브로셔"] forState:UIControlStateNormal];
[mBrochureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[mBrochureButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[mBrochureButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[mBrochureButton addTarget:self action:@selector(mBrochureButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:mBrochureButton];
UIButton* MatchingButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[MatchingButton setFrame:CGRectMake(1024-70*4,10, 70, 36)];
[MatchingButton setTitle:[NSString stringWithFormat:@"매칭하기"] forState:UIControlStateNormal];
[MatchingButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[MatchingButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[MatchingButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[MatchingButton addTarget:self action:@selector(MatchingButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:MatchingButton];
UIButton* CalButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[CalButton setFrame:CGRectMake(1024-70*3,10 , 70, 36)];
[CalButton setTitle:[NSString stringWithFormat:@"소요량계산"] forState:UIControlStateNormal];
[CalButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[CalButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[CalButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[CalButton addTarget:self action:@selector(CalButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:CalButton];
UIButton* SetButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[SetButton setFrame:CGRectMake(1024-70*2,10 , 70, 36)];
[SetButton setTitle:[NSString stringWithFormat:@"설정"] forState:UIControlStateNormal];
[SetButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[SetButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[SetButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[SetButton addTarget:self action:@selector(SetButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:SetButton];
UIButton* HelpButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[HelpButton setFrame:CGRectMake(1024-70, 10, 70, 36)];
[HelpButton setTitle:[NSString stringWithFormat:@"HELP"] forState:UIControlStateNormal];
[HelpButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[HelpButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[HelpButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[HelpButton addTarget:self action:@selector(HelpButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:HelpButton];
}
-(void)zinButtonPressed:(id)sender
{
ZinMainViewController* zinMainViewController = [[ZinMainViewController alloc] init];
[self.navigationController pushViewController:zinMainViewController animated:YES];
}
-(void)zinSampleBookButtonPressed:(id)sender
{
}
-(void)smartCounselButtonPressed:(id)sender
{
}
-(void)mBrochureButtonPressed:(id)sender
{
}
-(void)leftMenuView
{
UILabel* SmartCounselLb = [[UILabel alloc] initWithFrame:CGRectMake(40, 80, 140, 40)];
[SmartCounselLb setTextColor:[UIColor colorWithRed:0.36f green:0.36f blue:0.36f alpha:1.0f]];
[SmartCounselLb setBackgroundColor:[UIColor whiteColor]];
[SmartCounselLb setLineBreakMode:UILineBreakModeWordWrap];
[SmartCounselLb setText:@"Smart 상담기록"];
[self.view addSubview:SmartCounselLb];
UIButton* CounselRecordWatchButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[CounselRecordWatchButton setFrame:CGRectMake(30,150,160,40)];
[CounselRecordWatchButton setTitle:[NSString stringWithFormat:@"상담기록보기"] forState:UIControlStateNormal];
[CounselRecordWatchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[CounselRecordWatchButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[CounselRecordWatchButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[CounselRecordWatchButton addTarget:self action:@selector(CounselRecordWatchButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:CounselRecordWatchButton];
UIButton* CounselRecordButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[CounselRecordButton setFrame:CGRectMake(30,210,160,40)];
[CounselRecordButton setTitle:[NSString stringWithFormat:@"상담기록하기"] forState:UIControlStateNormal];
[CounselRecordButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[CounselRecordButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[CounselRecordButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[CounselRecordButton addTarget:self action:@selector(CounselRecordButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:CounselRecordButton];
UIButton* CounselRecordShareButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[CounselRecordShareButton setFrame:CGRectMake(30,270,160,40)];
[CounselRecordShareButton setTitle:[NSString stringWithFormat:@"상담내용공유하기"] forState:UIControlStateNormal];
[CounselRecordShareButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[CounselRecordShareButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[CounselRecordShareButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[CounselRecordShareButton addTarget:self action:@selector(CounselRecordShareButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:CounselRecordShareButton];
}
-(void)CounselRecordWatchButtonPressed:(id)sender
{
}
-(void)CounselRecordButtonPressed:(id)sender
{
SmartCounselRecordView* smartCounselRecordView = [[SmartCounselRecordView alloc] init];
[self.navigationController pushViewController:smartCounselRecordView animated:YES];
}
-(void)CounselRecordShareButtonPressed:(id)sender
{
}
-(void)ResultViewTopMenu
{
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(buttonLongPressed:)];
longPress.minimumPressDuration = 0.5;
UIButton* RegistrationFirstButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[RegistrationFirstButton setFrame:CGRectMake(250,80,100,40)];
[RegistrationFirstButton setTitle:[NSString stringWithFormat:@"등록순"] forState:UIControlStateNormal];
[RegistrationFirstButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[RegistrationFirstButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[RegistrationFirstButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[RegistrationFirstButton addTarget:self action:@selector(RegistrationFirstButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:RegistrationFirstButton];
UIButton* NameFirstButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[NameFirstButton setFrame:CGRectMake(370,80,100,40)];
[NameFirstButton setTitle:[NSString stringWithFormat:@"이름순"] forState:UIControlStateNormal];
[NameFirstButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[NameFirstButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[NameFirstButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[NameFirstButton addTarget:self action:@selector(NameFirstButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:NameFirstButton];
}
-(void)RegistrationFirstButtonPressed:(id)sender
{
}
-(void)NameFirstButtonPressed:(id)sender
{
}
-(void)ResultMainView
{
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(250, 130, 1024-270, 748-160)];
[scrollView setBackgroundColor:[UIColor whiteColor]];
int buttonWidth = 130;
int buttonHeight = 130;
int buttonMarignRight = 40;
int buttonMarginBottom = 65;
int rowCount = scrollView.frame.size.width / (buttonWidth + buttonMarignRight );
int buttonX = 0;
int buttonY = 0;
[scrollView setContentSize:CGSizeMake(scrollView.frame.size.width, (buttonHeight + buttonMarginBottom) * (int)ceil([self.counselList count] / (float)rowCount))];
// NSLog(@"%d", (buttonHeight + buttonMarginBottom) * (int)ceil(_xmlNodeCountArray.count / (float)rowCount));
for(int i = 0; i < [self.counselList count]; i++)
{
// NSString* pageThumbImg = [NSString stringWithFormat:@"img_project_b_file.png"];
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(buttonLongPressed:)];
longPress.minimumPressDuration = 0.5;
NSMutableDictionary* Datadic = [NSMutableDictionary dictionary];
Datadic = [self.counselList objectAtIndex:i];
NSString* pageTitle = [Datadic objectForKey:@"C_name"];
UIButton *eventButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonX = (i % rowCount) * (buttonWidth + buttonMarignRight) + 40;
buttonY = (buttonHeight + buttonMarginBottom) * (i / rowCount) + 31;
[eventButton setTag:i];
[eventButton addGestureRecognizer:longPress];
UILabel* DateLb = [[UILabel alloc] initWithFrame:CGRectMake(5, 80,buttonWidth-10, 20)];
[DateLb setTextColor:[UIColor colorWithRed:0.36f green:0.36f blue:0.36f alpha:1.0f]];
[DateLb setText:[Datadic objectForKey:@"C_date"]];
[DateLb setBackgroundColor:[UIColor clearColor]];
[DateLb setTextAlignment:UITextAlignmentCenter];
[eventButton addSubview:DateLb];
UILabel* TimeLb = [[UILabel alloc] initWithFrame:CGRectMake(5, 100,buttonWidth-10, 20)];
[TimeLb setTextColor:[UIColor colorWithRed:0.36f green:0.36f blue:0.36f alpha:1.0f]];
[TimeLb setText:[Datadic objectForKey:@"C_time"]];
[TimeLb setBackgroundColor:[UIColor clearColor]];
[TimeLb setTextAlignment:UITextAlignmentCenter];
[eventButton addSubview:TimeLb];
[eventButton setFrame:CGRectMake(buttonX, buttonY, buttonWidth, buttonHeight)];
[eventButton setTitle:pageTitle forState:UIControlStateNormal];
// [eventButton setBackgroundImage:[UIImage imageNamed:pageThumbImg] forState:UIControlStateNormal];
[eventButton addTarget:self action:@selector(/*버튼눌렀을때실행될핸들러함수*/projectButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[eventButton setContentEdgeInsets:UIEdgeInsetsMake(-30, 0, 0, 0)]; // 중앙이 원점으로 텍스트위치 (top, left, bottom, right)
[eventButton.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
[scrollView addSubview:eventButton];
}
[self.view addSubview:scrollView];
}
- (void)buttonLongPressed:(UILongPressGestureRecognizer *)sender
{
// NSLog(@"LongPress!!!!!");
if(sender.state == UIGestureRecognizerStateBegan)
{
NSLog(@"LongPress!!!!!");
NSLog(@"%d",sender.view.tag);
}
}
-(void)projectButtonPressed:(id)sender
{
SelectIndex = [sender tag];
NSMutableDictionary* Data = [NSMutableDictionary dictionary];
if([self.counselList count] == 0)
{
NSLog(@"없음");
}
NSLog(@"%d",[self.counselList count] );
Data = [self.counselList objectAtIndex:SelectIndex];
PopupCustomerInfo = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 1024, 748)];
[PopupCustomerInfo setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:PopupCustomerInfo];
// UIImage* backgroundImg = [UIImage imageNamed:@"a.png"];
// UIImageView* backgroundImgView = [[UIImageView alloc] initWithImage:backgroundImg];
// [backgroundImgView setFrame:CGRectMake(400, 160, 500, 530)];
// [PopupCustomerInfo addSubview:backgroundImgView];
UIView* temp = [[UIView alloc]initWithFrame:CGRectMake(400, 160, 500, 530)];
[temp setBackgroundColor:[UIColor grayColor]];
[PopupCustomerInfo addSubview:temp];
UILabel* TitleNameLb = [[UILabel alloc] initWithFrame:CGRectMake(150, 10, 80, 40)];
[TitleNameLb setTextColor:[UIColor colorWithRed:0.36f green:0.36f blue:0.36f alpha:1.0f]];
NSString* pageTitle = [Data objectForKey:@"C_name"];
[TitleNameLb setText:pageTitle];
[TitleNameLb setFont:[UIFont systemFontOfSize:20]];
[TitleNameLb setBackgroundColor:[UIColor clearColor]];
[TitleNameLb setTextAlignment:UITextAlignmentCenter];
[temp addSubview:TitleNameLb];
UILabel* NameLb = [[UILabel alloc] initWithFrame:CGRectMake(200, 50, 80, 40)];
[NameLb setTextColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
[NameLb setText:pageTitle];
[NameLb setFont:[UIFont systemFontOfSize:20]];
[NameLb setBackgroundColor:[UIColor clearColor]];
[NameLb setTextAlignment:UITextAlignmentCenter];
[temp addSubview:NameLb];
UILabel* PhoneLb = [[UILabel alloc] initWithFrame:CGRectMake(200, 80, 200, 40)];
[PhoneLb setTextColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
[PhoneLb setText:[Data objectForKey:@"C_phone"]];
[PhoneLb setFont:[UIFont systemFontOfSize:20]];
[PhoneLb setBackgroundColor:[UIColor clearColor]];
[PhoneLb setTextAlignment:UITextAlignmentCenter];
[temp addSubview:PhoneLb];
UILabel* MailLb = [[UILabel alloc] initWithFrame:CGRectMake(200, 110, 200, 40)];
[MailLb setTextColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
[MailLb setText:[Data objectForKey:@"C_mail"]];
[MailLb setFont:[UIFont systemFontOfSize:20]];
[MailLb setBackgroundColor:[UIColor clearColor]];
[MailLb setTextAlignment:UITextAlignmentCenter];
[temp addSubview:MailLb];
UILabel* ExpenseLb = [[UILabel alloc] initWithFrame:CGRectMake(200, 140, 200, 40)];
[ExpenseLb setTextColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
[ExpenseLb setText:[Data objectForKey:@"C_expanse"]];
[ExpenseLb setFont:[UIFont systemFontOfSize:20]];
[ExpenseLb setBackgroundColor:[UIColor clearColor]];
[ExpenseLb setTextAlignment:UITextAlignmentCenter];
[temp addSubview:ExpenseLb];
UILabel* MemoLb = [[UILabel alloc] initWithFrame:CGRectMake(200, 170, 200, 40)];
[MemoLb setTextColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
[MemoLb setText:[Data objectForKey:@"C_memo"]];
[MemoLb setFont:[UIFont systemFontOfSize:20]];
[MemoLb setBackgroundColor:[UIColor clearColor]];
[MemoLb setTextAlignment:UITextAlignmentCenter];
[temp addSubview:MemoLb];
UILabel* CounselItemLb = [[UILabel alloc] initWithFrame:CGRectMake(200, 200, 200, 40)];
[CounselItemLb setTextColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
[CounselItemLb setText:[Data objectForKey:@"C_item"]];
[CounselItemLb setFont:[UIFont systemFontOfSize:20]];
[CounselItemLb setBackgroundColor:[UIColor clearColor]];
[CounselItemLb setTextAlignment:UITextAlignmentCenter];
[temp addSubview:CounselItemLb];
NSArray* itemWallpaperList = [[NSArray alloc] init];
itemWallpaperList = [DatabaseManager spliteString:[Data objectForKey:@"C_wallPaperImgName"]];
NSArray* itemFlooringList = [[NSArray alloc] init];
itemFlooringList = [DatabaseManager spliteString:[Data objectForKey:@"C_FlooringImgName"]];
NSMutableArray* itemList = [[NSMutableArray alloc] init];
for(int i = 0;i<[itemWallpaperList count];i++)
{
[itemList addObject:[itemWallpaperList objectAtIndex:i]];
}
for(int i = 0;i<[itemFlooringList count];i++)
{
[itemList addObject:[itemFlooringList objectAtIndex:i]];
}
[self PopupImgitemView:itemList view:temp];
UIButton* PopupModifyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[PopupModifyButton setFrame:CGRectMake(500-100, 10, 50, 40)];
[PopupModifyButton setTitle:[NSString stringWithFormat:@"수정"] forState:UIControlStateNormal];
[PopupModifyButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[PopupModifyButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[PopupModifyButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[PopupModifyButton addTarget:self action:@selector(PopupModifyButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[temp addSubview:PopupModifyButton];
UIButton* PopupBackButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[PopupBackButton setFrame:CGRectMake(500-50, 10, 40, 40)];
[PopupBackButton setTitle:[NSString stringWithFormat:@"X"] forState:UIControlStateNormal];
[PopupBackButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[PopupBackButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[PopupBackButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 5)];
[PopupBackButton addTarget:self action:@selector(PopupBackButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[temp addSubview:PopupBackButton];
}
-(void)PopupImgitemView:(NSMutableArray*)_list view:(UIView*)_tempView
{
UIScrollView* itemScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(20, 340, 450, 170)];
[itemScroll setBackgroundColor:[UIColor whiteColor]];
int buttonWidth = 100;
int buttonHeight = 50;
int buttonMarignRight = 40;
int buttonMarginBottom = 45;
int rowCount = itemScroll.frame.size.width / (buttonWidth + buttonMarignRight );
int buttonX = 0;
int buttonY = 0;
[itemScroll setContentSize:CGSizeMake(itemScroll.frame.size.width, (buttonHeight + buttonMarginBottom) * (int)ceil([_list count] / (float)rowCount))];
for(int i = 0; i < [_list count]; i++)
{
UIImage* imgList = [UIImage imageNamed:[_list objectAtIndex:i]];
buttonX = (i % rowCount) * (buttonWidth + buttonMarignRight) + 40;
buttonY = (buttonHeight + buttonMarginBottom) * (i / rowCount) + 10;
UIImageView* imgListView = [[UIImageView alloc] initWithImage:imgList];
[imgListView setFrame:CGRectMake(buttonX, buttonY, buttonWidth, buttonHeight)];
[itemScroll addSubview:imgListView];
}
[_tempView addSubview:itemScroll];
}
-(void)PopupModifyButtonPressed:(id)sender
{
}
-(void)PopupBackButtonPressed:(id)sender
{
[PopupCustomerInfo removeFromSuperview];
[PopupCustomerInfo release];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
-(void)dealloc
{
[super dealloc];
// [DatabaseManager closeDatabse];
// [counselList release];
}
@end
| 009-20120511-zi | trunk/Zinipad/SmartCounselMainView.m | Objective-C | gpl3 | 23,290 |
//
// SampleBookViewFlooring.m
// Zinipad
//
// Created by ZeLkOvA on 12. 5. 23..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import "SampleBookViewFlooring.h"
#import "iCarousel.h"
#import "Util.h"
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define NUMBER_OF_ITEMS 6
#define NUMBER_OF_VISIBLE_ITEMS (IS_IPAD? 5: 19)
#define ITEM_SPACING 320.0f
#define INCLUDE_PLACEHOLDERS YES
#define SIZE_TOPBAR 60.0f
@interface SampleBookViewFlooring ()<UIActionSheetDelegate>
@property (nonatomic, assign) BOOL wrap;
@property (nonatomic, retain) NSMutableArray *items;
@end
@implementation SampleBookViewFlooring
@synthesize carousel;
@synthesize wrap;
@synthesize items;
@synthesize imgArray;
@synthesize floorList;
- (void)setUpImg
{
//set up data
wrap = YES;
self.items = [NSMutableArray array];
imgArray = [[NSMutableArray alloc] init];
// 이미지 가져와서 저장하기
[imgArray addObject:@"x.png"];
[imgArray addObject:@"y.png"];
[imgArray addObject:@"z.png"];
[imgArray addObject:@"x.png"];
[imgArray addObject:@"y.png"];
[imgArray addObject:@"z.png"];
[imgArray addObject:@"x.png"];
[imgArray addObject:@"y.png"];
[imgArray addObject:@"z.png"];
[imgArray addObject:@"x.png"];
[imgArray addObject:@"y.png"];
[imgArray addObject:@"z.png"];
[imgArray addObject:@"x.png"];
[imgArray addObject:@"y.png"];
[imgArray addObject:@"z.png"];
[imgArray addObject:@"x.png"];
[imgArray addObject:@"y.png"];
[imgArray addObject:@"z.png"];
[imgArray addObject:@"x.png"];
[imgArray addObject:@"y.png"];
[imgArray addObject:@"z.png"];
[imgArray addObject:@"x.png"];
[imgArray addObject:@"y.png"];
[imgArray addObject:@"z.png"];
[imgArray addObject:@"x.png"];
[imgArray addObject:@"y.png"];
[imgArray addObject:@"z.png"];
[imgArray addObject:@"x.png"];
[imgArray addObject:@"y.png"];
[imgArray addObject:@"z.png"];
[imgArray addObject:@"x.png"];
[imgArray addObject:@"y.png"];
[imgArray addObject:@"z.png"];
[imgArray addObject:@"x.png"];
[imgArray addObject:@"y.png"];
[imgArray addObject:@"z.png"];
// }
self.items = imgArray;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
[self setUpImg];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self InitCarousel];
[self InitFloorList];
// Do any additional setup after loading the view.
}
-(void)InitCarousel
{
NSLog(@"HOHOHOHO");
// count = 0;
carousel = [[iCarousel alloc] init];
[carousel setFrame:CGRectMake(0,0,1024-188-188/2,600-SIZE_TOPBAR)];
[self.view addSubview:carousel];
carousel.delegate = self;
carousel.dataSource = self;
//configure carousel
carousel.type = iCarouselTypeCoverFlow;
// navItem.title = @"CoverFlow2";
// carousel.vertical = !carousel.vertical;
}
-(void)InitFloorList
{
// carouselColor
floorList = [[iCarouselColor alloc] init];
[floorList setFrame:CGRectMake(80,500,600,200)];
floorList.dataSourceColor = self;
floorList.delegate = self;
[self.view addSubview:floorList];
// carouselColor.delegate = self;
// carouselColor.dataSourceColor = self;
floorList.type = iCarouselFloorTypeLinear;
// floorList.vertical = !floorList.vertical;
// ColorView = [[SampleBookColorViewWallpaper alloc] init];
// [ColorView.view setFrame:CGRectMake(40,100,150,300)];
// [self.view addSubview:ColorView.view];
}
- (void)carouselCurrnetImgIndex:(int)_imgIndex;
{
NSLog(@"ImgIndex == %d",_imgIndex);
// [floorList scrollToItemAtIndex:_imgIndex animated:YES];
// UIImage* tileBGImage = [UIImage imageNamed:[imgArray objectAtIndex:_imgIndex]];
// [detailImageView setImage:tileBGImage];
// detailImageView = [[UIImageView alloc] initWithImage:tileBGImage];
// [detailImageView setFrame:CGRectMake(50, 0, 300, 400)];
}
- (void)carouselCurrnetImgIndexColor:(int)_imgIndex;
{
NSLog(@"ImgIndexColor == %d",_imgIndex);
[carousel scrollToItemAtIndex:_imgIndex animated:YES];
// if(bFirstLoad)
// {
// bFirstLoad = NO;
// return;
// }
// if(carousel)
// {
// [carousel removeFromSuperview];
// [carousel release];
// }
// UIImage* tileBGImage = [UIImage imageNamed:[items objectAtIndex:_imgIndex]];
// [detailImageView setImage:tileBGImage];
// [self setUpImg];
// [self InitCarousel];
// [carousel scrollToItemAtIndex:_imgIndex animated:YES];
}
- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
return [items count];
}
- (NSUInteger)numberOfVisibleItemsInCarousel:(iCarousel *)carousel
{
//limit the number of items views loaded concurrently (for performance reasons)
//this also affects the appearance of circular-type carousels
return NUMBER_OF_VISIBLE_ITEMS;
}
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
if (view == nil)
{
// NSLog(@"here %d",count);
// view = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:[imgArray objectAtIndex:index]]] autorelease];
view = [[UIImageView alloc] init];
[view setFrame:CGRectMake(0, 0, 480, 400)];
UIImage* aaaa = [UIImage imageNamed:@"img_shadow.png"];
UIImageView* aaaaaaaaaaa = [[UIImageView alloc] initWithImage:aaaa];
[aaaaaaaaaaa setFrame:CGRectMake(0, 0, 480, 400)];
UIImageView* reflect = [Util cropImage:[imgArray objectAtIndex:index] targetX:0 targetY:250 targetWidth:480-27*2 targetHeight:50 resultX:25 resultY:400-40 resultWidth:480-27*2 resultHeight:50];
reflect.transform = CGAffineTransformMakeRotation(1.57*2);//Right -1.57 Left
[reflect setAlpha:0.3f];
[view addSubview:reflect];
[view addSubview:aaaaaaaaaaa];
UIImage* bbbb = [UIImage imageNamed:[imgArray objectAtIndex:index]];
UIImageView* bbbbbb = [[UIImageView alloc] initWithImage:bbbb];
[bbbbbb setFrame:CGRectMake(25, 21, 480-27*2, 400-21*2)];
[aaaaaaaaaaa addSubview:bbbbbb];
// [arView setHidden:NO];
// view.layer.doubleSided = NO; //prevent back side of view from showing
// UIImage* aaaa = [UIImage imageNamed:@"page.png"];
// UIImageView* aaaaaaaaaaa = [[UIImageView alloc] initWithImage:aaaa];
// [aaaaaaaaaaa setFrame:CGRectMake(0, 300, 400, 150)];
// [view addSubview:aaaaaaaaaaa];
// 라벨 들어갈자리 /////////////////
// UILabel* cccc =
///////////////////////
// count++;
}
else
{
view = [[UIImageView alloc] init];
[view setFrame:CGRectMake(0, 0, 480, 400)];
UIImage* aaaa = [UIImage imageNamed:@"img_shadow.png"];
UIImageView* aaaaaaaaaaa = [[UIImageView alloc] initWithImage:aaaa];
[aaaaaaaaaaa setFrame:CGRectMake(0, 0, 480, 400)];
UIImageView* reflect = [Util cropImage:[imgArray objectAtIndex:index] targetX:0 targetY:250 targetWidth:480-27*2 targetHeight:50 resultX:25 resultY:400-40 resultWidth:480-27*2 resultHeight:50];
reflect.transform = CGAffineTransformMakeRotation(1.57*2);//Right -1.57 Left
[reflect setAlpha:0.3f];
[view addSubview:reflect];
[view addSubview:aaaaaaaaaaa];
UIImage* bbbb = [UIImage imageNamed:[imgArray objectAtIndex:index]];
UIImageView* bbbbbb = [[UIImageView alloc] initWithImage:bbbb];
[bbbbbb setFrame:CGRectMake(25, 21, 480-27*2, 400-21*2)];
[aaaaaaaaaaa addSubview:bbbbbb];
}
return view;
}
- (NSUInteger)numberOfPlaceholdersInCarousel:(iCarousel *)carousel
{
//note: placeholder views are only displayed on some carousels if wrapping is disabled
return INCLUDE_PLACEHOLDERS? 2: 0;
}
- (CGFloat)carouselItemWidth:(iCarousel *)carousel
{
//usually this should be slightly wider than the item views
return ITEM_SPACING;
}
//- (CGFloat)carousel:(iCarousel *)carousel itemAlphaForOffset:(CGFloat)offset
//{
// //set opacity based on distance from camera
// return 1.0f - fminf(fmaxf(offset, 0.0f), 1.0f);
//}
//- (CATransform3D)carousel:(iCarousel *)_carousel itemTransformForOffset:(CGFloat)offset baseTransform:(CATransform3D)transform
//{
// //implement 'flip3D' style carousel
// transform = CATransform3DRotate(transform, M_PI / 8.0f, 0.0f, 1.0f, 0.0f);
// return CATransform3DTranslate(transform, 0.0f, 0.0f, offset * carousel.itemWidth);
//}
-(void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index
{
NSLog(@"%d",index);
}
- (BOOL)carouselShouldWrap:(iCarousel *)carousel
{
return wrap;
}
-(void)dealloc
{
carousel.delegate = nil;
carousel.dataSource = nil;
[carousel release];
[items release];
[super dealloc];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (NSUInteger)numberOfItemsInCarouselColor:(iCarouselColor *)carousel
{
return [items count];
}
- (NSUInteger)numberOfVisibleItemsInCarouselColor:(iCarouselColor *)carousel
{
//limit the number of items views loaded concurrently (for performance reasons)
//this also affects the appearance of circular-type carousels
return 13;
}
- (UIView *)carouselColor:(iCarouselColor *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
if (view == nil)
{
// NSLog(@"here %d",index);
view = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:[items objectAtIndex:index]]] autorelease];
[view setFrame:CGRectMake(0, 0, 70, 70)];
view.layer.doubleSided = YES; //prevent back side of view from showing
// label = [[[UILabel alloc] initWithFrame:view.bounds] autorelease];
// label.backgroundColor = [UIColor clearColor];
// label.textAlignment = UITextAlignmentCenter;
// label.font = [label.font fontWithSize:10];
// label.text = [NSString stringWithFormat:@"%d",count];
// [view addSubview:label];
// count++;
}
else
{
// NSLog(@"here %d",index);
view = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:[items objectAtIndex:index]]] autorelease];
[view setFrame:CGRectMake(0, 0, 70, 70)];
view.layer.doubleSided = YES;
}
//
return view;
}
- (NSUInteger)numberOfPlaceholdersInCarouselColor:(iCarouselColor *)carousel
{
//note: placeholder views are only displayed on some carousels if wrapping is disabled
return 0;
}
- (CGFloat)carouselItemWidthColor:(iCarouselColor *)carousel
{
//usually this should be slightly wider than the item views
return 100;
}
- (BOOL)carouselShouldWrapColor:(iCarouselColor *)carousel
{
return wrap;
}
@end
| 009-20120511-zi | trunk/Zinipad/SampleBookViewFlooring.m | Objective-C | gpl3 | 11,433 |
//
// AppDelegate.m
// Zinipad
//
// Created by ZeLkOvA on 12. 5. 17..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import "AppDelegate.h"
#import "ZinMainViewController.h"
@implementation AppDelegate
@synthesize window = _window;
@synthesize _aNavigationController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
zinMainViewController = [[ZinMainViewController alloc] init];
_aNavigationContoller = [[UINavigationController alloc] initWithRootViewController:zinMainViewController];
[_aNavigationContoller setNavigationBarHidden:YES];
self._aNavigationController = _aNavigationContoller;
[self.window addSubview:self._aNavigationController.view];
[self.window makeKeyAndVisible];
// NSLog(@"앱 델리게이트");
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
*/
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
/*
Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
*/
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
}
- (void)applicationWillTerminate:(UIApplication *)application
{
/*
Called when the application is about to terminate.
Save data if appropriate.
See also applicationDidEnterBackground:.
*/
}
@end
| 009-20120511-zi | trunk/Zinipad/AppDelegate.m | Objective-C | gpl3 | 2,767 |
//
// MyTreeViewCell.m
// MyTreeViewPrototype
//
// Created by Jon Limjap on 4/21/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "MyTreeViewCell.h"
#define IMG_HEIGHT_WIDTH 20
#define CELL_HEIGHT 50
#define SCREEN_WIDTH 188
#define LEVEL_INDENT 20
#define YOFFSET 12
#define XOFFSET 0
@interface MyTreeViewCell (Private)
- (UILabel *)newLabelWithPrimaryColor:(UIColor *)primaryColor
selectedColor:(UIColor *)selectedColor
fontSize:(CGFloat)fontSize
bold:(BOOL)bold;
@end
@implementation MyTreeViewCell
@synthesize valueLabel, arrowImage;
@synthesize level, expanded;
- (id)initWithStyle:(UITableViewCellStyle)style
reuseIdentifier:(NSString *)reuseIdentifier
level:(NSUInteger)_level
expanded:(BOOL)_expanded {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.level = _level;
self.expanded = _expanded;
// UIView *content = self.contentView;
//
// if(level == 0)
// {
// self.valueLabel =
// [self newLabelWithPrimaryColor:[UIColor blackColor]
// selectedColor:[UIColor whiteColor]
// fontSize:15.0 bold:YES];
// self.valueLabel.textAlignment = UITextAlignmentLeft;
//
// [content addSubview:self.valueLabel];
//
//// self.arrowImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CircleArrowDown_sml"]];
////// self.arrowImage.frame = CGRectMake(0, 0, 170, 44);
//// [content addSubview:self.arrowImage];
//
// }
// else
// {
// self.valueLabel =
// [self newLabelWithPrimaryColor:[UIColor blackColor]
// selectedColor:[UIColor whiteColor]
// fontSize:12.0 bold:NO];
// self.valueLabel.textAlignment = UITextAlignmentLeft;
//
// [content addSubview:self.valueLabel];
// }
//
// [content release];
// NSLog(@"%d",level);
}
return self;
}
#pragma mark -
#pragma mark Memory Management
- (void)dealloc {
[valueLabel release];
[arrowImage release];
[super dealloc];
}
#pragma mark -
#pragma mark Other overrides
- (void)layoutSubviews {
[super layoutSubviews];
// CGRect contentRect = self.contentView.bounds;
if (!self.editing) {
// get the X pixel spot
// CGFloat boundsX = contentRect.origin.x;
// CGRect frame;
//
// frame = CGRectMake((boundsX + self.level + 1) * LEVEL_INDENT, 0, SCREEN_WIDTH - (self.level * LEVEL_INDENT), CELL_HEIGHT );
// self.valueLabel.frame = frame;
//
// CGRect imgFrame;
// imgFrame = CGRectMake(((boundsX + self.level + 1) * LEVEL_INDENT) - (IMG_HEIGHT_WIDTH + XOFFSET),
// YOFFSET,
// IMG_HEIGHT_WIDTH,
// IMG_HEIGHT_WIDTH);
// self.arrowImage.frame = imgFrame;
}
}
#pragma mark -
#pragma mark Private category
- (UILabel *)newLabelWithPrimaryColor:(UIColor *)primaryColor
selectedColor:(UIColor *)selectedColor
fontSize:(CGFloat)fontSize
bold:(BOOL)bold {
UIFont *font;
if (bold) {
font = [UIFont boldSystemFontOfSize:fontSize];
} else {
font = [UIFont systemFontOfSize:fontSize];
}
UILabel *newLabel = [[UILabel alloc] initWithFrame:CGRectZero];
newLabel.backgroundColor = [UIColor whiteColor];
newLabel.opaque = YES;
newLabel.textColor = primaryColor;
newLabel.highlightedTextColor = selectedColor;
newLabel.font = font;
newLabel.numberOfLines = 0;
return newLabel;
}
@end | 009-20120511-zi | trunk/Zinipad/MyTreeViewCell.m | Objective-C | gpl3 | 3,542 |
//
// ASIHTTPRequestDelegate.h
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 13/04/2010.
// Copyright 2010 All-Seeing Interactive. All rights reserved.
//
@class ASIHTTPRequest;
@protocol ASIHTTPRequestDelegate <NSObject>
@optional
// These are the default delegate methods for request status
// You can use different ones by setting didStartSelector / didFinishSelector / didFailSelector
- (void)requestStarted:(ASIHTTPRequest *)request;
- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders;
- (void)request:(ASIHTTPRequest *)request willRedirectToURL:(NSURL *)newURL;
- (void)requestFinished:(ASIHTTPRequest *)request;
- (void)requestFailed:(ASIHTTPRequest *)request;
- (void)requestRedirected:(ASIHTTPRequest *)request;
// When a delegate implements this method, it is expected to process all incoming data itself
// This means that responseData / responseString / downloadDestinationPath etc are ignored
// You can have the request call a different method by setting didReceiveDataSelector
- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data;
// If a delegate implements one of these, it will be asked to supply credentials when none are available
// The delegate can then either restart the request ([request retryUsingSuppliedCredentials]) once credentials have been set
// or cancel it ([request cancelAuthentication])
- (void)authenticationNeededForRequest:(ASIHTTPRequest *)request;
- (void)proxyAuthenticationNeededForRequest:(ASIHTTPRequest *)request;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASIHTTPRequestDelegate.h | Objective-C | gpl3 | 1,598 |
//
// ASIDownloadCache.h
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 01/05/2010.
// Copyright 2010 All-Seeing Interactive. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "ASICacheDelegate.h"
@interface ASIDownloadCache : NSObject <ASICacheDelegate> {
// The default cache policy for this cache
// Requests that store data in the cache will use this cache policy if their cache policy is set to ASIUseDefaultCachePolicy
// Defaults to ASIAskServerIfModifiedWhenStaleCachePolicy
ASICachePolicy defaultCachePolicy;
// The directory in which cached data will be stored
// Defaults to a directory called 'ASIHTTPRequestCache' in the temporary directory
NSString *storagePath;
// Mediates access to the cache
NSRecursiveLock *accessLock;
// When YES, the cache will look for cache-control / pragma: no-cache headers, and won't reuse store responses if it finds them
BOOL shouldRespectCacheControlHeaders;
}
// Returns a static instance of an ASIDownloadCache
// In most circumstances, it will make sense to use this as a global cache, rather than creating your own cache
// To make ASIHTTPRequests use it automatically, use [ASIHTTPRequest setDefaultCache:[ASIDownloadCache sharedCache]];
+ (id)sharedCache;
// A helper function that determines if the server has requested data should not be cached by looking at the request's response headers
+ (BOOL)serverAllowsResponseCachingForRequest:(ASIHTTPRequest *)request;
// A list of file extensions that we know won't be readable by a webview when accessed locally
// If we're asking for a path to cache a particular url and it has one of these extensions, we change it to '.html'
+ (NSArray *)fileExtensionsToHandleAsHTML;
@property (assign, nonatomic) ASICachePolicy defaultCachePolicy;
@property (retain, nonatomic) NSString *storagePath;
@property (retain) NSRecursiveLock *accessLock;
@property (assign) BOOL shouldRespectCacheControlHeaders;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASIDownloadCache.h | Objective-C | gpl3 | 1,996 |
//
// ASIHTTPRequestConfig.h
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 14/12/2009.
// Copyright 2009 All-Seeing Interactive. All rights reserved.
//
// ======
// Debug output configuration options
// ======
// If defined will use the specified function for debug logging
// Otherwise use NSLog
#ifndef ASI_DEBUG_LOG
#define ASI_DEBUG_LOG NSLog
#endif
// When set to 1 ASIHTTPRequests will print information about what a request is doing
#ifndef DEBUG_REQUEST_STATUS
#define DEBUG_REQUEST_STATUS 0
#endif
// When set to 1, ASIFormDataRequests will print information about the request body to the console
#ifndef DEBUG_FORM_DATA_REQUEST
#define DEBUG_FORM_DATA_REQUEST 0
#endif
// When set to 1, ASIHTTPRequests will print information about bandwidth throttling to the console
#ifndef DEBUG_THROTTLING
#define DEBUG_THROTTLING 0
#endif
// When set to 1, ASIHTTPRequests will print information about persistent connections to the console
#ifndef DEBUG_PERSISTENT_CONNECTIONS
#define DEBUG_PERSISTENT_CONNECTIONS 0
#endif
// When set to 1, ASIHTTPRequests will print information about HTTP authentication (Basic, Digest or NTLM) to the console
#ifndef DEBUG_HTTP_AUTHENTICATION
#define DEBUG_HTTP_AUTHENTICATION 0
#endif
| 009-20120511-zi | trunk/Zinipad/ASI/ASIHTTPRequestConfig.h | C | gpl3 | 1,297 |
//
// ASIDataDecompressor.h
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 17/08/2010.
// Copyright 2010 All-Seeing Interactive. All rights reserved.
//
// This is a helper class used by ASIHTTPRequest to handle inflating (decompressing) data in memory and on disk
// You may also find it helpful if you need to inflate data and files yourself - see the class methods below
// Most of the zlib stuff is based on the sample code by Mark Adler available at http://zlib.net
#import <Foundation/Foundation.h>
#import <zlib.h>
@interface ASIDataDecompressor : NSObject {
BOOL streamReady;
z_stream zStream;
}
// Convenience constructor will call setupStream for you
+ (id)decompressor;
// Uncompress the passed chunk of data
- (NSData *)uncompressBytes:(Bytef *)bytes length:(NSUInteger)length error:(NSError **)err;
// Convenience method - pass it some deflated data, and you'll get inflated data back
+ (NSData *)uncompressData:(NSData*)compressedData error:(NSError **)err;
// Convenience method - pass it a file containing deflated data in sourcePath, and it will write inflated data to destinationPath
+ (BOOL)uncompressDataFromFile:(NSString *)sourcePath toFile:(NSString *)destinationPath error:(NSError **)err;
// Sets up zlib to handle the inflating. You only need to call this yourself if you aren't using the convenience constructor 'decompressor'
- (NSError *)setupStream;
// Tells zlib to clean up. You need to call this if you need to cancel inflating part way through
// If inflating finishes or fails, this method will be called automatically
- (NSError *)closeStream;
@property (assign, readonly) BOOL streamReady;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASIDataDecompressor.h | Objective-C | gpl3 | 1,699 |