FlatCAMApp.py 288 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import sys
  9. import traceback
  10. import urllib.request, urllib.parse, urllib.error
  11. import getopt
  12. import os
  13. import random
  14. import logging
  15. import simplejson as json
  16. import re
  17. import os
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import subprocess
  20. import tkinter as tk
  21. from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
  22. from PyQt5.QtCore import QSettings
  23. import time # Just used for debugging. Double check before removing.
  24. import urllib.request, urllib.parse, urllib.error
  25. import webbrowser
  26. from contextlib import contextmanager
  27. from xml.dom.minidom import parseString as parse_xml_string
  28. from copy import copy,deepcopy
  29. import numpy as np
  30. from datetime import datetime
  31. import gc
  32. ########################################
  33. ## Imports part of FlatCAM ##
  34. ########################################
  35. from ObjectCollection import *
  36. from FlatCAMObj import *
  37. from PlotCanvas import *
  38. from FlatCAMGUI import *
  39. from FlatCAMCommon import LoudDict
  40. from FlatCAMPostProc import load_postprocessors
  41. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. from multiprocessing import Pool
  49. import tclCommands
  50. # from ParseFont import *
  51. ########################################
  52. ## App ##
  53. ########################################
  54. class App(QtCore.QObject):
  55. """
  56. The main application class. The constructor starts the GUI.
  57. """
  58. # Get Cmd Line Options
  59. cmd_line_shellfile = ''
  60. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  61. try:
  62. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  63. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  64. except getopt.GetoptError:
  65. print(cmd_line_help)
  66. sys.exit(2)
  67. for opt, arg in cmd_line_options:
  68. if opt == '-h':
  69. print(cmd_line_help)
  70. sys.exit()
  71. elif opt == '--shellfile':
  72. cmd_line_shellfile = arg
  73. # Logging ##
  74. log = logging.getLogger('base')
  75. log.setLevel(logging.DEBUG)
  76. # log.setLevel(logging.WARNING)
  77. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  78. handler = logging.StreamHandler()
  79. handler.setFormatter(formatter)
  80. log.addHandler(handler)
  81. # Version
  82. version = 8.909
  83. version_date = "2019/02/12"
  84. beta = True
  85. # current date now
  86. date = str(datetime.today()).rpartition(' ')[0]
  87. # URL for update checks and statistics
  88. version_url = "http://flatcam.org/version"
  89. # App URL
  90. app_url = "http://flatcam.org"
  91. # Manual URL
  92. manual_url = "http://flatcam.org/manual/index.html"
  93. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  94. should_we_quit = True
  95. ##################
  96. ## Signals ##
  97. ##################
  98. # Inform the user
  99. # Handled by:
  100. # * App.info() --> Print on the status bar
  101. inform = QtCore.pyqtSignal(str)
  102. # General purpose background task
  103. worker_task = QtCore.pyqtSignal(dict)
  104. # File opened
  105. # Handled by:
  106. # * register_folder()
  107. # * register_recent()
  108. # Note: Setting the parameters to unicode does not seem
  109. # to have an effect. Then are received as Qstring
  110. # anyway.
  111. # File type and filename
  112. file_opened = QtCore.pyqtSignal(str, str)
  113. # File type and filename
  114. file_saved = QtCore.pyqtSignal(str, str)
  115. # Percentage of progress
  116. progress = QtCore.pyqtSignal(int)
  117. plots_updated = QtCore.pyqtSignal()
  118. # Emitted by new_object() and passes the new object as argument, plot flag.
  119. # on_object_created() adds the object to the collection, plots on appropriate flag
  120. # and emits new_object_available.
  121. object_created = QtCore.pyqtSignal(object, bool, bool)
  122. # Emitted when a object has been changed (like scaled, mirrored)
  123. object_changed = QtCore.pyqtSignal(object)
  124. # Emitted after object has been plotted.
  125. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  126. object_plotted = QtCore.pyqtSignal(object)
  127. # Emitted when a new object has been added to the collection
  128. # and is ready to be used.
  129. new_object_available = QtCore.pyqtSignal(object)
  130. message = QtCore.pyqtSignal(str, str, str)
  131. # Emmited when shell command is finished(one command only)
  132. shell_command_finished = QtCore.pyqtSignal(object)
  133. # Emitted when multiprocess pool has been recreated
  134. pool_recreated = QtCore.pyqtSignal(object)
  135. # Emitted when an unhandled exception happens
  136. # in the worker task.
  137. thread_exception = QtCore.pyqtSignal(object)
  138. def __init__(self, user_defaults=True, post_gui=None):
  139. """
  140. Starts the application.
  141. :return: app
  142. :rtype: App
  143. """
  144. App.log.info("FlatCAM Starting...")
  145. ###################
  146. ### OS-specific ###
  147. ###################
  148. # Folder for user settings.
  149. if sys.platform == 'win32':
  150. from win32com.shell import shell, shellcon
  151. if platform.architecture()[0] == '32bit':
  152. App.log.debug("Win32!")
  153. else:
  154. App.log.debug("Win64!")
  155. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  156. '\FlatCAM'
  157. self.os = 'windows'
  158. else: # Linux/Unix/MacOS
  159. self.data_path = os.path.expanduser('~') + \
  160. '/.FlatCAM'
  161. self.os = 'unix'
  162. ###############################
  163. ### Setup folders and files ###
  164. ###############################
  165. if not os.path.exists(self.data_path):
  166. os.makedirs(self.data_path)
  167. App.log.debug('Created data folder: ' + self.data_path)
  168. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  169. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  170. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  171. if not os.path.exists(self.postprocessorpaths):
  172. os.makedirs(self.postprocessorpaths)
  173. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  174. # create current_defaults.FlatConfig file if there is none
  175. try:
  176. f = open(self.data_path + '/current_defaults.FlatConfig')
  177. f.close()
  178. except IOError:
  179. App.log.debug('Creating empty current_defaults.FlatConfig')
  180. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  181. json.dump({}, f)
  182. f.close()
  183. # create factory_defaults.FlatConfig file if there is none
  184. try:
  185. f = open(self.data_path + '/factory_defaults.FlatConfig')
  186. f.close()
  187. except IOError:
  188. App.log.debug('Creating empty factory_defaults.FlatConfig')
  189. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  190. json.dump({}, f)
  191. f.close()
  192. try:
  193. f = open(self.data_path + '/recent.json')
  194. f.close()
  195. except IOError:
  196. App.log.debug('Creating empty recent.json')
  197. f = open(self.data_path + '/recent.json', 'w')
  198. json.dump([], f)
  199. f.close()
  200. # Application directory. CHDIR to it. Otherwise, trying to load
  201. # GUI icons will fail as their path is relative.
  202. # This will fail under cx_freeze ...
  203. self.app_home = os.path.dirname(os.path.realpath(__file__))
  204. App.log.debug("Application path is " + self.app_home)
  205. App.log.debug("Started in " + os.getcwd())
  206. # cx_freeze workaround
  207. if os.path.isfile(self.app_home):
  208. self.app_home = os.path.dirname(self.app_home)
  209. os.chdir(self.app_home)
  210. # Create multiprocessing pool
  211. self.pool = Pool()
  212. # variable to store mouse coordinates
  213. self.mouse = [0, 0]
  214. ####################
  215. ## Initialize GUI ##
  216. ####################
  217. # FlatCAM colors used in plotting
  218. self.FC_light_green = '#BBF268BF'
  219. self.FC_dark_green = '#006E20BF'
  220. self.FC_light_blue = '#a5a5ffbf'
  221. self.FC_dark_blue = '#0000ffbf'
  222. QtCore.QObject.__init__(self)
  223. self.ui = FlatCAMGUI(self.version, self.beta, self)
  224. # self.connect(self.ui,
  225. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  226. # self.save_geometry) PyQt4
  227. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  228. self.ui.final_save.connect(self.final_save)
  229. ##############
  230. #### Data ####
  231. ##############
  232. self.recent = []
  233. self.clipboard = QtWidgets.QApplication.clipboard()
  234. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  235. self.project_filename = None
  236. self.toggle_units_ignore = False
  237. # self.defaults_form = PreferencesUI()
  238. self.general_defaults_form = GeneralPreferencesUI()
  239. self.gerber_defaults_form = GerberPreferencesUI()
  240. self.excellon_defaults_form = ExcellonPreferencesUI()
  241. self.geometry_defaults_form = GeometryPreferencesUI()
  242. self.cncjob_defaults_form = CNCJobPreferencesUI()
  243. self.tools_defaults_form = ToolsPreferencesUI()
  244. # when adding entries here read the comments in the method found bellow named:
  245. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  246. self.defaults_form_fields = {
  247. "units": self.general_defaults_form.general_app_group.units_radio,
  248. "global_shell_at_startup": self.general_defaults_form.general_app_group.shell_startup_cb,
  249. "global_version_check": self.general_defaults_form.general_app_group.version_check_cb,
  250. "global_send_stats": self.general_defaults_form.general_app_group.send_stats_cb,
  251. "global_gridx": self.general_defaults_form.general_gui_group.gridx_entry,
  252. "global_gridy": self.general_defaults_form.general_gui_group.gridy_entry,
  253. "global_snap_max": self.general_defaults_form.general_gui_group.snap_max_dist_entry,
  254. "global_plot_fill": self.general_defaults_form.general_gui_group.pf_color_entry,
  255. "global_plot_line": self.general_defaults_form.general_gui_group.pl_color_entry,
  256. "global_sel_fill": self.general_defaults_form.general_gui_group.sf_color_entry,
  257. "global_sel_line": self.general_defaults_form.general_gui_group.sl_color_entry,
  258. "global_alt_sel_fill": self.general_defaults_form.general_gui_group.alt_sf_color_entry,
  259. "global_alt_sel_line": self.general_defaults_form.general_gui_group.alt_sl_color_entry,
  260. "global_draw_color": self.general_defaults_form.general_gui_group.draw_color_entry,
  261. "global_sel_draw_color": self.general_defaults_form.general_gui_group.sel_draw_color_entry,
  262. "global_pan_button": self.general_defaults_form.general_app_group.pan_button_radio,
  263. "global_mselect_key": self.general_defaults_form.general_app_group.mselect_radio,
  264. # "global_pan_with_space_key": self.general_defaults_form.general_gui_group.pan_with_space_cb,
  265. "global_workspace": self.general_defaults_form.general_gui_group.workspace_cb,
  266. "global_workspaceT": self.general_defaults_form.general_gui_group.wk_cb,
  267. "gerber_plot": self.gerber_defaults_form.gerber_gen_group.plot_cb,
  268. "gerber_solid": self.gerber_defaults_form.gerber_gen_group.solid_cb,
  269. "gerber_multicolored": self.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  270. "gerber_circle_steps": self.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  271. "gerber_isotooldia": self.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  272. "gerber_isopasses": self.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  273. "gerber_isooverlap": self.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  274. "gerber_combine_passes": self.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  275. "gerber_milling_type": self.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  276. "gerber_noncoppermargin": self.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  277. "gerber_noncopperrounded": self.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  278. "gerber_bboxmargin": self.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  279. "gerber_bboxrounded": self.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  280. "excellon_plot": self.excellon_defaults_form.excellon_gen_group.plot_cb,
  281. "excellon_solid": self.excellon_defaults_form.excellon_gen_group.solid_cb,
  282. "excellon_format_upper_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  283. "excellon_format_lower_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  284. "excellon_format_upper_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  285. "excellon_format_lower_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  286. "excellon_zeros": self.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  287. "excellon_units": self.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  288. "excellon_optimization_type": self.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  289. "excellon_search_time": self.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  290. "excellon_drillz": self.excellon_defaults_form.excellon_opt_group.cutz_entry,
  291. "excellon_travelz": self.excellon_defaults_form.excellon_opt_group.travelz_entry,
  292. "excellon_feedrate": self.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  293. "excellon_feedrate_rapid": self.excellon_defaults_form.excellon_opt_group.feedrate_rapid_entry,
  294. "excellon_feedrate_probe": self.excellon_defaults_form.excellon_opt_group.feedrate_probe_entry,
  295. "excellon_spindlespeed": self.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  296. "excellon_dwell": self.excellon_defaults_form.excellon_opt_group.dwell_cb,
  297. "excellon_dwelltime": self.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  298. "excellon_toolchange": self.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  299. "excellon_toolchangez": self.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  300. "excellon_toolchangexy": self.excellon_defaults_form.excellon_opt_group.toolchangexy_entry,
  301. "excellon_ppname_e": self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  302. "excellon_z_pdepth": self.excellon_defaults_form.excellon_opt_group.pdepth_entry,
  303. "excellon_f_plunge": self.excellon_defaults_form.excellon_opt_group.fplunge_cb,
  304. "excellon_startz": self.excellon_defaults_form.excellon_opt_group.estartz_entry,
  305. "excellon_endz": self.excellon_defaults_form.excellon_opt_group.eendz_entry,
  306. "excellon_tooldia": self.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  307. "excellon_slot_tooldia": self.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  308. "excellon_gcode_type": self.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  309. "geometry_plot": self.geometry_defaults_form.geometry_gen_group.plot_cb,
  310. "geometry_cnctooldia": self.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  311. "geometry_circle_steps": self.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  312. "geometry_segx": self.geometry_defaults_form.geometry_opt_group.segx_entry,
  313. "geometry_segy": self.geometry_defaults_form.geometry_opt_group.segy_entry,
  314. "geometry_cutz": self.geometry_defaults_form.geometry_opt_group.cutz_entry,
  315. "geometry_travelz": self.geometry_defaults_form.geometry_opt_group.travelz_entry,
  316. "geometry_feedrate": self.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  317. "geometry_feedrate_z": self.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  318. "geometry_feedrate_rapid": self.geometry_defaults_form.geometry_opt_group.cncfeedrate_rapid_entry,
  319. "geometry_feedrate_probe": self.geometry_defaults_form.geometry_opt_group.feedrate_probe_entry,
  320. "geometry_spindlespeed": self.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  321. "geometry_dwell": self.geometry_defaults_form.geometry_opt_group.dwell_cb,
  322. "geometry_dwelltime": self.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  323. "geometry_ppname_g": self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  324. "geometry_z_pdepth": self.geometry_defaults_form.geometry_opt_group.pdepth_entry,
  325. "geometry_f_plunge": self.geometry_defaults_form.geometry_opt_group.fplunge_cb,
  326. "geometry_toolchange": self.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  327. "geometry_toolchangez": self.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  328. "geometry_toolchangexy": self.geometry_defaults_form.geometry_opt_group.toolchangexy_entry,
  329. "geometry_startz": self.geometry_defaults_form.geometry_opt_group.gstartz_entry,
  330. "geometry_endz": self.geometry_defaults_form.geometry_opt_group.gendz_entry,
  331. "geometry_multidepth": self.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  332. "geometry_depthperpass": self.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  333. "geometry_extracut": self.geometry_defaults_form.geometry_opt_group.extracut_cb,
  334. "cncjob_plot": self.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  335. "cncjob_plot_kind": self.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  336. "cncjob_tooldia": self.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  337. "cncjob_coords_decimals": self.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  338. "cncjob_fr_decimals": self.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  339. "cncjob_steps_per_circle": self.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  340. "cncjob_prepend": self.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  341. "cncjob_append": self.cncjob_defaults_form.cncjob_opt_group.append_text,
  342. "tools_ncctools": self.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  343. "tools_nccoverlap": self.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  344. "tools_nccmargin": self.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  345. "tools_nccmethod": self.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  346. "tools_nccconnect": self.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  347. "tools_ncccontour": self.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  348. "tools_nccrest": self.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  349. "tools_cutouttooldia": self.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  350. "tools_cutoutmargin": self.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  351. "tools_cutoutgapsize": self.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  352. "tools_gaps_rect": self.tools_defaults_form.tools_cutout_group.gaps_radio,
  353. "tools_gaps_ff": self.tools_defaults_form.tools_cutout_group.gaps_combo,
  354. "tools_painttooldia": self.tools_defaults_form.tools_paint_group.painttooldia_entry,
  355. "tools_paintoverlap": self.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  356. "tools_paintmargin": self.tools_defaults_form.tools_paint_group.paintmargin_entry,
  357. "tools_paintmethod": self.tools_defaults_form.tools_paint_group.paintmethod_combo,
  358. "tools_selectmethod": self.tools_defaults_form.tools_paint_group.selectmethod_combo,
  359. "tools_pathconnect": self.tools_defaults_form.tools_paint_group.pathconnect_cb,
  360. "tools_paintcontour": self.tools_defaults_form.tools_paint_group.contour_cb,
  361. "tools_2sided_mirror_axis": self.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  362. "tools_2sided_axis_loc": self.tools_defaults_form.tools_2sided_group.axis_location_radio,
  363. "tools_2sided_drilldia": self.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  364. "tools_film_type": self.tools_defaults_form.tools_film_group.film_type_radio,
  365. "tools_film_boundary": self.tools_defaults_form.tools_film_group.film_boundary_entry,
  366. "tools_film_scale": self.tools_defaults_form.tools_film_group.film_scale_entry,
  367. "tools_panelize_spacing_columns": self.tools_defaults_form.tools_panelize_group.pspacing_columns,
  368. "tools_panelize_spacing_rows": self.tools_defaults_form.tools_panelize_group.pspacing_rows,
  369. "tools_panelize_columns": self.tools_defaults_form.tools_panelize_group.pcolumns,
  370. "tools_panelize_rows": self.tools_defaults_form.tools_panelize_group.prows,
  371. "tools_panelize_constrain": self.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  372. "tools_panelize_constrainx": self.tools_defaults_form.tools_panelize_group.px_width_entry,
  373. "tools_panelize_constrainy": self.tools_defaults_form.tools_panelize_group.py_height_entry,
  374. "tools_calc_vshape_tip_dia": self.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  375. "tools_calc_vshape_tip_angle": self.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  376. "tools_calc_vshape_cut_z": self.tools_defaults_form.tools_calculators_group.cut_z_entry,
  377. "tools_calc_electro_length": self.tools_defaults_form.tools_calculators_group.pcblength_entry,
  378. "tools_calc_electro_width": self.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  379. "tools_calc_electro_cdensity": self.tools_defaults_form.tools_calculators_group.cdensity_entry,
  380. "tools_calc_electro_growth": self.tools_defaults_form.tools_calculators_group.growth_entry
  381. }
  382. # loads postprocessors
  383. self.postprocessors = load_postprocessors(self)
  384. for name in list(self.postprocessors.keys()):
  385. self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  386. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  387. if name == 'hpgl':
  388. continue
  389. self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  390. self.defaults = LoudDict()
  391. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  392. self.defaults.update({
  393. "global_serial": 0,
  394. "global_stats": {},
  395. "units": "IN",
  396. "global_version_check": True,
  397. "global_send_stats": True,
  398. "global_gridx": 1.0,
  399. "global_gridy": 1.0,
  400. "global_snap_max": 0.05,
  401. "global_plot_fill": '#BBF268BF',
  402. "global_plot_line": '#006E20BF',
  403. "global_sel_fill": '#a5a5ffbf',
  404. "global_sel_line": '#0000ffbf',
  405. "global_alt_sel_fill": '#BBF268BF',
  406. "global_alt_sel_line": '#006E20BF',
  407. "global_draw_color": '#FF0000',
  408. "global_sel_draw_color": '#0000FF',
  409. "global_pan_button": '2',
  410. "global_mselect_key": 'Control',
  411. # "global_pan_with_space_key": False,
  412. "global_workspace": False,
  413. "global_workspaceT": "A4P",
  414. "global_toolbar_view": 127,
  415. "global_background_timeout": 300000, # Default value is 5 minutes
  416. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  417. # (python trace only for unknown errors),
  418. # 1 = show trace(show trace allways),
  419. # 2 = (For the future).
  420. # Persistence
  421. "global_last_folder": None,
  422. "global_last_save_folder": None,
  423. # Default window geometry
  424. "global_def_win_x": 100,
  425. "global_def_win_y": 100,
  426. "global_def_win_w": 1024,
  427. "global_def_win_h": 650,
  428. # Constants...
  429. "global_defaults_save_period_ms": 20000, # Time between default saves.
  430. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  431. "global_shell_at_startup": False, # Show the shell at startup.
  432. "global_recent_limit": 10, # Max. items in recent list.
  433. "fit_key": 'V',
  434. "zoom_out_key": '-',
  435. "zoom_in_key": '=',
  436. "grid_toggle_key": 'G',
  437. "zoom_ratio": 1.5,
  438. "global_point_clipboard_format": "(%.4f, %.4f)",
  439. "global_zdownrate": None,
  440. "gerber_plot": True,
  441. "gerber_solid": True,
  442. "gerber_multicolored": False,
  443. "gerber_isotooldia": 0.016,
  444. "gerber_isopasses": 1,
  445. "gerber_isooverlap": 0.15,
  446. "gerber_combine_passes": False,
  447. "gerber_milling_type": "cl",
  448. "gerber_noncoppermargin": 0.1,
  449. "gerber_noncopperrounded": False,
  450. "gerber_bboxmargin": 0.1,
  451. "gerber_bboxrounded": False,
  452. "gerber_circle_steps": 64,
  453. "gerber_use_buffer_for_union": True,
  454. "excellon_plot": True,
  455. "excellon_solid": True,
  456. "excellon_format_upper_in": 2,
  457. "excellon_format_lower_in": 4,
  458. "excellon_format_upper_mm": 3,
  459. "excellon_format_lower_mm": 3,
  460. "excellon_zeros": "L",
  461. "excellon_units": "INCH",
  462. "excellon_optimization_type": 'B',
  463. "excellon_search_time": 3,
  464. "excellon_drillz": -0.1,
  465. "excellon_travelz": 0.1,
  466. "excellon_feedrate": 3.0,
  467. "excellon_feedrate_rapid": 3.0,
  468. "excellon_feedrate_probe": 3.0,
  469. "excellon_spindlespeed": None,
  470. "excellon_dwell": False,
  471. "excellon_dwelltime": 1,
  472. "excellon_toolchange": False,
  473. "excellon_toolchangez": 1.0,
  474. "excellon_toolchangexy": "0.0, 0.0",
  475. "excellon_tooldia": 0.016,
  476. "excellon_slot_tooldia": 0.016,
  477. "excellon_startz": None,
  478. "excellon_endz": 2.0,
  479. "excellon_ppname_e": 'default',
  480. "excellon_z_pdepth": -0.02,
  481. "excellon_f_plunge": False,
  482. "excellon_gcode_type": "drills",
  483. "geometry_plot": True,
  484. "geometry_segx": 0.0,
  485. "geometry_segy": 0.0,
  486. "geometry_cutz": -0.002,
  487. "geometry_travelz": 0.1,
  488. "geometry_toolchange": False,
  489. "geometry_toolchangez": 1.0,
  490. "geometry_toolchangexy": "0.0, 0.0",
  491. "geometry_startz": None,
  492. "geometry_endz": 2.0,
  493. "geometry_feedrate": 3.0,
  494. "geometry_feedrate_z": 3.0,
  495. "geometry_feedrate_rapid": 3.0,
  496. "geometry_feedrate_probe": 3.0,
  497. "geometry_cnctooldia": 0.016,
  498. "geometry_spindlespeed": None,
  499. "geometry_dwell": False,
  500. "geometry_dwelltime": 1,
  501. "geometry_ppname_g": 'default',
  502. "geometry_z_pdepth": -0.02,
  503. "geometry_f_plunge": False,
  504. "geometry_depthperpass": 0.002,
  505. "geometry_multidepth": False,
  506. "geometry_extracut": False,
  507. "geometry_circle_steps": 64,
  508. "cncjob_plot": True,
  509. "cncjob_plot_kind": 'all',
  510. "cncjob_tooldia": 0.0393701,
  511. "cncjob_coords_decimals": 4,
  512. "cncjob_fr_decimals": 2,
  513. "cncjob_prepend": "",
  514. "cncjob_append": "",
  515. "cncjob_steps_per_circle": 64,
  516. "tools_ncctools": "1.0, 0.5",
  517. "tools_nccoverlap": 0.4,
  518. "tools_nccmargin": 0.1,
  519. "tools_nccmethod": "seed",
  520. "tools_nccconnect": True,
  521. "tools_ncccontour": True,
  522. "tools_nccrest": False,
  523. "tools_cutouttooldia": 0.1,
  524. "tools_cutoutmargin": 0.1,
  525. "tools_cutoutgapsize": 0.15,
  526. "tools_gaps_rect": "4",
  527. "tools_gaps_ff": "8",
  528. "tools_painttooldia": 0.07,
  529. "tools_paintoverlap": 0.15,
  530. "tools_paintmargin": 0.0,
  531. "tools_paintmethod": "seed",
  532. "tools_selectmethod": "single",
  533. "tools_pathconnect": True,
  534. "tools_paintcontour": True,
  535. "tools_2sided_mirror_axis": "X",
  536. "tools_2sided_axis_loc": "point",
  537. "tools_2sided_drilldia": 1,
  538. "tools_film_type": 'neg',
  539. "tools_film_boundary": 1,
  540. "tools_film_scale": 0,
  541. "tools_panelize_spacing_columns": 0,
  542. "tools_panelize_spacing_rows": 0,
  543. "tools_panelize_columns": 1,
  544. "tools_panelize_rows": 1,
  545. "tools_panelize_constrain": False,
  546. "tools_panelize_constrainx": 0.0,
  547. "tools_panelize_constrainy": 0.0,
  548. "tools_calc_vshape_tip_dia": 0.007874,
  549. "tools_calc_vshape_tip_angle": 30,
  550. "tools_calc_vshape_cut_z": 0.000787,
  551. "tools_calc_electro_length": 10.0,
  552. "tools_calc_electro_width": 10.0,
  553. "tools_calc_electro_cdensity":13.0,
  554. "tools_calc_electro_growth": 10.0
  555. })
  556. ###############################
  557. ### Load defaults from file ###
  558. if user_defaults:
  559. self.load_defaults(filename='current_defaults')
  560. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  561. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  562. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  563. self.save_defaults(silent=True)
  564. self.propagate_defaults(silent=True)
  565. self.restore_main_win_geom()
  566. def auto_save_defaults():
  567. try:
  568. self.save_defaults(silent=True)
  569. self.propagate_defaults(silent=True)
  570. finally:
  571. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  572. # the following lines activates automatic defaults save
  573. # if user_defaults:
  574. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  575. # self.options_form = PreferencesUI()
  576. self.general_options_form = GeneralPreferencesUI()
  577. self.gerber_options_form = GerberPreferencesUI()
  578. self.excellon_options_form = ExcellonPreferencesUI()
  579. self.geometry_options_form = GeometryPreferencesUI()
  580. self.cncjob_options_form = CNCJobPreferencesUI()
  581. self.tools_options_form = ToolsPreferencesUI()
  582. self.options_form_fields = {
  583. "units": self.general_options_form.general_app_group.units_radio,
  584. "global_gridx": self.general_options_form.general_gui_group.gridx_entry,
  585. "global_gridy": self.general_options_form.general_gui_group.gridy_entry,
  586. "global_snap_max": self.general_options_form.general_gui_group.snap_max_dist_entry,
  587. "gerber_plot": self.gerber_options_form.gerber_gen_group.plot_cb,
  588. "gerber_solid": self.gerber_options_form.gerber_gen_group.solid_cb,
  589. "gerber_multicolored": self.gerber_options_form.gerber_gen_group.multicolored_cb,
  590. "gerber_isotooldia": self.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  591. "gerber_isopasses": self.gerber_options_form.gerber_opt_group.iso_width_entry,
  592. "gerber_isooverlap": self.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  593. "gerber_combine_passes": self.gerber_options_form.gerber_opt_group.combine_passes_cb,
  594. "gerber_noncoppermargin": self.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  595. "gerber_noncopperrounded": self.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  596. "gerber_bboxmargin": self.gerber_options_form.gerber_opt_group.bbmargin_entry,
  597. "gerber_bboxrounded": self.gerber_options_form.gerber_opt_group.bbrounded_cb,
  598. "excellon_plot": self.excellon_options_form.excellon_gen_group.plot_cb,
  599. "excellon_solid": self.excellon_options_form.excellon_gen_group.solid_cb,
  600. "excellon_format_upper_in": self.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  601. "excellon_format_lower_in": self.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  602. "excellon_format_upper_mm": self.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  603. "excellon_format_lower_mm": self.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  604. "excellon_zeros": self.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  605. "excellon_units": self.excellon_options_form.excellon_gen_group.excellon_units_radio,
  606. "excellon_optimization_type": self.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  607. "excellon_drillz": self.excellon_options_form.excellon_opt_group.cutz_entry,
  608. "excellon_travelz": self.excellon_options_form.excellon_opt_group.travelz_entry,
  609. "excellon_feedrate": self.excellon_options_form.excellon_opt_group.feedrate_entry,
  610. "excellon_feedrate_rapid": self.excellon_options_form.excellon_opt_group.feedrate_rapid_entry,
  611. "excellon_spindlespeed": self.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  612. "excellon_dwell": self.excellon_options_form.excellon_opt_group.dwell_cb,
  613. "excellon_dwelltime": self.excellon_options_form.excellon_opt_group.dwelltime_entry,
  614. "excellon_toolchange": self.excellon_options_form.excellon_opt_group.toolchange_cb,
  615. "excellon_toolchangez": self.excellon_options_form.excellon_opt_group.toolchangez_entry,
  616. "excellon_toolchangexy": self.excellon_options_form.excellon_opt_group.toolchangexy_entry,
  617. "excellon_tooldia": self.excellon_options_form.excellon_opt_group.tooldia_entry,
  618. "excellon_ppname_e": self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  619. "excellon_f_plunge": self.excellon_options_form.excellon_opt_group.fplunge_cb,
  620. "excellon_startz": self.excellon_options_form.excellon_opt_group.estartz_entry,
  621. "excellon_endz": self.excellon_options_form.excellon_opt_group.eendz_entry,
  622. "geometry_plot": self.geometry_options_form.geometry_gen_group.plot_cb,
  623. "geometry_cnctooldia": self.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  624. "geometry_segx": self.geometry_options_form.geometry_opt_group.segx_entry,
  625. "geometry_segy": self.geometry_options_form.geometry_opt_group.segy_entry,
  626. "geometry_cutz": self.geometry_options_form.geometry_opt_group.cutz_entry,
  627. "geometry_travelz": self.geometry_options_form.geometry_opt_group.travelz_entry,
  628. "geometry_feedrate": self.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  629. "geometry_feedrate_z": self.geometry_options_form.geometry_opt_group.cncplunge_entry,
  630. "geometry_feedrate_rapid": self.geometry_options_form.geometry_opt_group.cncfeedrate_rapid_entry,
  631. "geometry_spindlespeed": self.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  632. "geometry_dwell": self.geometry_options_form.geometry_opt_group.dwell_cb,
  633. "geometry_dwelltime": self.geometry_options_form.geometry_opt_group.dwelltime_entry,
  634. "geometry_ppname_g": self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  635. "geometry_f_plunge": self.geometry_options_form.geometry_opt_group.fplunge_cb,
  636. "geometry_toolchange": self.geometry_options_form.geometry_opt_group.toolchange_cb,
  637. "geometry_toolchangez": self.geometry_options_form.geometry_opt_group.toolchangez_entry,
  638. "geometry_toolchangexy": self.geometry_options_form.geometry_opt_group.toolchangexy_entry,
  639. "geometry_startz": self.geometry_options_form.geometry_opt_group.gstartz_entry,
  640. "geometry_endz": self.geometry_options_form.geometry_opt_group.gendz_entry,
  641. "geometry_depthperpass": self.geometry_options_form.geometry_opt_group.depthperpass_entry,
  642. "geometry_multidepth": self.geometry_options_form.geometry_opt_group.multidepth_cb,
  643. "geometry_extracut": self.geometry_options_form.geometry_opt_group.extracut_cb,
  644. "cncjob_plot": self.cncjob_options_form.cncjob_gen_group.plot_cb,
  645. "cncjob_tooldia": self.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  646. "cncjob_prepend": self.cncjob_options_form.cncjob_opt_group.prepend_text,
  647. "cncjob_append": self.cncjob_options_form.cncjob_opt_group.append_text,
  648. "tools_ncctools": self.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  649. "tools_nccoverlap": self.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  650. "tools_nccmargin": self.tools_options_form.tools_ncc_group.ncc_margin_entry,
  651. "tools_cutouttooldia": self.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  652. "tools_cutoutmargin": self.tools_options_form.tools_cutout_group.cutout_margin_entry,
  653. "tools_cutoutgapsize": self.tools_options_form.tools_cutout_group.cutout_gap_entry,
  654. "tools_gaps_rect": self.tools_options_form.tools_cutout_group.gaps_radio,
  655. "tools_gaps_ff": self.tools_options_form.tools_cutout_group.gaps_combo,
  656. "tools_painttooldia": self.tools_options_form.tools_paint_group.painttooldia_entry,
  657. "tools_paintoverlap": self.tools_options_form.tools_paint_group.paintoverlap_entry,
  658. "tools_paintmargin": self.tools_options_form.tools_paint_group.paintmargin_entry,
  659. "tools_paintmethod": self.tools_options_form.tools_paint_group.paintmethod_combo,
  660. "tools_selectmethod": self.tools_options_form.tools_paint_group.selectmethod_combo,
  661. "tools_pathconnect": self.tools_options_form.tools_paint_group.pathconnect_cb,
  662. "tools_paintcontour": self.tools_options_form.tools_paint_group.contour_cb,
  663. "tools_2sided_mirror_axis": self.tools_options_form.tools_2sided_group.mirror_axis_radio,
  664. "tools_2sided_axis_loc": self.tools_options_form.tools_2sided_group.axis_location_radio,
  665. "tools_2sided_drilldia": self.tools_options_form.tools_2sided_group.drill_dia_entry,
  666. "tools_film_type": self.tools_options_form.tools_film_group.film_type_radio,
  667. "tools_film_boundary": self.tools_options_form.tools_film_group.film_boundary_entry,
  668. "tools_film_scale": self.tools_options_form.tools_film_group.film_scale_entry,
  669. "tools_panelize_spacing_columns": self.tools_options_form.tools_panelize_group.pspacing_columns,
  670. "tools_panelize_spacing_rows": self.tools_options_form.tools_panelize_group.pspacing_rows,
  671. "tools_panelize_columns": self.tools_options_form.tools_panelize_group.pcolumns,
  672. "tools_panelize_rows": self.tools_options_form.tools_panelize_group.prows,
  673. "tools_panelize_constrain": self.tools_options_form.tools_panelize_group.pconstrain_cb,
  674. "tools_panelize_constrainx": self.tools_options_form.tools_panelize_group.px_width_entry,
  675. "tools_panelize_constrainy": self.tools_options_form.tools_panelize_group.py_height_entry
  676. }
  677. for name in list(self.postprocessors.keys()):
  678. self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  679. self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  680. self.options = LoudDict()
  681. self.options.set_change_callback(self.on_options_dict_change)
  682. self.options.update({
  683. "units": "IN",
  684. "global_gridx": 1.0,
  685. "global_gridy": 1.0,
  686. "global_snap_max": 0.05,
  687. "global_background_timeout": 300000, # Default value is 5 minutes
  688. "global_verbose_error_level": 0, # Shell verbosity:
  689. # 0 = default(python trace only for unknown errors),
  690. # 1 = show trace(show trace allways), 2 = (For the future).
  691. "gerber_plot": True,
  692. "gerber_solid": True,
  693. "gerber_multicolored": False,
  694. "gerber_isotooldia": 0.016,
  695. "gerber_isopasses": 1,
  696. "gerber_isooverlap": 0.15,
  697. "gerber_combine_passes": True,
  698. "gerber_noncoppermargin": 0.0,
  699. "gerber_noncopperrounded": False,
  700. "gerber_bboxmargin": 0.0,
  701. "gerber_bboxrounded": False,
  702. "excellon_plot": True,
  703. "excellon_solid": False,
  704. "excellon_format_upper_in": 2,
  705. "excellon_format_lower_in": 4,
  706. "excellon_format_upper_mm": 3,
  707. "excellon_format_lower_mm": 3,
  708. "excellon_units": 'INCH',
  709. "excellon_optimization_type": 'B',
  710. "excellon_search_time": 3,
  711. "excellon_zeros": "L",
  712. "excellon_drillz": -0.1,
  713. "excellon_travelz": 0.1,
  714. "excellon_feedrate": 3.0,
  715. "excellon_feedrate_rapid": 3.0,
  716. "excellon_spindlespeed": None,
  717. "excellon_dwell": True,
  718. "excellon_dwelltime": 1000,
  719. "excellon_toolchange": False,
  720. "excellon_toolchangez": 1.0,
  721. "excellon_toolchangexy": "0.0, 0.0",
  722. "excellon_tooldia": 0.016,
  723. "excellon_ppname_e": 'default',
  724. "excellon_f_plunge": False,
  725. "excellon_startz": None,
  726. "excellon_endz": 2.0,
  727. "geometry_plot": True,
  728. "geometry_segx": 0.0,
  729. "geometry_segy": 0.0,
  730. "geometry_cutz": -0.002,
  731. "geometry_travelz": 0.1,
  732. "geometry_feedrate": 3.0,
  733. "geometry_feedrate_z": 3.0,
  734. "geometry_feedrate_rapid": 3.0,
  735. "geometry_spindlespeed": None,
  736. "geometry_dwell": True,
  737. "geometry_dwelltime": 1000,
  738. "geometry_cnctooldia": 0.016,
  739. "geometry_toolchange": False,
  740. "geometry_toolchangez": 2.0,
  741. "geometry_toolchangexy": "0.0, 0.0",
  742. "geometry_startz": None,
  743. "geometry_endz": 2.0,
  744. "geometry_ppname_g": "default",
  745. "geometry_f_plunge": False,
  746. "geometry_depthperpass": 0.002,
  747. "geometry_multidepth": False,
  748. "geometry_extracut": False,
  749. "cncjob_plot": True,
  750. "cncjob_tooldia": 0.016,
  751. "cncjob_prepend": "",
  752. "cncjob_append": "",
  753. "tools_ncctools": "1.0, 0.5",
  754. "tools_nccoverlap": 0.4,
  755. "tools_nccmargin": 1,
  756. "tools_cutouttooldia": 0.07,
  757. "tools_cutoutmargin": 0.1,
  758. "tools_cutoutgapsize": 0.15,
  759. "tools_gaps_rect": "4",
  760. "tools_gaps_ff": "8",
  761. "tools_painttooldia": 0.07,
  762. "tools_paintoverlap": 0.15,
  763. "tools_paintmargin": 0.0,
  764. "tools_paintmethod": "seed",
  765. "tools_selectmethod": "single",
  766. "tools_pathconnect": True,
  767. "tools_paintcontour": True,
  768. "tools_2sided_mirror_axis": "X",
  769. "tools_2sided_axis_loc": 'point',
  770. "tools_2sided_drilldia": 1,
  771. "tools_film_type": 'neg',
  772. "tools_film_boundary": 1,
  773. "tools_film_scale": 0,
  774. "tools_panelize_spacing_columns": 0,
  775. "tools_panelize_spacing_rows": 0,
  776. "tools_panelize_columns": 1,
  777. "tools_panelize_rows": 1,
  778. "tools_panelize_constrain": False,
  779. "tools_panelize_constrainx": 0.0,
  780. "tools_panelize_constrainy": 0.0
  781. })
  782. self.options.update(self.defaults) # Copy app defaults to project options
  783. self.gen_form = None
  784. self.ger_form = None
  785. self.exc_form = None
  786. self.geo_form = None
  787. self.cnc_form = None
  788. self.tools_form = None
  789. self.on_options_combo_change(0) # Will show the initial form
  790. ### Define OBJECT COLLECTION ###
  791. self.collection = ObjectCollection(self)
  792. self.ui.project_tab_layout.addWidget(self.collection.view)
  793. ###
  794. self.log.debug("Finished creating Object Collection.")
  795. ### Initialize the color box's color in Preferences -> Global -> Color
  796. # Init Plot Colors
  797. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  798. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  799. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  800. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  801. int(self.defaults['global_plot_fill'][7:9], 16))
  802. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  803. int(self.defaults['global_plot_fill'][7:9], 16))
  804. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  805. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  806. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  807. # Init Left-Right Selection colors
  808. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  809. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  810. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  811. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  812. int(self.defaults['global_sel_fill'][7:9], 16))
  813. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  814. int(self.defaults['global_sel_fill'][7:9], 16))
  815. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  816. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  817. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  818. # Init Right-Left Selection colors
  819. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  820. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  821. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  822. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  823. int(self.defaults['global_sel_fill'][7:9], 16))
  824. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  825. int(self.defaults['global_sel_fill'][7:9], 16))
  826. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  827. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  828. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  829. # Init Draw color and Selection Draw Color
  830. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  831. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  832. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  833. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  834. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  835. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  836. #### End of Data ####
  837. #### Plot Area ####
  838. start_plot_time = time.time() # debug
  839. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  840. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  841. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  842. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  843. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  844. # Keys over plot enabled
  845. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  846. self.ui.splitter.setStretchFactor(1, 2)
  847. # So it can receive key presses
  848. self.plotcanvas.vispy_canvas.native.setFocus()
  849. self.app_cursor = self.plotcanvas.new_cursor()
  850. self.app_cursor.enabled = False
  851. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  852. # depending on from where those tools are called different actions can be done
  853. self.call_source = 'app'
  854. end_plot_time = time.time()
  855. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  856. ### EDITOR section
  857. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  858. self.exc_editor = FlatCAMExcEditor(self)
  859. #### Adjust tabs width ####
  860. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  861. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  862. self.collection.view.setMinimumWidth(290)
  863. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  864. #### Worker ####
  865. self.workers = WorkerStack()
  866. self.worker_task.connect(self.workers.add_task)
  867. ### Signal handling ###
  868. ## Custom signals
  869. self.inform.connect(self.info)
  870. self.message.connect(self.message_dialog)
  871. self.progress.connect(self.set_progress_bar)
  872. self.object_created.connect(self.on_object_created)
  873. self.object_changed.connect(self.on_object_changed)
  874. self.object_plotted.connect(self.on_object_plotted)
  875. self.plots_updated.connect(self.on_plots_updated)
  876. self.file_opened.connect(self.register_recent)
  877. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  878. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  879. ## Standard signals
  880. # Menu
  881. self.ui.menufilenew.triggered.connect(self.on_file_new_click)
  882. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  883. self.ui.menufileopengerber_follow.triggered.connect(self.on_fileopengerber_follow)
  884. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  885. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  886. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  887. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  888. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  889. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  890. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  891. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  892. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  893. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  894. self.ui.menufileexportexcellon.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=None))
  895. self.ui.menufileexportexcellon_altium.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=True))
  896. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  897. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  898. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  899. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  900. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  901. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  902. self.ui.menueditnew.triggered.connect(self.new_geometry_object)
  903. self.ui.menueditnewexc.triggered.connect(self.new_excellon_object)
  904. self.ui.menueditedit.triggered.connect(self.object2editor)
  905. self.ui.menueditok.triggered.connect(self.editor2object)
  906. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  907. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  908. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  909. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  910. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  911. self.ui.menueditdelete.triggered.connect(self.on_delete)
  912. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  913. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  914. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  915. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  916. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  917. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  918. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  919. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  920. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  921. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  922. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  923. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  924. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  925. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  926. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  927. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  928. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  929. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  930. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  931. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  932. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  933. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  934. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  935. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  936. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  937. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  938. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  939. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  940. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  941. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  942. self.ui.menuhelp_about.triggered.connect(self.on_about)
  943. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  944. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  945. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  946. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  947. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  948. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  949. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  950. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  951. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  952. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  953. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  954. # Toolbar
  955. #self.ui.file_new_btn.triggered.connect(self.on_file_new)
  956. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  957. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  958. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  959. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  960. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  961. self.ui.replot_btn.triggered.connect(self.plot_all)
  962. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  963. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  964. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  965. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  966. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  967. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  968. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  969. self.ui.delete_btn.triggered.connect(self.on_delete)
  970. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  971. # Context Menu
  972. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  973. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  974. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  975. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  976. self.ui.gridmenu_1.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.05"))
  977. self.ui.gridmenu_2.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.1"))
  978. self.ui.gridmenu_3.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.2"))
  979. self.ui.gridmenu_4.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.5"))
  980. self.ui.gridmenu_5.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("1.0"))
  981. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  982. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  983. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  984. self.ui.draw_move.triggered.connect(self.geo_editor.on_move)
  985. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  986. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  987. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  988. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  989. self.ui.clearplot.triggered.connect(self.clear_plots)
  990. self.ui.replot.triggered.connect(self.plot_all)
  991. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  992. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  993. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  994. self.ui.popmenu_save.triggered.connect(self.editor2object)
  995. self.ui.popmenu_move.triggered.connect(self.obj_move)
  996. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  997. # Preferences Plot Area TAB
  998. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  999. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1000. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1001. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1002. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1003. ###############################
  1004. ### GUI PREFERENCES SIGNALS ###
  1005. ###############################
  1006. self.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1007. self.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(self.on_language_apply)
  1008. ###############################
  1009. ### GUI PREFERENCES SIGNALS ###
  1010. ###############################
  1011. # Setting plot colors signals
  1012. self.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  1013. self.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  1014. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  1015. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  1016. self.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  1017. self.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  1018. # Setting selection (left - right) colors signals
  1019. self.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  1020. self.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  1021. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  1022. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  1023. self.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  1024. self.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  1025. # Setting selection (right - left) colors signals
  1026. self.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  1027. self.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  1028. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1029. self.on_alt_sf_color_spinner)
  1030. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1031. self.on_alt_sf_color_slider)
  1032. self.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  1033. self.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  1034. # Setting Editor Draw colors signals
  1035. self.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  1036. self.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  1037. self.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  1038. self.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  1039. self.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1040. self.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1041. self.general_defaults_form.general_gui_group.layout_combo.activated.connect(self.on_layout)
  1042. # Modify G-CODE Plot Area TAB
  1043. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1044. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1045. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1046. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1047. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1048. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1049. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1050. # Object list
  1051. self.collection.view.activated.connect(self.on_row_activated)
  1052. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1053. self.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1054. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1055. self.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1056. self.on_excellon_defaults_button)
  1057. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1058. self.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1059. self.on_excellon_options_button)
  1060. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1061. self.tool_tab_locked = False
  1062. ####################
  1063. ### Other setups ###
  1064. ####################
  1065. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1066. self.setup_obj_classes()
  1067. self.setup_recent_items()
  1068. self.setup_component_editor()
  1069. #############
  1070. ### Shell ###
  1071. #############
  1072. ###
  1073. # Auto-complete KEYWORDS
  1074. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1075. 'aligndrill', 'clear',
  1076. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1077. 'export_gcode',
  1078. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1079. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1080. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1081. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1082. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1083. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1084. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1085. ]
  1086. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1087. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1088. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1089. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1090. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1091. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1092. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1093. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1094. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1095. ]
  1096. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  1097. self.shell = FCShell(self, version=self.version)
  1098. self.shell._edit.set_model_data(self.myKeywords)
  1099. self.shell.setWindowIcon(self.ui.app_icon)
  1100. self.shell.setWindowTitle("FlatCAM Shell")
  1101. self.shell.resize(*self.defaults["global_shell_shape"])
  1102. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1103. self.shell.append_output("(Type help to get started)\n\n")
  1104. self.init_tcl()
  1105. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1106. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1107. self.ui.shell_dock.setWidget(self.shell)
  1108. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1109. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1110. QtWidgets.QDockWidget.DockWidgetFloatable |
  1111. QtWidgets.QDockWidget.DockWidgetClosable)
  1112. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1113. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1114. if self.defaults["global_shell_at_startup"]:
  1115. self.ui.shell_dock.show()
  1116. else:
  1117. self.ui.shell_dock.hide()
  1118. #########################
  1119. ### Tools and Plugins ###
  1120. #########################
  1121. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1122. self.install_tools()
  1123. ### System Font Parsing ###
  1124. # self.f_parse = ParseFont(self)
  1125. # self.parse_system_fonts()
  1126. # test if the program was started with a script as parameter
  1127. if self.cmd_line_shellfile:
  1128. try:
  1129. with open(self.cmd_line_shellfile, "r") as myfile:
  1130. cmd_line_shellfile_text = myfile.read()
  1131. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1132. except Exception as ext:
  1133. print("ERROR: ", ext)
  1134. sys.exit(2)
  1135. ###########################
  1136. #### Check for updates ####
  1137. ###########################
  1138. # Separate thread (Not worker)
  1139. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1140. if (self.beta is False or self.beta is None) and \
  1141. self.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1142. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1143. self.thr2 = QtCore.QThread()
  1144. self.worker_task.emit({'fcn': self.version_check,
  1145. 'params': []})
  1146. self.thr2.start()
  1147. ####################################
  1148. #### Variables for global usage ####
  1149. ####################################
  1150. # coordinates for relative position display
  1151. self.rel_point1 = (0, 0)
  1152. self.rel_point2 = (0, 0)
  1153. # variable to store coordinates
  1154. self.pos = (0, 0)
  1155. self.pos_jump = (0, 0)
  1156. # variable to store if there was motion before right mouse button click (panning)
  1157. self.panning_action = False
  1158. # variable to store if a command is active (then the var is not None) and which one it is
  1159. self.command_active = None
  1160. # variable to store the status of moving selection action
  1161. # None value means that it's not an selection action
  1162. # True value = a selection from left to right
  1163. # False value = a selection from right to left
  1164. self.selection_type = None
  1165. # List to store the objects that are currently loaded in FlatCAM
  1166. # This list is updated on each object creation or object delete
  1167. self.all_objects_list = []
  1168. # List to store the objects that are selected
  1169. self.sel_objects_list = []
  1170. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1171. self.key_modifiers = None
  1172. # Variable to hold the status of the axis
  1173. self.toggle_axis = True
  1174. # Variable to store the status of the fullscreen event
  1175. self.toggle_fscreen = False
  1176. self.cursor = None
  1177. # Variable to store the GCODE that was edited
  1178. self.gcode_edited = ""
  1179. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1180. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1181. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1182. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1183. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1184. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1185. 'mpf']
  1186. self.svg_list = ['svg']
  1187. self.dxf_list = ['dxf']
  1188. self.prj_list = ['flatprj']
  1189. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1190. # flag for polygons not cleared
  1191. self.poly_not_cleared = False
  1192. ### Save defaults to factory_defaults.FlatConfig file ###
  1193. ### It's done only once after install #############
  1194. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1195. fac_def_from_file = factory_file.read()
  1196. factory_defaults = json.loads(fac_def_from_file)
  1197. # if the file contain an empty dictionary then save the factory defaults into the file
  1198. if not factory_defaults:
  1199. self.save_factory_defaults(silent=False)
  1200. factory_file.close()
  1201. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1202. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1203. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1204. # Post-GUI initialization: Experimental attempt
  1205. # to perform unit tests on the GUI.
  1206. # if post_gui is not None:
  1207. # post_gui(self)
  1208. App.log.debug("END of constructor. Releasing control.")
  1209. # accept a project file as command line parameter
  1210. # the path/file_name must be enclosed in quotes if it contain spaces
  1211. for argument in App.args:
  1212. if '.FlatPrj' in argument:
  1213. try:
  1214. project_name = str(argument)
  1215. if project_name == "":
  1216. self.inform.emit("Open cancelled.")
  1217. else:
  1218. # self.open_project(project_name)
  1219. run_from_arg = True
  1220. self.worker_task.emit({'fcn': self.open_project,
  1221. 'params': [project_name, run_from_arg]})
  1222. except Exception as e:
  1223. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1224. def defaults_read_form(self):
  1225. for option in self.defaults_form_fields:
  1226. try:
  1227. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1228. except:
  1229. pass
  1230. def defaults_write_form(self):
  1231. for option in self.defaults:
  1232. self.defaults_write_form_field(option)
  1233. # try:
  1234. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1235. # except KeyError:
  1236. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1237. # # TODO: Rethink this?
  1238. # pass
  1239. def defaults_write_form_field(self, field):
  1240. try:
  1241. self.defaults_form_fields[field].set_value(self.defaults[field])
  1242. except KeyError:
  1243. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1244. # TODO: Rethink this?
  1245. pass
  1246. def clear_pool(self):
  1247. self.pool.close()
  1248. self.pool = Pool()
  1249. self.pool_recreated.emit(self.pool)
  1250. gc.collect()
  1251. # the order that the tools are installed is important as they can depend on each other install position
  1252. def install_tools(self):
  1253. self.dblsidedtool = DblSidedTool(self)
  1254. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1255. self.measurement_tool = Measurement(self)
  1256. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1257. self.panelize_tool = Panelize(self)
  1258. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1259. self.film_tool = Film(self)
  1260. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'), separator=True)
  1261. self.move_tool = ToolMove(self)
  1262. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1263. before=self.ui.menueditorigin)
  1264. self.cutout_tool = ToolCutOut(self)
  1265. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16.png'), pos=self.ui.menutool,
  1266. before=self.measurement_tool.menuAction)
  1267. self.ncclear_tool = NonCopperClear(self)
  1268. self.ncclear_tool.install(icon=QtGui.QIcon('share/flatcam_icon16.png'), pos=self.ui.menutool,
  1269. before=self.measurement_tool.menuAction, separator=True)
  1270. self.paint_tool = ToolPaint(self)
  1271. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1272. before=self.measurement_tool.menuAction, separator=True)
  1273. self.calculator_tool = ToolCalculator(self)
  1274. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1275. self.transform_tool = ToolTransform(self)
  1276. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1277. self.properties_tool = Properties(self)
  1278. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1279. self.image_tool = ToolImage(self)
  1280. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1281. separator=True)
  1282. self.log.debug("Tools are installed.")
  1283. def remove_tools(self):
  1284. for act in self.ui.menutool.actions():
  1285. self.ui.menutool.removeAction(act)
  1286. def init_tools(self):
  1287. log.debug("init_tools()")
  1288. # delete the data currently in the Tools Tab and the Tab itself
  1289. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1290. if widget is not None:
  1291. widget.deleteLater()
  1292. self.ui.notebook.removeTab(2)
  1293. # rebuild the Tools Tab
  1294. self.ui.tool_tab = QtWidgets.QWidget()
  1295. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1296. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1297. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1298. self.ui.tool_scroll_area = VerticalScrollArea()
  1299. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1300. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1301. # first remove all of them
  1302. self.remove_tools()
  1303. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1304. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1305. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1306. # third install all of them
  1307. self.install_tools()
  1308. self.log.debug("Tools are initialized.")
  1309. # def parse_system_fonts(self):
  1310. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1311. # 'params': []})
  1312. def object2editor(self):
  1313. """
  1314. Send the current Geometry or Excellon object (if any) into the editor.
  1315. :return: None
  1316. """
  1317. self.report_usage("object2editor()")
  1318. # adjust the visibility of some of the canvas context menu
  1319. self.ui.popmenu_edit.setVisible(False)
  1320. self.ui.popmenu_save.setVisible(True)
  1321. edited_object = self.collection.get_active()
  1322. if isinstance(edited_object, FlatCAMGeometry):
  1323. # for now, if the Geometry is MultiGeo do not allow the editing
  1324. if edited_object.multigeo is True:
  1325. self.inform.emit("[WARNING_NOTCL]Editing a MultiGeo Geometry is not possible for the moment.")
  1326. return
  1327. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1328. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1329. self.geo_editor.edit_fcgeometry(edited_object)
  1330. # set call source to the Editor we go into
  1331. self.call_source = 'geo_editor'
  1332. elif isinstance(edited_object, FlatCAMExcellon):
  1333. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1334. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1335. self.exc_editor.edit_fcexcellon(edited_object)
  1336. # set call source to the Editor we go into
  1337. self.call_source = 'exc_editor'
  1338. else:
  1339. self.inform.emit("[WARNING_NOTCL]Select a Geometry or Excellon Object to edit.")
  1340. return
  1341. # make sure that we can't select another object while in Editor Mode:
  1342. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1343. # delete any selection shape that might be active as they are not relevant in Editor
  1344. self.delete_selection_shape()
  1345. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1346. self.ui.plot_tab_area.protectTab(0)
  1347. self.inform.emit("[WARNING_NOTCL]Editor is activated ...")
  1348. def editor2object(self):
  1349. """
  1350. Transfers the Geometry or Excellon from the editor to the current object.
  1351. :return: None
  1352. """
  1353. self.report_usage("editor2object()")
  1354. # adjust the visibility of some of the canvas context menu
  1355. self.ui.popmenu_edit.setVisible(True)
  1356. self.ui.popmenu_save.setVisible(False)
  1357. edited_obj = self.collection.get_active()
  1358. obj_type = ""
  1359. if isinstance(edited_obj, FlatCAMGeometry):
  1360. obj_type = "Geometry"
  1361. self.geo_editor.update_fcgeometry(edited_obj)
  1362. self.geo_editor.update_options(edited_obj)
  1363. self.geo_editor.deactivate()
  1364. # update the geo object options so it is including the bounding box values
  1365. try:
  1366. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1367. edited_obj.options['xmin'] = xmin
  1368. edited_obj.options['ymin'] = ymin
  1369. edited_obj.options['xmax'] = xmax
  1370. edited_obj.options['ymax'] = ymax
  1371. except AttributeError:
  1372. self.inform.emit("[WARNING] Object empty after edit.")
  1373. elif isinstance(edited_obj, FlatCAMExcellon):
  1374. obj_type = "Excellon"
  1375. self.exc_editor.update_fcexcellon(edited_obj)
  1376. self.exc_editor.update_options(edited_obj)
  1377. self.exc_editor.deactivate()
  1378. else:
  1379. self.inform.emit("[WARNING_NOTCL]Select a Geometry or Excellon Object to update.")
  1380. return
  1381. # restore the call_source to app
  1382. self.call_source = 'app'
  1383. edited_obj.plot()
  1384. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1385. self.ui.plot_tab_area.protectTab(0)
  1386. self.inform.emit("[selected] %s is updated, returning to App..." % obj_type)
  1387. # reset the Object UI to original settings
  1388. # edited_obj.set_ui(edited_obj.ui_type())
  1389. # edited_obj.build_ui()
  1390. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1391. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1392. def get_last_folder(self):
  1393. return self.defaults["global_last_folder"]
  1394. def get_last_save_folder(self):
  1395. loc = self.defaults["global_last_save_folder"]
  1396. if loc is None:
  1397. loc = self.defaults["global_last_folder"]
  1398. if loc is None:
  1399. loc = os.path.dirname(__file__)
  1400. return loc
  1401. def report_usage(self, resource):
  1402. """
  1403. Increments usage counter for the given resource
  1404. in self.defaults['global_stats'].
  1405. :param resource: Name of the resource.
  1406. :return: None
  1407. """
  1408. if resource in self.defaults['global_stats']:
  1409. self.defaults['global_stats'][resource] += 1
  1410. else:
  1411. self.defaults['global_stats'][resource] = 1
  1412. def init_tcl(self):
  1413. if hasattr(self,'tcl'):
  1414. # self.tcl = None
  1415. # TODO we need to clean non default variables and procedures here
  1416. # new object cannot be used here as it will not remember values created for next passes,
  1417. # because tcl was execudted in old instance of TCL
  1418. pass
  1419. else:
  1420. self.tcl = tk.Tcl()
  1421. self.setup_shell()
  1422. self.log.debug("TCL Shell has been initialized.")
  1423. # TODO: This shouldn't be here.
  1424. class TclErrorException(Exception):
  1425. """
  1426. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1427. """
  1428. pass
  1429. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  1430. """
  1431. Shows a message on the FlatCAM Shell
  1432. :param msg: Message to display.
  1433. :param show: Opens the shell.
  1434. :param error: Shows the message as an error.
  1435. :return: None
  1436. """
  1437. if show:
  1438. self.ui.shell_dock.show()
  1439. try:
  1440. if error:
  1441. self.shell.append_error(msg + "\n")
  1442. elif warning:
  1443. self.shell.append_warning(msg + "\n")
  1444. elif success:
  1445. self.shell.append_success(msg + "\n")
  1446. elif selected:
  1447. self.shell.append_selected(msg + "\n")
  1448. else:
  1449. self.shell.append_output(msg + "\n")
  1450. except AttributeError:
  1451. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1452. def raise_tcl_unknown_error(self, unknownException):
  1453. """
  1454. Raise exception if is different type than TclErrorException
  1455. this is here mainly to show unknown errors inside TCL shell console.
  1456. :param unknownException:
  1457. :return:
  1458. """
  1459. if not isinstance(unknownException, self.TclErrorException):
  1460. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1461. else:
  1462. raise unknownException
  1463. def display_tcl_error(self, error, error_info=None):
  1464. """
  1465. escape bracket [ with \ otherwise there is error
  1466. "ERROR: missing close-bracket" instead of real error
  1467. :param error: it may be text or exception
  1468. :return: None
  1469. """
  1470. if isinstance(error, Exception):
  1471. exc_type, exc_value, exc_traceback = error_info
  1472. if not isinstance(error, self.TclErrorException):
  1473. show_trace = 1
  1474. else:
  1475. show_trace = int(self.defaults['global_verbose_error_level'])
  1476. if show_trace > 0:
  1477. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1478. trc_formated = []
  1479. for a in reversed(trc):
  1480. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1481. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1482. exc_type,
  1483. "\n".join(trc_formated))
  1484. else:
  1485. text = "%s" % error
  1486. else:
  1487. text = error
  1488. text = text.replace('[', '\\[').replace('"', '\\"')
  1489. self.tcl.eval('return -code error "%s"' % text)
  1490. def raise_tcl_error(self, text):
  1491. """
  1492. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1493. :param text: text of error
  1494. :return: raise exception
  1495. """
  1496. self.display_tcl_error(text)
  1497. raise self.TclErrorException(text)
  1498. def exec_command(self, text):
  1499. """
  1500. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1501. Also handles execution in separated threads
  1502. :param text:
  1503. :return: output if there was any
  1504. """
  1505. self.report_usage('exec_command')
  1506. result = self.exec_command_test(text, False)
  1507. #MS: added this method call so the geometry is updated once the TCL
  1508. #command is executed
  1509. self.plot_all()
  1510. return result
  1511. def exec_command_test(self, text, reraise=True):
  1512. """
  1513. Same as exec_command(...) with additional control over exceptions.
  1514. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1515. :param text: Input command
  1516. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1517. :return: Output from the command
  1518. """
  1519. text = str(text)
  1520. try:
  1521. self.shell.open_proccessing() # Disables input box.
  1522. result = self.tcl.eval(str(text))
  1523. if result != 'None':
  1524. self.shell.append_output(result + '\n')
  1525. except tk.TclError as e:
  1526. # This will display more precise answer if something in TCL shell fails
  1527. result = self.tcl.eval("set errorInfo")
  1528. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1529. self.shell.append_error('ERROR: ' + result + '\n')
  1530. # Show error in console and just return or in test raise exception
  1531. if reraise:
  1532. raise e
  1533. finally:
  1534. self.shell.close_proccessing()
  1535. pass
  1536. return result
  1537. # """
  1538. # Code below is unsused. Saved for later.
  1539. # """
  1540. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1541. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1542. # self.log.debug(parts)
  1543. # try:
  1544. # if parts[0] not in commands:
  1545. # self.shell.append_error("Unknown command\n")
  1546. # return
  1547. #
  1548. # #import inspect
  1549. # #inspect.getargspec(someMethod)
  1550. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1551. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1552. # self.shell.append_error(
  1553. # "Command %s takes %d arguments. %d given.\n" %
  1554. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1555. # )
  1556. # return
  1557. #
  1558. # cmdfcn = commands[parts[0]]["fcn"]
  1559. # cmdconv = commands[parts[0]]["converters"]
  1560. # if len(parts) - 1 > 0:
  1561. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1562. # else:
  1563. # retval = cmdfcn()
  1564. # retfcn = commands[parts[0]]["retfcn"]
  1565. # if retval and retfcn(retval):
  1566. # self.shell.append_output(retfcn(retval) + "\n")
  1567. #
  1568. # except Exception as e:
  1569. # #self.shell.append_error(''.join(traceback.format_exc()))
  1570. # #self.shell.append_error("?\n")
  1571. # self.shell.append_error(str(e) + "\n")
  1572. def info(self, msg):
  1573. """
  1574. Informs the user. Normally on the status bar, optionally
  1575. also on the shell.
  1576. :param msg: Text to write.
  1577. :return: None
  1578. """
  1579. # Type of message in brackets at the begining of the message.
  1580. match = re.search("\[([^\]]+)\](.*)", msg)
  1581. if match:
  1582. level = match.group(1)
  1583. msg_ = match.group(2)
  1584. self.ui.fcinfo.set_status(str(msg_), level=level)
  1585. if level.lower() == "error":
  1586. self.shell_message(msg, error=True, show=True)
  1587. elif level.lower() == "warning":
  1588. self.shell_message(msg, warning=True, show=True)
  1589. elif level.lower() == "error_notcl":
  1590. self.shell_message(msg, error=True, show=False)
  1591. elif level.lower() == "warning_notcl":
  1592. self.shell_message(msg, warning=True, show=False)
  1593. elif level.lower() == "success":
  1594. self.shell_message(msg, success=True, show=False)
  1595. elif level.lower() == "selected":
  1596. self.shell_message(msg, selected=True, show=False)
  1597. else:
  1598. self.shell_message(msg, show=False)
  1599. else:
  1600. self.ui.fcinfo.set_status(str(msg), level="info")
  1601. # make sure that if the message is to clear the infobar with a space
  1602. # is not printed over and over on the shell
  1603. if msg != '':
  1604. self.shell_message(msg)
  1605. def restore_toolbar_view(self):
  1606. tb = self.defaults["global_toolbar_view"]
  1607. if tb & 1:
  1608. self.ui.toolbarfile.setVisible(True)
  1609. else:
  1610. self.ui.toolbarfile.setVisible(False)
  1611. if tb & 2:
  1612. self.ui.toolbargeo.setVisible(True)
  1613. else:
  1614. self.ui.toolbargeo.setVisible(False)
  1615. if tb & 4:
  1616. self.ui.toolbarview.setVisible(True)
  1617. else:
  1618. self.ui.toolbarview.setVisible(False)
  1619. if tb & 8:
  1620. self.ui.toolbartools.setVisible(True)
  1621. else:
  1622. self.ui.toolbartools.setVisible(False)
  1623. if tb & 16:
  1624. self.ui.exc_edit_toolbar.setVisible(True)
  1625. else:
  1626. self.ui.exc_edit_toolbar.setVisible(False)
  1627. if tb & 32:
  1628. self.ui.geo_edit_toolbar.setVisible(True)
  1629. else:
  1630. self.ui.geo_edit_toolbar.setVisible(False)
  1631. if tb & 64:
  1632. self.ui.snap_toolbar.setVisible(True)
  1633. else:
  1634. self.ui.snap_toolbar.setVisible(False)
  1635. def load_defaults(self, filename):
  1636. """
  1637. Loads the aplication's default settings from current_defaults.FlatConfig into
  1638. ``self.defaults``.
  1639. :return: None
  1640. """
  1641. try:
  1642. f = open(self.data_path + "/" + filename + ".FlatConfig")
  1643. options = f.read()
  1644. f.close()
  1645. except IOError:
  1646. self.log.error("Could not load defaults file.")
  1647. self.inform.emit("[ERROR] Could not load defaults file.")
  1648. # in case the defaults file can't be loaded, show all toolbars
  1649. self.defaults["global_toolbar_view"] = 127
  1650. return
  1651. try:
  1652. defaults = json.loads(options)
  1653. except:
  1654. # in case the defaults file can't be loaded, show all toolbars
  1655. self.defaults["global_toolbar_view"] = 127
  1656. e = sys.exc_info()[0]
  1657. App.log.error(str(e))
  1658. self.inform.emit("[ERROR] Failed to parse defaults file.")
  1659. return
  1660. self.defaults.update(defaults)
  1661. log.debug("FlatCAM defaults loaded from: %s" % filename)
  1662. # restore the toolbar view
  1663. self.restore_toolbar_view()
  1664. def on_import_preferences(self):
  1665. """
  1666. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  1667. ``self.defaults``.
  1668. :return: None
  1669. """
  1670. self.report_usage("on_import_preferences")
  1671. App.log.debug("on_import_preferences()")
  1672. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1673. try:
  1674. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences",
  1675. directory=self.data_path, filter=filter)
  1676. except TypeError:
  1677. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences", filter=filter)
  1678. filename = str(filename)
  1679. if filename == "":
  1680. self.inform.emit("[WARNING_NOTCL]FlatCAM preferences import cancelled.")
  1681. else:
  1682. try:
  1683. f = open(filename)
  1684. options = f.read()
  1685. f.close()
  1686. except IOError:
  1687. self.log.error("Could not load defaults file.")
  1688. self.inform.emit("[ERROR_NOTCL] Could not load defaults file.")
  1689. return
  1690. try:
  1691. defaults_from_file = json.loads(options)
  1692. except:
  1693. e = sys.exc_info()[0]
  1694. App.log.error(str(e))
  1695. self.inform.emit("[ERROR_NOTCL] Failed to parse defaults file.")
  1696. return
  1697. self.defaults.update(defaults_from_file)
  1698. self.inform.emit("[success]Imported Defaults from %s" %filename)
  1699. def on_export_preferences(self):
  1700. self.report_usage("on_export_preferences")
  1701. App.log.debug("on_export_preferences()")
  1702. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1703. try:
  1704. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  1705. caption="Export FlatCAM Preferences",
  1706. directory=self.data_path + '/preferences_' + self.date.replace('-', ''), filter=filter
  1707. )
  1708. except TypeError:
  1709. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences", filter=filter)
  1710. filename = str(filename)
  1711. defaults_from_file = {}
  1712. if filename == "":
  1713. self.inform.emit("[WARNING_NOTCL]FlatCAM preferences export cancelled.")
  1714. return
  1715. else:
  1716. try:
  1717. f = open(filename, 'w')
  1718. defaults_file_content = f.read()
  1719. f.close()
  1720. except IOError:
  1721. App.log.debug('Creating a new preferences file ...')
  1722. f = open(filename, 'w')
  1723. json.dump({}, f)
  1724. f.close()
  1725. except:
  1726. e = sys.exc_info()[0]
  1727. App.log.error("Could not load defaults file.")
  1728. App.log.error(str(e))
  1729. self.inform.emit("[ERROR_NOTCL]Could not load defaults file.")
  1730. return
  1731. try:
  1732. defaults_from_file = json.loads(defaults_file_content)
  1733. except:
  1734. App.log.warning("Trying to read an empty Preferences file. Continue.")
  1735. # Update options
  1736. self.defaults_read_form()
  1737. defaults_from_file.update(self.defaults)
  1738. self.propagate_defaults(silent=True)
  1739. # Save update options
  1740. try:
  1741. f = open(filename, "w")
  1742. json.dump(defaults_from_file, f)
  1743. f.close()
  1744. except:
  1745. self.inform.emit("[ERROR_NOTCL] Failed to write defaults to file.")
  1746. return
  1747. self.file_saved.emit("preferences", filename)
  1748. self.inform.emit("[success]Exported Defaults to %s" % filename)
  1749. def on_preferences_open_folder(self):
  1750. self.report_usage("on_preferences_open_folder()")
  1751. if sys.platform == 'win32':
  1752. subprocess.Popen('explorer %s' % self.data_path)
  1753. elif sys.platform == 'darwin':
  1754. os.system('open "%s"' % self.data_path)
  1755. else:
  1756. subprocess.Popen(['xdg-open', self.data_path])
  1757. self.inform.emit("[success]FlatCAM Preferences Folder opened.")
  1758. def save_geometry(self, x, y, width, height, notebook_width):
  1759. self.defaults["global_def_win_x"] = x
  1760. self.defaults["global_def_win_y"] = y
  1761. self.defaults["global_def_win_w"] = width
  1762. self.defaults["global_def_win_h"] = height
  1763. self.defaults["def_notebook_width"] = notebook_width
  1764. self.save_defaults()
  1765. def message_dialog(self, title, message, kind="info"):
  1766. icon = {"info": QtWidgets.QMessageBox.Information,
  1767. "warning": QtWidgets.QMessageBox.Warning,
  1768. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  1769. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  1770. dlg.setText(message)
  1771. dlg.exec_()
  1772. def register_recent(self, kind, filename):
  1773. self.log.debug("register_recent()")
  1774. self.log.debug(" %s" % kind)
  1775. self.log.debug(" %s" % filename)
  1776. record = {'kind': str(kind), 'filename': str(filename)}
  1777. if record in self.recent:
  1778. return
  1779. self.recent.insert(0, record)
  1780. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  1781. self.recent.pop()
  1782. try:
  1783. f = open(self.data_path + '/recent.json', 'w')
  1784. except IOError:
  1785. App.log.error("Failed to open recent items file for writing.")
  1786. self.inform.emit('[ERROR_NOTCL]Failed to open recent files file for writing.')
  1787. return
  1788. #try:
  1789. json.dump(self.recent, f)
  1790. # except:
  1791. # App.log.error("Failed to write to recent items file.")
  1792. # self.inform.emit('ERROR: Failed to write to recent items file.')
  1793. # f.close()
  1794. f.close()
  1795. # Re-buid the recent items menu
  1796. self.setup_recent_items()
  1797. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  1798. """
  1799. Creates a new specalized FlatCAMObj and attaches it to the application,
  1800. this is, updates the GUI accordingly, any other records and plots it.
  1801. This method is thread-safe.
  1802. Notes:
  1803. * If the name is in use, the self.collection will modify it
  1804. when appending it to the collection. There is no need to handle
  1805. name conflicts here.
  1806. :param kind: The kind of object to create. One of 'gerber',
  1807. 'excellon', 'cncjob' and 'geometry'.
  1808. :type kind: str
  1809. :param name: Name for the object.
  1810. :type name: str
  1811. :param initialize: Function to run after creation of the object
  1812. but before it is attached to the application. The function is
  1813. called with 2 parameters: the new object and the App instance.
  1814. :type initialize: function
  1815. :return: None
  1816. :rtype: None
  1817. """
  1818. App.log.debug("new_object()")
  1819. self.plot = plot
  1820. self.autoselected = autoselected
  1821. t0 = time.time() # Debug
  1822. ## Create object
  1823. classdict = {
  1824. "gerber": FlatCAMGerber,
  1825. "excellon": FlatCAMExcellon,
  1826. "cncjob": FlatCAMCNCjob,
  1827. "geometry": FlatCAMGeometry
  1828. }
  1829. App.log.debug("Calling object constructor...")
  1830. obj = classdict[kind](name)
  1831. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  1832. # Set options from "Project options" form
  1833. self.options_read_form()
  1834. # IMPORTANT
  1835. # The key names in defaults and options dictionary's are not random:
  1836. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  1837. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  1838. # the options from project options form into the self.options. After that, below, depending on the type of
  1839. # object that is created, it will strip the name of the object and the underline (if the original key was
  1840. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  1841. # "toolchange"
  1842. for option in self.options:
  1843. if option.find(kind + "_") == 0:
  1844. oname = option[len(kind) + 1:]
  1845. obj.options[oname] = self.options[option]
  1846. # if kind == 'geometry':
  1847. # obj.tools = {}
  1848. # elif kind == 'cncjob':
  1849. # obj.cnc_tools = {}
  1850. # Initialize as per user request
  1851. # User must take care to implement initialize
  1852. # in a thread-safe way as is is likely that we
  1853. # have been invoked in a separate thread.
  1854. t1 = time.time()
  1855. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  1856. try:
  1857. return_value = initialize(obj, self)
  1858. except Exception as e:
  1859. msg = "[ERROR_NOTCL] An internal error has ocurred. See shell.\n"
  1860. msg += "Object (%s) failed because: %s \n\n" % (kind, str(e))
  1861. msg += traceback.format_exc()
  1862. self.inform.emit(msg)
  1863. # if str(e) == "Empty Geometry":
  1864. # self.inform.emit("[ERROR_NOTCL] )
  1865. # else:
  1866. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  1867. return "fail"
  1868. t2 = time.time()
  1869. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  1870. if return_value == 'fail':
  1871. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  1872. return "fail"
  1873. # Check units and convert if necessary
  1874. # This condition CAN be true because initialize() can change obj.units
  1875. if self.options["units"].upper() != obj.units.upper():
  1876. self.inform.emit("Converting units to " + self.options["units"] + ".")
  1877. obj.convert_units(self.options["units"])
  1878. t3 = time.time()
  1879. self.log.debug("%f seconds converting units." % (t3 - t2))
  1880. # Create the bounding box for the object and then add the results to the obj.options
  1881. try:
  1882. xmin, ymin, xmax, ymax = obj.bounds()
  1883. obj.options['xmin'] = xmin
  1884. obj.options['ymin'] = ymin
  1885. obj.options['xmax'] = xmax
  1886. obj.options['ymax'] = ymax
  1887. except:
  1888. log.warning("The object has no bounds properties.")
  1889. # don't plot objects with no bounds, there is nothing to plot
  1890. self.plot = False
  1891. pass
  1892. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  1893. # Move the object to the main thread and let the app know that it is available.
  1894. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  1895. self.object_created.emit(obj, self.plot, self.autoselected)
  1896. return obj
  1897. def new_excellon_object(self):
  1898. self.report_usage("new_excellon_object()")
  1899. self.new_object('excellon', 'new_e', lambda x, y: None, plot=False)
  1900. def new_geometry_object(self):
  1901. self.report_usage("new_geometry_object()")
  1902. def initialize(obj, self):
  1903. obj.multitool = False
  1904. self.new_object('geometry', 'new_g', initialize, plot=False)
  1905. def on_object_created(self, obj, plot, autoselect):
  1906. """
  1907. Event callback for object creation.
  1908. :param obj: The newly created FlatCAM object.
  1909. :return: None
  1910. """
  1911. t0 = time.time() # DEBUG
  1912. self.log.debug("on_object_created()")
  1913. # The Collection might change the name if there is a collision
  1914. self.collection.append(obj)
  1915. # after adding the object to the collection always update the list of objects that are in the collection
  1916. self.all_objects_list = self.collection.get_list()
  1917. # self.inform.emit('[selected] %s created & selected: %s' %
  1918. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  1919. if obj.kind == 'gerber':
  1920. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1921. (obj.kind.capitalize(), 'green', str(obj.options['name'])))
  1922. elif obj.kind == 'excellon':
  1923. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1924. (obj.kind.capitalize(), 'brown', str(obj.options['name'])))
  1925. elif obj.kind == 'cncjob':
  1926. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1927. (obj.kind.capitalize(), 'blue', str(obj.options['name'])))
  1928. elif obj.kind == 'geometry':
  1929. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1930. (obj.kind.capitalize(), 'red', str(obj.options['name'])))
  1931. # self.new_object_available.emit(obj)
  1932. # update the SHELL auto-completer model with the name of the new object
  1933. self.myKeywords.append(obj.options['name'])
  1934. self.shell._edit.set_model_data(self.myKeywords)
  1935. if autoselect:
  1936. # select the just opened object but deselect the previous ones
  1937. self.collection.set_all_inactive()
  1938. self.collection.set_active(obj.options["name"])
  1939. # here it is done the object plotting
  1940. def worker_task(obj):
  1941. with self.proc_container.new("Plotting"):
  1942. if isinstance(obj, FlatCAMCNCjob):
  1943. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  1944. else:
  1945. obj.plot()
  1946. t1 = time.time() # DEBUG
  1947. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  1948. self.object_plotted.emit(obj)
  1949. # Send to worker
  1950. # self.worker.add_task(worker_task, [self])
  1951. if plot is True:
  1952. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  1953. def on_object_changed(self, obj):
  1954. # update the bounding box data from obj.options
  1955. xmin, ymin, xmax, ymax = obj.bounds()
  1956. obj.options['xmin'] = xmin
  1957. obj.options['ymin'] = ymin
  1958. obj.options['xmax'] = xmax
  1959. obj.options['ymax'] = ymax
  1960. log.debug("Object changed, updating the bounding box data on self.options")
  1961. # delete the old selection shape
  1962. self.delete_selection_shape()
  1963. def on_object_plotted(self, obj):
  1964. self.on_zoom_fit(None)
  1965. def options_read_form(self):
  1966. for option in self.options_form_fields:
  1967. self.options[option] = self.options_form_fields[option].get_value()
  1968. def options_write_form(self):
  1969. for option in self.options:
  1970. self.options_write_form_field(option)
  1971. def options_write_form_field(self, field):
  1972. try:
  1973. self.options_form_fields[field].set_value(self.options[field])
  1974. except KeyError:
  1975. # Changed from error to debug. This allows to have data stored
  1976. # which is not user-editable.
  1977. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  1978. pass
  1979. def on_about(self):
  1980. """
  1981. Displays the "about" dialog.
  1982. :return: None
  1983. """
  1984. self.report_usage("on_about")
  1985. version = self.version
  1986. version_date = self.version_date
  1987. beta = self.beta
  1988. class AboutDialog(QtWidgets.QDialog):
  1989. def __init__(self, parent=None):
  1990. QtWidgets.QDialog.__init__(self, parent)
  1991. # Icon and title
  1992. self.setWindowIcon(parent.app_icon)
  1993. self.setWindowTitle("FlatCAM")
  1994. layout1 = QtWidgets.QVBoxLayout()
  1995. self.setLayout(layout1)
  1996. layout2 = QtWidgets.QHBoxLayout()
  1997. layout1.addLayout(layout2)
  1998. logo = QtWidgets.QLabel()
  1999. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2000. layout2.addWidget(logo, stretch=0)
  2001. title = QtWidgets.QLabel(
  2002. "<font size=8><B>FlatCAM</B></font><BR>"
  2003. "Version %s %s (%s) - %s <BR>"
  2004. "<BR>"
  2005. "2D Computer-Aided Printed Circuit Board<BR>"
  2006. "Manufacturing.<BR>"
  2007. "<BR>"
  2008. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2009. "<BR>"
  2010. "<B> Main Contributors:</B><BR>"
  2011. "Denis Hayrullin<BR>"
  2012. "Kamil Sopko<BR>"
  2013. "Marius Stanciu<BR>"
  2014. "Matthieu Berthomé<BR>"
  2015. "and many others found "
  2016. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2017. "<BR>"
  2018. "Development is done "
  2019. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2020. "DOWNLOAD area "
  2021. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2022. "" % (version, ('BETA' if beta else ''), version_date, platform.architecture()[0])
  2023. )
  2024. title.setOpenExternalLinks(True)
  2025. layout2.addWidget(title, stretch=1)
  2026. layout3 = QtWidgets.QHBoxLayout()
  2027. layout1.addLayout(layout3)
  2028. layout3.addStretch()
  2029. okbtn = QtWidgets.QPushButton("Close")
  2030. layout3.addWidget(okbtn)
  2031. okbtn.clicked.connect(self.accept)
  2032. AboutDialog(self.ui).exec_()
  2033. def on_file_savedefaults(self):
  2034. """
  2035. Callback for menu item File->Save Defaults. Saves application default options
  2036. ``self.defaults`` to current_defaults.FlatConfig.
  2037. :return: None
  2038. """
  2039. self.save_defaults()
  2040. def on_app_exit(self):
  2041. self.report_usage("on_app_exit()")
  2042. if self.collection.get_list():
  2043. msgbox = QtWidgets.QMessageBox()
  2044. # msgbox.setText("<B>Save changes ...</B>")
  2045. msgbox.setText("There are files/objects opened in FlatCAM. "
  2046. "\n"
  2047. "Do you want to Save the project?")
  2048. msgbox.setWindowTitle("Save changes")
  2049. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2050. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2051. QtWidgets.QMessageBox.Cancel)
  2052. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2053. response = msgbox.exec_()
  2054. if response == QtWidgets.QMessageBox.Yes:
  2055. self.on_file_saveprojectas(thread=False)
  2056. elif response == QtWidgets.QMessageBox.Cancel:
  2057. return
  2058. self.save_defaults()
  2059. else:
  2060. self.save_defaults()
  2061. log.debug("Application defaults saved ... Exit event.")
  2062. QtWidgets.qApp.quit()
  2063. def save_defaults(self, silent=False):
  2064. """
  2065. Saves application default options
  2066. ``self.defaults`` to current_defaults.FlatConfig.
  2067. :return: None
  2068. """
  2069. self.report_usage("save_defaults")
  2070. # Read options from file
  2071. try:
  2072. f = open(self.data_path + "/current_defaults.FlatConfig")
  2073. defaults_file_content = f.read()
  2074. f.close()
  2075. except:
  2076. e = sys.exc_info()[0]
  2077. App.log.error("Could not load defaults file.")
  2078. App.log.error(str(e))
  2079. self.inform.emit("[ERROR_NOTCL] Could not load defaults file.")
  2080. return
  2081. try:
  2082. defaults = json.loads(defaults_file_content)
  2083. except:
  2084. e = sys.exc_info()[0]
  2085. App.log.error("Failed to parse defaults file.")
  2086. App.log.error(str(e))
  2087. self.inform.emit("[ERROR_NOTCL] Failed to parse defaults file.")
  2088. return
  2089. # Update options
  2090. self.defaults_read_form()
  2091. defaults.update(self.defaults)
  2092. self.propagate_defaults(silent=True)
  2093. # Save update options
  2094. try:
  2095. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2096. json.dump(defaults, f)
  2097. f.close()
  2098. except:
  2099. self.inform.emit("[ERROR_NOTCL] Failed to write defaults to file.")
  2100. return
  2101. # Save the toolbar view
  2102. tb_status = 0
  2103. if self.ui.toolbarfile.isVisible():
  2104. tb_status += 1
  2105. if self.ui.toolbargeo.isVisible():
  2106. tb_status += 2
  2107. if self.ui.toolbarview.isVisible():
  2108. tb_status += 4
  2109. if self.ui.toolbartools.isVisible():
  2110. tb_status += 8
  2111. if self.ui.exc_edit_toolbar.isVisible():
  2112. tb_status += 16
  2113. if self.ui.geo_edit_toolbar.isVisible():
  2114. tb_status += 32
  2115. if self.ui.snap_toolbar.isVisible():
  2116. tb_status += 64
  2117. self.defaults["global_toolbar_view"] = tb_status
  2118. if not silent:
  2119. self.inform.emit("[success]Defaults saved.")
  2120. def save_factory_defaults(self, silent=False):
  2121. """
  2122. Saves application factory default options
  2123. ``self.defaults`` to factory_defaults.FlatConfig.
  2124. It's a one time job done just after the first install.
  2125. :return: None
  2126. """
  2127. self.report_usage("save_factory_defaults")
  2128. # Read options from file
  2129. try:
  2130. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2131. factory_defaults_file_content = f_f_def.read()
  2132. f_f_def.close()
  2133. except:
  2134. e = sys.exc_info()[0]
  2135. App.log.error("Could not load factory defaults file.")
  2136. App.log.error(str(e))
  2137. self.inform.emit("[ERROR_NOTCL] Could not load factory defaults file.")
  2138. return
  2139. try:
  2140. factory_defaults = json.loads(factory_defaults_file_content)
  2141. except:
  2142. e = sys.exc_info()[0]
  2143. App.log.error("Failed to parse factory defaults file.")
  2144. App.log.error(str(e))
  2145. self.inform.emit("[ERROR_NOTCL] Failed to parse factory defaults file.")
  2146. return
  2147. # Update options
  2148. self.defaults_read_form()
  2149. factory_defaults.update(self.defaults)
  2150. self.propagate_defaults(silent=True)
  2151. # Save update options
  2152. try:
  2153. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2154. json.dump(factory_defaults, f_f_def_s)
  2155. f_f_def_s.close()
  2156. except:
  2157. self.inform.emit("[ERROR_NOTCL] Failed to write factory defaults to file.")
  2158. return
  2159. if silent is False:
  2160. self.inform.emit("Factory defaults saved.")
  2161. def final_save(self):
  2162. if self.collection.get_list():
  2163. msgbox = QtWidgets.QMessageBox()
  2164. # msgbox.setText("<B>Save changes ...</B>")
  2165. msgbox.setText("There are files/objects opened in FlatCAM. "
  2166. "\n"
  2167. "Do you want to Save the project?")
  2168. msgbox.setWindowTitle("Save changes")
  2169. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2170. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2171. QtWidgets.QMessageBox.Cancel)
  2172. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2173. response = msgbox.exec_()
  2174. if response == QtWidgets.QMessageBox.Yes:
  2175. self.on_file_saveprojectas(thread=False)
  2176. elif response == QtWidgets.QMessageBox.Cancel:
  2177. self.should_we_quit = False
  2178. return
  2179. self.save_defaults()
  2180. log.debug("Application defaults saved ... Exit event.")
  2181. def on_toggle_shell(self):
  2182. """
  2183. toggle shell if is visible close it if closed open it
  2184. :return:
  2185. """
  2186. self.report_usage("on_toggle_shell()")
  2187. if self.ui.shell_dock.isVisible():
  2188. self.ui.shell_dock.hide()
  2189. else:
  2190. self.ui.shell_dock.show()
  2191. def on_edit_join(self, name=None):
  2192. """
  2193. Callback for Edit->Join. Joins the selected geometry objects into
  2194. a new one.
  2195. :return: None
  2196. """
  2197. self.report_usage("on_edit_join()")
  2198. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2199. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2200. tooldias = []
  2201. geo_type_list = []
  2202. objs = self.collection.get_selected()
  2203. for obj in objs:
  2204. geo_type_list.append(obj.multigeo)
  2205. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2206. if len(set(geo_type_list)) != 1:
  2207. self.inform.emit("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2208. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2209. "convert from one to another and retry joining \n"
  2210. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2211. "the result may not be what was expected. \n"
  2212. "Check the generated GCODE.")
  2213. return
  2214. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2215. if True in geo_type_list:
  2216. def initialize(obj, app):
  2217. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2218. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2219. for v in obj.tools.values():
  2220. v['data']['name'] = obj_name_multi
  2221. self.new_object("geometry", obj_name_multi, initialize)
  2222. else:
  2223. def initialize(obj, app):
  2224. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2225. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2226. for v in obj.tools.values():
  2227. v['data']['name'] = obj_name_single
  2228. self.new_object("geometry", obj_name_single, initialize)
  2229. def on_edit_join_exc(self):
  2230. """
  2231. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2232. a new one.
  2233. :return: None
  2234. """
  2235. self.report_usage("on_edit_join_exc()")
  2236. objs = self.collection.get_selected()
  2237. for obj in objs:
  2238. if not isinstance(obj, FlatCAMExcellon):
  2239. self.inform.emit("[ERROR_NOTCL]Failed. Excellon joining works only on Excellon objects.")
  2240. return
  2241. def initialize(obj, app):
  2242. FlatCAMExcellon.merge(objs, obj)
  2243. self.new_object("excellon", 'Combo_Excellon', initialize)
  2244. def on_edit_join_grb(self):
  2245. """
  2246. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2247. a new one.
  2248. :return: None
  2249. """
  2250. self.report_usage("on_edit_join_grb()")
  2251. objs = self.collection.get_selected()
  2252. for obj in objs:
  2253. if not isinstance(obj, FlatCAMGerber):
  2254. self.inform.emit("[ERROR_NOTCL]Failed. Gerber joining works only on Gerber objects.")
  2255. return
  2256. def initialize(obj, app):
  2257. FlatCAMGerber.merge(objs, obj)
  2258. self.new_object("gerber", 'Combo_Gerber', initialize)
  2259. def on_convert_singlegeo_to_multigeo(self):
  2260. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2261. obj = self.collection.get_active()
  2262. if obj is None:
  2263. self.inform.emit("[ERROR_NOTCL]Failed. Select a Geometry Object and try again.")
  2264. return
  2265. if not isinstance(obj, FlatCAMGeometry):
  2266. self.inform.emit("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s" % type(obj))
  2267. return
  2268. obj.multigeo = True
  2269. for tooluid, dict_value in obj.tools.items():
  2270. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2271. if not isinstance(obj.solid_geometry, list):
  2272. obj.solid_geometry = [obj.solid_geometry]
  2273. obj.solid_geometry[:] = []
  2274. obj.plot()
  2275. self.inform.emit("[success] A Geometry object was converted to MultiGeo type.")
  2276. def on_convert_multigeo_to_singlegeo(self):
  2277. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2278. obj = self.collection.get_active()
  2279. if obj is None:
  2280. self.inform.emit("[ERROR_NOTCL]Failed. Select a Geometry Object and try again.")
  2281. return
  2282. if not isinstance(obj, FlatCAMGeometry):
  2283. self.inform.emit("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s" % type(obj))
  2284. return
  2285. obj.multigeo = False
  2286. total_solid_geometry = []
  2287. for tooluid, dict_value in obj.tools.items():
  2288. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2289. # clear the original geometry
  2290. dict_value['solid_geometry'][:] = []
  2291. obj.solid_geometry = deepcopy(total_solid_geometry)
  2292. obj.plot()
  2293. self.inform.emit("[success] A Geometry object was converted to SingleGeo type.")
  2294. def on_options_dict_change(self, field):
  2295. self.options_write_form_field(field)
  2296. if field == "units":
  2297. self.set_screen_units(self.options['units'])
  2298. def on_defaults_dict_change(self, field):
  2299. self.defaults_write_form_field(field)
  2300. def set_screen_units(self, units):
  2301. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  2302. def on_toggle_units(self):
  2303. """
  2304. Callback for the Units radio-button change in the Options tab.
  2305. Changes the application's default units or the current project's units.
  2306. If changing the project's units, the change propagates to all of
  2307. the objects in the project.
  2308. :return: None
  2309. """
  2310. self.report_usage("on_toggle_units")
  2311. if self.toggle_units_ignore:
  2312. return
  2313. # If option is the same, then ignore
  2314. if self.general_options_form.general_app_group.units_radio.get_value().upper() == self.options["units"].upper():
  2315. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  2316. return
  2317. # Options to scale
  2318. dimensions = ['gerber_isotooldia', 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2319. 'gerber_noncoppermargin', 'gerber_bboxmargin','gerber_isooverlap','tools_nccoverlap',
  2320. 'tools_nccmargin','tools_cutouttooldia','tools_cutoutgapsize',
  2321. 'gerber_noncoppermargin','gerber_bboxmargin',
  2322. 'excellon_drillz', "excellon_toolchangexy",
  2323. 'excellon_travelz', 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2324. 'excellon_tooldia', 'excellon_endz', 'cncjob_tooldia',
  2325. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate', 'geometry_feedrate_rapid',
  2326. 'geometry_cnctooldia', 'tools_painttooldia', 'tools_paintoverlap', 'geometry_toolchangexy',
  2327. 'geometry_toolchangez',
  2328. 'tools_paintmargin', 'geometry_endz', 'geometry_depthperpass', 'global_gridx', 'global_gridy']
  2329. def scale_options(sfactor):
  2330. for dim in dimensions:
  2331. if dim == 'excellon_toolchangexy':
  2332. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2333. coords_xy[0] *= sfactor
  2334. coords_xy[1] *= sfactor
  2335. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2336. elif dim == 'geometry_toolchangexy':
  2337. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2338. coords_xy[0] *= sfactor
  2339. coords_xy[1] *= sfactor
  2340. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2341. else:
  2342. self.options[dim] *= sfactor
  2343. # The scaling factor depending on choice of units.
  2344. factor = 1/25.4
  2345. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2346. factor = 25.4
  2347. # Changing project units. Warn user.
  2348. msgbox = QtWidgets.QMessageBox()
  2349. msgbox.setText("<B>Change project units ...</B>")
  2350. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2351. "properties of all objects to be scaled accordingly. Continue?")
  2352. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2353. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2354. response = msgbox.exec_()
  2355. if response == QtWidgets.QMessageBox.Ok:
  2356. self.options_read_form()
  2357. scale_options(factor)
  2358. self.options_write_form()
  2359. # change this only if the workspace is active
  2360. if self.defaults['global_workspace'] is True:
  2361. self.plotcanvas.draw_workspace()
  2362. # adjust the grid values on the main toolbar
  2363. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2364. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2365. for obj in self.collection.get_list():
  2366. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  2367. obj.convert_units(units)
  2368. # make that the properties stored in the object are also updated
  2369. self.object_changed.emit(obj)
  2370. obj.build_ui()
  2371. current = self.collection.get_active()
  2372. if current is not None:
  2373. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2374. if not isinstance(current, FlatCAMGeometry):
  2375. current.to_form()
  2376. self.plot_all()
  2377. self.inform.emit("[success]Converted units to %s" % self.options["units"])
  2378. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  2379. self.set_screen_units(self.options["units"])
  2380. else:
  2381. # Undo toggling
  2382. self.toggle_units_ignore = True
  2383. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2384. self.general_options_form.general_app_group.units_radio.set_value('IN')
  2385. else:
  2386. self.general_options_form.general_app_group.units_radio.set_value('MM')
  2387. self.toggle_units_ignore = False
  2388. self.inform.emit("[WARNING_NOTCL]Units conversion cancelled.")
  2389. self.options_read_form()
  2390. def on_toggle_units_click(self):
  2391. if self.options["units"] == 'MM':
  2392. self.general_options_form.general_app_group.units_radio.set_value("IN")
  2393. else:
  2394. self.general_options_form.general_app_group.units_radio.set_value("MM")
  2395. self.on_toggle_units()
  2396. def on_language_apply(self):
  2397. self.report_usage("on_language_apply()")
  2398. # TODO: apply the language
  2399. # app restart section
  2400. pass
  2401. def on_fullscreen(self):
  2402. self.report_usage("on_fullscreen()")
  2403. if self.toggle_fscreen is False:
  2404. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  2405. tb.setVisible(False)
  2406. self.ui.splitter_left.setVisible(False)
  2407. self.toggle_fscreen = True
  2408. else:
  2409. self.restore_toolbar_view()
  2410. self.ui.splitter_left.setVisible(True)
  2411. self.toggle_fscreen = False
  2412. def on_toggle_plotarea(self):
  2413. self.report_usage("on_toggle_plotarea()")
  2414. try:
  2415. name = self.ui.plot_tab_area.widget(0).objectName()
  2416. except AttributeError:
  2417. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  2418. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2419. self.ui.plot_tab_area.protectTab(0)
  2420. return
  2421. if name != 'plotarea':
  2422. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  2423. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2424. self.ui.plot_tab_area.protectTab(0)
  2425. else:
  2426. self.ui.plot_tab_area.closeTab(0)
  2427. def on_toggle_notebook(self):
  2428. if self.ui.splitter.sizes()[0] == 0:
  2429. self.ui.splitter.setSizes([1, 1])
  2430. else:
  2431. self.ui.splitter.setSizes([0, 1])
  2432. def on_toggle_axis(self):
  2433. self.report_usage("on_toggle_axis()")
  2434. if self.toggle_axis is False:
  2435. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2436. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2437. self.plotcanvas.redraw()
  2438. self.toggle_axis = True
  2439. else:
  2440. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2441. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2442. self.plotcanvas.redraw()
  2443. self.toggle_axis = False
  2444. def on_toggle_grid(self):
  2445. self.report_usage("on_toggle_grid()")
  2446. self.ui.grid_snap_btn.trigger()
  2447. def on_options_combo_change(self, sel):
  2448. """
  2449. Called when the combo box to choose between application defaults and
  2450. project option changes value. The corresponding variables are
  2451. copied to the UI.
  2452. :param sel: The option index that was chosen.
  2453. :return: None
  2454. """
  2455. # combo_sel = self.ui.notebook.combo_options.get_active()
  2456. App.log.debug("Options --> %s" % sel)
  2457. # form = [self.defaults_form, self.options_form][sel]
  2458. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2459. if sel == 0:
  2460. self.gen_form = self.general_defaults_form
  2461. self.ger_form = self.gerber_defaults_form
  2462. self.exc_form = self.excellon_defaults_form
  2463. self.geo_form = self.geometry_defaults_form
  2464. self.cnc_form = self.cncjob_defaults_form
  2465. self.tools_form = self.tools_defaults_form
  2466. elif sel == 1:
  2467. self.gen_form = self.general_options_form
  2468. self.ger_form = self.gerber_options_form
  2469. self.exc_form = self.excellon_options_form
  2470. self.geo_form = self.geometry_options_form
  2471. self.cnc_form = self.cncjob_options_form
  2472. self.tools_form = self.tools_options_form
  2473. else:
  2474. return
  2475. try:
  2476. self.ui.general_scroll_area.takeWidget()
  2477. except:
  2478. self.log.debug("Nothing to remove")
  2479. self.ui.general_scroll_area.setWidget(self.gen_form)
  2480. self.gen_form.show()
  2481. try:
  2482. self.ui.gerber_scroll_area.takeWidget()
  2483. except:
  2484. self.log.debug("Nothing to remove")
  2485. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2486. self.ger_form.show()
  2487. try:
  2488. self.ui.excellon_scroll_area.takeWidget()
  2489. except:
  2490. self.log.debug("Nothing to remove")
  2491. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2492. self.exc_form.show()
  2493. try:
  2494. self.ui.geometry_scroll_area.takeWidget()
  2495. except:
  2496. self.log.debug("Nothing to remove")
  2497. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2498. self.geo_form.show()
  2499. try:
  2500. self.ui.cncjob_scroll_area.takeWidget()
  2501. except:
  2502. self.log.debug("Nothing to remove")
  2503. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2504. self.cnc_form.show()
  2505. try:
  2506. self.ui.tools_scroll_area.takeWidget()
  2507. except:
  2508. self.log.debug("Nothing to remove")
  2509. self.ui.tools_scroll_area.setWidget(self.tools_form)
  2510. self.tools_form.show()
  2511. self.log.debug("Finished GUI form initialization.")
  2512. # self.options2form()
  2513. def on_excellon_defaults_button(self):
  2514. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2515. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2516. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2517. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2518. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2519. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2520. log.debug("Excellon app defaults loaded ...")
  2521. def on_excellon_options_button(self):
  2522. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2523. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2524. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2525. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2526. self.options_form_fields["excellon_zeros"].set_value('L')
  2527. self.options_form_fields["excellon_units"].set_value('INCH')
  2528. log.debug("Excellon options defaults loaded ...")
  2529. # Setting plot colors handlers
  2530. def on_pf_color_entry(self):
  2531. self.defaults['global_plot_fill'] = self.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  2532. self.defaults['global_plot_fill'][7:9]
  2533. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2534. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2535. def on_pf_color_button(self):
  2536. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2537. c_dialog = QtWidgets.QColorDialog()
  2538. plot_fill_color = c_dialog.getColor(initial=current_color)
  2539. if plot_fill_color.isValid() is False:
  2540. return
  2541. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2542. "background-color:%s" % str(plot_fill_color.name()))
  2543. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2544. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  2545. self.defaults['global_plot_fill'] = new_val
  2546. def on_pf_color_spinner(self):
  2547. spinner_value = self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  2548. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  2549. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2550. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2551. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2552. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2553. def on_pf_color_slider(self):
  2554. slider_value = self.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  2555. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  2556. def on_pl_color_entry(self):
  2557. self.defaults['global_plot_line'] = self.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  2558. self.defaults['global_plot_line'][7:9]
  2559. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2560. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2561. def on_pl_color_button(self):
  2562. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2563. # print(current_color)
  2564. c_dialog = QtWidgets.QColorDialog()
  2565. plot_line_color = c_dialog.getColor(initial=current_color)
  2566. if plot_line_color.isValid() is False:
  2567. return
  2568. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2569. "background-color:%s" % str(plot_line_color.name()))
  2570. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2571. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  2572. self.defaults['global_plot_line'] = new_val_line
  2573. # Setting selection colors (left - right) handlers
  2574. def on_sf_color_entry(self):
  2575. self.defaults['global_sel_fill'] = self.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  2576. self.defaults['global_sel_fill'][7:9]
  2577. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2578. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2579. def on_sf_color_button(self):
  2580. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2581. c_dialog = QtWidgets.QColorDialog()
  2582. plot_fill_color = c_dialog.getColor(initial=current_color)
  2583. if plot_fill_color.isValid() is False:
  2584. return
  2585. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2586. "background-color:%s" % str(plot_fill_color.name()))
  2587. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2588. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  2589. self.defaults['global_sel_fill'] = new_val
  2590. def on_sf_color_spinner(self):
  2591. spinner_value = self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  2592. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  2593. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2594. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2595. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2596. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2597. def on_sf_color_slider(self):
  2598. slider_value = self.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  2599. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  2600. def on_sl_color_entry(self):
  2601. self.defaults['global_sel_line'] = self.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  2602. self.defaults['global_sel_line'][7:9]
  2603. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2604. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2605. def on_sl_color_button(self):
  2606. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2607. c_dialog = QtWidgets.QColorDialog()
  2608. plot_line_color = c_dialog.getColor(initial=current_color)
  2609. if plot_line_color.isValid() is False:
  2610. return
  2611. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2612. "background-color:%s" % str(plot_line_color.name()))
  2613. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2614. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  2615. self.defaults['global_sel_line'] = new_val_line
  2616. # Setting selection colors (right - left) handlers
  2617. def on_alt_sf_color_entry(self):
  2618. self.defaults['global_alt_sel_fill'] = self.general_defaults_form.general_gui_group \
  2619. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2620. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2621. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2622. def on_alt_sf_color_button(self):
  2623. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2624. c_dialog = QtWidgets.QColorDialog()
  2625. plot_fill_color = c_dialog.getColor(initial=current_color)
  2626. if plot_fill_color.isValid() is False:
  2627. return
  2628. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2629. "background-color:%s" % str(plot_fill_color.name()))
  2630. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2631. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  2632. self.defaults['global_alt_sel_fill'] = new_val
  2633. def on_alt_sf_color_spinner(self):
  2634. spinner_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  2635. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2636. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2637. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2638. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2639. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2640. def on_alt_sf_color_slider(self):
  2641. slider_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  2642. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2643. def on_alt_sl_color_entry(self):
  2644. self.defaults['global_alt_sel_line'] = self.general_defaults_form.general_gui_group \
  2645. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2646. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2647. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2648. def on_alt_sl_color_button(self):
  2649. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2650. c_dialog = QtWidgets.QColorDialog()
  2651. plot_line_color = c_dialog.getColor(initial=current_color)
  2652. if plot_line_color.isValid() is False:
  2653. return
  2654. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2655. "background-color:%s" % str(plot_line_color.name()))
  2656. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2657. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  2658. self.defaults['global_alt_sel_line'] = new_val_line
  2659. # Setting Editor colors
  2660. def on_draw_color_entry(self):
  2661. self.defaults['global_draw_color'] = self.general_defaults_form.general_gui_group \
  2662. .draw_color_entry.get_value()
  2663. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2664. "background-color:%s" % str(self.defaults['global_draw_color']))
  2665. def on_draw_color_button(self):
  2666. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2667. c_dialog = QtWidgets.QColorDialog()
  2668. draw_color = c_dialog.getColor(initial=current_color)
  2669. if draw_color.isValid() is False:
  2670. return
  2671. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2672. "background-color:%s" % str(draw_color.name()))
  2673. new_val = str(draw_color.name())
  2674. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  2675. self.defaults['global_draw_color'] = new_val
  2676. def on_sel_draw_color_entry(self):
  2677. self.defaults['global_sel_draw_color'] = self.general_defaults_form.general_gui_group \
  2678. .sel_draw_color_entry.get_value()
  2679. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2680. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  2681. def on_sel_draw_color_button(self):
  2682. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  2683. c_dialog = QtWidgets.QColorDialog()
  2684. sel_draw_color = c_dialog.getColor(initial=current_color)
  2685. if sel_draw_color.isValid() is False:
  2686. return
  2687. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2688. "background-color:%s" % str(sel_draw_color.name()))
  2689. new_val_sel = str(sel_draw_color.name())
  2690. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  2691. self.defaults['global_sel_draw_color'] = new_val_sel
  2692. def on_deselect_all(self):
  2693. self.collection.set_all_inactive()
  2694. self.delete_selection_shape()
  2695. def on_workspace_modified(self):
  2696. self.save_defaults(silent=True)
  2697. self.plotcanvas.draw_workspace()
  2698. def on_workspace(self):
  2699. self.report_usage("on_workspace()")
  2700. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2701. self.plotcanvas.restore_workspace()
  2702. else:
  2703. self.plotcanvas.delete_workspace()
  2704. self.save_defaults(silent=True)
  2705. def on_workspace_menu(self):
  2706. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2707. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  2708. else:
  2709. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  2710. self.on_workspace()
  2711. def on_layout(self):
  2712. self.report_usage("on_layout()")
  2713. current_layout= self.general_defaults_form.general_gui_group.layout_combo.get_value().lower()
  2714. settings = QSettings("Open Source", "FlatCAM")
  2715. settings.setValue('layout', current_layout)
  2716. # This will write the setting to the platform specific storage.
  2717. del settings
  2718. # first remove the toolbars:
  2719. self.ui.removeToolBar(self.ui.toolbarfile)
  2720. self.ui.removeToolBar(self.ui.toolbargeo)
  2721. self.ui.removeToolBar(self.ui.toolbarview)
  2722. self.ui.removeToolBar(self.ui.toolbartools)
  2723. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  2724. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  2725. self.ui.removeToolBar(self.ui.snap_toolbar)
  2726. if current_layout == 'standard':
  2727. ### TOOLBAR INSTALLATION ###
  2728. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  2729. self.ui.toolbarfile.setObjectName('File_TB')
  2730. self.ui.addToolBar(self.ui.toolbarfile)
  2731. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  2732. self.ui.toolbargeo.setObjectName('Edit_TB')
  2733. self.ui.addToolBar(self.ui.toolbargeo)
  2734. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  2735. self.ui.toolbarview.setObjectName('View_TB')
  2736. self.ui.addToolBar(self.ui.toolbarview)
  2737. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  2738. self.ui.toolbartools.setObjectName('Tools_TB')
  2739. self.ui.addToolBar(self.ui.toolbartools)
  2740. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  2741. self.ui.exc_edit_toolbar.setVisible(False)
  2742. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  2743. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  2744. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  2745. self.ui.geo_edit_toolbar.setVisible(False)
  2746. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  2747. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  2748. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  2749. self.ui.snap_toolbar.setObjectName('Snap_TB')
  2750. # self.ui.snap_toolbar.setMaximumHeight(30)
  2751. self.ui.addToolBar(self.ui.snap_toolbar)
  2752. self.ui.corner_snap_btn.setVisible(False)
  2753. self.ui.snap_magnet.setVisible(False)
  2754. elif current_layout == 'compact':
  2755. ### TOOLBAR INSTALLATION ###
  2756. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  2757. self.ui.toolbarfile.setObjectName('File_TB')
  2758. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  2759. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  2760. self.ui.toolbargeo.setObjectName('Edit_TB')
  2761. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  2762. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  2763. self.ui.toolbarview.setObjectName('View_TB')
  2764. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  2765. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  2766. self.ui.toolbartools.setObjectName('Tools_TB')
  2767. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  2768. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  2769. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  2770. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.exc_edit_toolbar)
  2771. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  2772. self.ui.geo_edit_toolbar.setVisible(False)
  2773. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  2774. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  2775. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  2776. self.ui.snap_toolbar.setObjectName('Snap_TB')
  2777. self.ui.snap_toolbar.setMaximumHeight(30)
  2778. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  2779. self.ui.corner_snap_btn.setVisible(True)
  2780. self.ui.snap_magnet.setVisible(True)
  2781. self.ui.populate_toolbars()
  2782. self.ui.grid_snap_btn.setChecked(True)
  2783. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  2784. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  2785. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  2786. self.ui.grid_gap_link_cb.setChecked(True)
  2787. def on_save_button(self):
  2788. self.save_defaults(silent=False)
  2789. # load the defaults so they are updated into the app
  2790. self.load_defaults(filename='current_defaults')
  2791. # Re-fresh project options
  2792. self.on_options_app2project()
  2793. def handleOpen(self):
  2794. self.report_usage("handleOpen()")
  2795. filter_group = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2796. "All Files (*.*)"
  2797. path, _ = QtWidgets.QFileDialog.getOpenFileName(
  2798. caption='Open file', directory=self.get_last_folder(), filter=filter_group)
  2799. if path:
  2800. file = QtCore.QFile(path)
  2801. if file.open(QtCore.QIODevice.ReadOnly):
  2802. stream = QtCore.QTextStream(file)
  2803. self.gcode_edited = stream.readAll()
  2804. self.ui.code_editor.setPlainText(self.gcode_edited)
  2805. file.close()
  2806. def handlePrint(self):
  2807. self.report_usage("handlePrint()")
  2808. dialog = QtPrintSupport.QPrintDialog()
  2809. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  2810. self.ui.code_editor.document().print_(dialog.printer())
  2811. def handlePreview(self):
  2812. self.report_usage("handlePreview()")
  2813. dialog = QtPrintSupport.QPrintPreviewDialog()
  2814. dialog.paintRequested.connect(self.ui.code_editor.print_)
  2815. dialog.exec_()
  2816. def handleTextChanged(self):
  2817. self.report_usage("handleTextChanged()")
  2818. # enable = not self.ui.code_editor.document().isEmpty()
  2819. # self.ui.buttonPrint.setEnabled(enable)
  2820. # self.ui.buttonPreview.setEnabled(enable)
  2821. pass
  2822. def handleSaveGCode(self):
  2823. self.report_usage("handleSaveGCode()")
  2824. obj_name = self.collection.get_active().options['name']
  2825. _filter_ = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2826. "All Files (*.*)"
  2827. try:
  2828. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  2829. caption="Export G-Code ...",
  2830. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  2831. filter=_filter_
  2832. )[0])
  2833. except TypeError:
  2834. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export G-Code ...", filter=_filter_)[0])
  2835. if filename == "":
  2836. self.inform.emit("[WARNING_NOTCL]Export CNC Code cancelled.")
  2837. return
  2838. else:
  2839. try:
  2840. my_gcode = self.ui.code_editor.toPlainText()
  2841. with open(filename, 'w') as f:
  2842. for line in my_gcode:
  2843. f.write(line)
  2844. except FileNotFoundError:
  2845. self.inform.emit("[WARNING] No such file or directory")
  2846. return
  2847. # Just for adding it to the recent files list.
  2848. self.file_opened.emit("cncjob", filename)
  2849. self.file_saved.emit("cncjob", filename)
  2850. self.inform.emit("Saved to: " + filename)
  2851. def handleFindGCode(self):
  2852. self.report_usage("handleFindGCode()")
  2853. flags = QtGui.QTextDocument.FindCaseSensitively
  2854. text_to_be_found = self.ui.entryFind.get_value()
  2855. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  2856. if r is False:
  2857. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2858. def handleReplaceGCode(self):
  2859. self.report_usage("handleReplaceGCode()")
  2860. old = self.ui.entryFind.get_value()
  2861. new = self.ui.entryReplace.get_value()
  2862. if self.ui.sel_all_cb.isChecked():
  2863. while True:
  2864. cursor = self.ui.code_editor.textCursor()
  2865. cursor.beginEditBlock()
  2866. flags = QtGui.QTextDocument.FindCaseSensitively
  2867. # self.ui.editor is the QPlainTextEdit
  2868. r = self.ui.code_editor.find(str(old), flags)
  2869. if r:
  2870. qc = self.ui.code_editor.textCursor()
  2871. if qc.hasSelection():
  2872. qc.insertText(new)
  2873. else:
  2874. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2875. break
  2876. # Mark end of undo block
  2877. cursor.endEditBlock()
  2878. else:
  2879. cursor = self.ui.code_editor.textCursor()
  2880. cursor.beginEditBlock()
  2881. qc = self.ui.code_editor.textCursor()
  2882. if qc.hasSelection():
  2883. qc.insertText(new)
  2884. # Mark end of undo block
  2885. cursor.endEditBlock()
  2886. def on_tool_add_keypress(self):
  2887. ## Current application units in Upper Case
  2888. self.units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  2889. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  2890. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  2891. if notebook_widget_name == 'selected_tab':
  2892. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  2893. tool_add_popup = FCInputDialog(title="New Tool ...",
  2894. text='Enter a Tool Diameter:',
  2895. min=0.0000, max=99.9999, decimals=4)
  2896. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  2897. val, ok = tool_add_popup.get_value()
  2898. if ok:
  2899. if float(val) == 0:
  2900. self.inform.emit(
  2901. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  2902. return
  2903. self.collection.get_active().on_tool_add(dia=float(val))
  2904. else:
  2905. self.inform.emit(
  2906. "[WARNING_NOTCL] Adding Tool cancelled ...")
  2907. # work only if the notebook tab on focus is the Tools_Tab
  2908. if notebook_widget_name == 'tool_tab':
  2909. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  2910. # and only if the tool is NCC Tool
  2911. if tool_widget == self.ncclear_tool.toolName:
  2912. tool_add_popup = FCInputDialog(title="New Tool ...",
  2913. text='Enter a Tool Diameter:',
  2914. min=0.0000, max=99.9999, decimals=4)
  2915. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  2916. val, ok = tool_add_popup.get_value()
  2917. if ok:
  2918. if float(val) == 0:
  2919. self.inform.emit(
  2920. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  2921. return
  2922. self.ncclear_tool.on_tool_add(dia=float(val))
  2923. else:
  2924. self.inform.emit(
  2925. "[WARNING_NOTCL] Adding Tool cancelled ...")
  2926. # and only if the tool is Paint Area Tool
  2927. elif tool_widget == self.paint_tool.toolName:
  2928. tool_add_popup = FCInputDialog(title="New Tool ...",
  2929. text='Enter a Tool Diameter:',
  2930. min=0.0000, max=99.9999, decimals=4)
  2931. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  2932. val, ok = tool_add_popup.get_value()
  2933. if ok:
  2934. if float(val) == 0:
  2935. self.inform.emit(
  2936. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  2937. return
  2938. self.paint_tool.on_tool_add(dia=float(val))
  2939. else:
  2940. self.inform.emit(
  2941. "[WARNING_NOTCL] Adding Tool cancelled ...")
  2942. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  2943. # See description bellow.
  2944. def on_delete_keypress(self):
  2945. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  2946. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  2947. if notebook_widget_name == 'selected_tab':
  2948. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  2949. self.collection.get_active().on_tool_delete()
  2950. # work only if the notebook tab on focus is the Tools_Tab
  2951. elif notebook_widget_name == 'tool_tab':
  2952. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  2953. # and only if the tool is NCC Tool
  2954. if tool_widget == self.ncclear_tool.toolName:
  2955. self.ncclear_tool.on_tool_delete()
  2956. # and only if the tool is Paint Tool
  2957. elif tool_widget == self.paint_tool.toolName:
  2958. self.paint_tool.on_tool_delete()
  2959. else:
  2960. self.on_delete()
  2961. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  2962. # some screens you have to be careful where you hover with your mouse.
  2963. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  2964. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  2965. # Complicated, I know :)
  2966. def on_delete(self):
  2967. """
  2968. Delete the currently selected FlatCAMObjs.
  2969. :return: None
  2970. """
  2971. self.report_usage("on_delete()")
  2972. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  2973. # a geometry object before we update it.
  2974. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  2975. if self.collection.get_active():
  2976. self.log.debug("on_delete()")
  2977. self.report_usage("on_delete")
  2978. while (self.collection.get_active()):
  2979. self.delete_first_selected()
  2980. self.inform.emit("Object(s) deleted ...")
  2981. # make sure that the selection shape is deleted, too
  2982. self.delete_selection_shape()
  2983. else:
  2984. self.inform.emit("Failed. No object(s) selected...")
  2985. else:
  2986. self.inform.emit("Save the work in Editor and try again ...")
  2987. def on_set_origin(self):
  2988. """
  2989. Set the origin to the left mouse click position
  2990. :return: None
  2991. """
  2992. #display the message for the user
  2993. #and ask him to click on the desired position
  2994. self.report_usage("on_set_origin()")
  2995. self.inform.emit('Click to set the origin ...')
  2996. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  2997. def on_jump_to(self):
  2998. """
  2999. Jump to a location by setting the mouse cursor location
  3000. :return:
  3001. """
  3002. self.report_usage("on_jump_to()")
  3003. dia_box = Dialog_box(title="Jump to Coordinates", label="Enter the coordinates in format X,Y:")
  3004. if dia_box.ok is True:
  3005. try:
  3006. location = eval(dia_box.location)
  3007. if not isinstance(location, tuple):
  3008. self.inform.emit("Wrong coordinates. Enter coordinates in format: X,Y")
  3009. return
  3010. except:
  3011. return
  3012. else:
  3013. return
  3014. self.plotcanvas.fit_center(loc=location)
  3015. cursor = QtGui.QCursor()
  3016. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3017. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3018. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3019. self.inform.emit("Done.")
  3020. def on_copy_object(self):
  3021. self.report_usage("on_copy_object()")
  3022. def initialize(obj_init, app):
  3023. obj_init.solid_geometry = obj.solid_geometry
  3024. try:
  3025. if obj.tools:
  3026. obj_init.tools = obj.tools
  3027. except Exception as e:
  3028. log.debug("on_copy_object() --> %s" % str(e))
  3029. def initialize_excellon(obj_init, app):
  3030. obj_init.tools = obj.tools
  3031. # drills are offset, so they need to be deep copied
  3032. obj_init.drills = deepcopy(obj.drills)
  3033. # slots are offset, so they need to be deep copied
  3034. obj_init.slots = deepcopy(obj.slots)
  3035. obj_init.create_geometry()
  3036. for obj in self.collection.get_selected():
  3037. obj_name = obj.options["name"]
  3038. try:
  3039. if isinstance(obj, FlatCAMExcellon):
  3040. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3041. elif isinstance(obj,FlatCAMGerber):
  3042. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3043. elif isinstance(obj,FlatCAMGeometry):
  3044. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3045. except Exception as e:
  3046. return "Operation failed: %s" % str(e)
  3047. def on_copy_object2(self, custom_name):
  3048. def initialize_geometry(obj_init, app):
  3049. obj_init.solid_geometry = obj.solid_geometry
  3050. try:
  3051. if obj.tools:
  3052. obj_init.tools = obj.tools
  3053. except Exception as e:
  3054. log.debug("on_copy_object2() --> %s" % str(e))
  3055. def initialize_gerber(obj_init, app):
  3056. obj_init.solid_geometry = obj.solid_geometry
  3057. obj_init.apertures = deepcopy(obj.apertures)
  3058. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3059. def initialize_excellon(obj_init, app):
  3060. obj_init.tools = obj.tools
  3061. # drills are offset, so they need to be deep copied
  3062. obj_init.drills = deepcopy(obj.drills)
  3063. # slots are offset, so they need to be deep copied
  3064. obj_init.slots = deepcopy(obj.slots)
  3065. obj_init.create_geometry()
  3066. for obj in self.collection.get_selected():
  3067. obj_name = obj.options["name"]
  3068. try:
  3069. if isinstance(obj, FlatCAMExcellon):
  3070. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3071. elif isinstance(obj,FlatCAMGerber):
  3072. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3073. elif isinstance(obj,FlatCAMGeometry):
  3074. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3075. except Exception as e:
  3076. return "Operation failed: %s" % str(e)
  3077. def on_rename_object(self, text):
  3078. self.report_usage("on_rename_object()")
  3079. named_obj = self.collection.get_active()
  3080. for obj in named_obj:
  3081. if obj is list:
  3082. self.on_rename_object(text)
  3083. else:
  3084. try:
  3085. obj.options['name'] = text
  3086. except:
  3087. log.warning("Could not rename the object in the list")
  3088. def on_copy_object_as_geometry(self):
  3089. self.report_usage("on_copy_object_as_geometry()")
  3090. def initialize(obj_init, app):
  3091. obj_init.solid_geometry = obj.solid_geometry
  3092. if obj.tools:
  3093. obj_init.tools = obj.tools
  3094. def initialize_excellon(obj, app):
  3095. objs = self.collection.get_selected()
  3096. FlatCAMGeometry.merge(objs, obj)
  3097. for obj in self.collection.get_selected():
  3098. obj_name = obj.options["name"]
  3099. try:
  3100. if isinstance(obj, FlatCAMExcellon):
  3101. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  3102. else:
  3103. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  3104. except Exception as e:
  3105. return "Operation failed: %s" % str(e)
  3106. def on_set_zero_click(self, event):
  3107. #this function will be available only for mouse left click
  3108. pos =[]
  3109. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3110. if event.button == 1:
  3111. if self.grid_status() == True:
  3112. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3113. else:
  3114. pos = pos_canvas
  3115. x = 0 - pos[0]
  3116. y = 0 - pos[1]
  3117. for obj in self.collection.get_list():
  3118. obj.offset((x,y))
  3119. self.object_changed.emit(obj)
  3120. # obj.plot()
  3121. self.plot_all(zoom=False)
  3122. self.inform.emit('[success] Origin set ...')
  3123. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  3124. def on_selectall(self):
  3125. self.report_usage("on_selectall()")
  3126. # delete the possible selection box around a possible selected object
  3127. self.delete_selection_shape()
  3128. for name in self.collection.get_names():
  3129. self.collection.set_active(name)
  3130. curr_sel_obj = self.collection.get_by_name(name)
  3131. # create the selection box around the selected object
  3132. self.draw_selection_shape(curr_sel_obj)
  3133. def on_preferences(self):
  3134. # add the tab if it was closed
  3135. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, "Preferences")
  3136. # delete the absolute and relative position and messages in the infobar
  3137. self.ui.position_label.setText("")
  3138. self.ui.rel_position_label.setText("")
  3139. # Switch plot_area to preferences page
  3140. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  3141. self.ui.show()
  3142. def on_flipy(self):
  3143. self.report_usage("on_flipy()")
  3144. obj_list = self.collection.get_selected()
  3145. xminlist = []
  3146. yminlist = []
  3147. xmaxlist = []
  3148. ymaxlist = []
  3149. if not obj_list:
  3150. self.inform.emit("[WARNING_NOTCL] No object selected to Flip on Y axis.")
  3151. else:
  3152. try:
  3153. # first get a bounding box to fit all
  3154. for obj in obj_list:
  3155. xmin, ymin, xmax, ymax = obj.bounds()
  3156. xminlist.append(xmin)
  3157. yminlist.append(ymin)
  3158. xmaxlist.append(xmax)
  3159. ymaxlist.append(ymax)
  3160. # get the minimum x,y and maximum x,y for all objects selected
  3161. xminimal = min(xminlist)
  3162. yminimal = min(yminlist)
  3163. xmaximal = max(xmaxlist)
  3164. ymaximal = max(ymaxlist)
  3165. px = 0.5 * (xminimal + xmaximal)
  3166. py = 0.5 * (yminimal + ymaximal)
  3167. # execute mirroring
  3168. for obj in obj_list:
  3169. obj.mirror('X', [px, py])
  3170. obj.plot()
  3171. self.object_changed.emit(obj)
  3172. except Exception as e:
  3173. self.inform.emit("[ERROR_NOTCL] Due of %s, Flip action was not executed." % str(e))
  3174. return
  3175. def on_flipx(self):
  3176. self.report_usage("on_flipx()")
  3177. obj_list = self.collection.get_selected()
  3178. xminlist = []
  3179. yminlist = []
  3180. xmaxlist = []
  3181. ymaxlist = []
  3182. if not obj_list:
  3183. self.inform.emit("[WARNING_NOTCL] No object selected to Flip on X axis.")
  3184. else:
  3185. try:
  3186. # first get a bounding box to fit all
  3187. for obj in obj_list:
  3188. xmin, ymin, xmax, ymax = obj.bounds()
  3189. xminlist.append(xmin)
  3190. yminlist.append(ymin)
  3191. xmaxlist.append(xmax)
  3192. ymaxlist.append(ymax)
  3193. # get the minimum x,y and maximum x,y for all objects selected
  3194. xminimal = min(xminlist)
  3195. yminimal = min(yminlist)
  3196. xmaximal = max(xmaxlist)
  3197. ymaximal = max(ymaxlist)
  3198. px = 0.5 * (xminimal + xmaximal)
  3199. py = 0.5 * (yminimal + ymaximal)
  3200. # execute mirroring
  3201. for obj in obj_list:
  3202. obj.mirror('Y', [px, py])
  3203. obj.plot()
  3204. self.object_changed.emit(obj)
  3205. except Exception as e:
  3206. self.inform.emit("[ERROR_NOTCL] Due of %s, Flip action was not executed." % str(e))
  3207. return
  3208. def on_rotate(self, silent=False, preset=None):
  3209. self.report_usage("on_rotate()")
  3210. obj_list = self.collection.get_selected()
  3211. xminlist = []
  3212. yminlist = []
  3213. xmaxlist = []
  3214. ymaxlist = []
  3215. if not obj_list:
  3216. self.inform.emit("[WARNING_NOTCL] No object selected to Rotate.")
  3217. else:
  3218. if silent is False:
  3219. rotatebox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3220. min=-360, max=360, decimals=3)
  3221. num, ok = rotatebox.get_value()
  3222. else:
  3223. num = preset
  3224. ok = True
  3225. if ok:
  3226. try:
  3227. # first get a bounding box to fit all
  3228. for obj in obj_list:
  3229. xmin, ymin, xmax, ymax = obj.bounds()
  3230. xminlist.append(xmin)
  3231. yminlist.append(ymin)
  3232. xmaxlist.append(xmax)
  3233. ymaxlist.append(ymax)
  3234. # get the minimum x,y and maximum x,y for all objects selected
  3235. xminimal = min(xminlist)
  3236. yminimal = min(yminlist)
  3237. xmaximal = max(xmaxlist)
  3238. ymaximal = max(ymaxlist)
  3239. px = 0.5 * (xminimal + xmaximal)
  3240. py = 0.5 * (yminimal + ymaximal)
  3241. for sel_obj in obj_list:
  3242. sel_obj.rotate(-num, point=(px, py))
  3243. sel_obj.plot()
  3244. self.object_changed.emit(sel_obj)
  3245. except Exception as e:
  3246. self.inform.emit("[ERROR_NOTCL] Due of %s, rotation movement was not executed." % str(e))
  3247. return
  3248. def on_skewx(self):
  3249. self.report_usage("on_skewx()")
  3250. obj_list = self.collection.get_selected()
  3251. xminlist = []
  3252. yminlist = []
  3253. if not obj_list:
  3254. self.inform.emit("[WARNING_NOTCL] No object selected to Skew/Shear on X axis.")
  3255. else:
  3256. skewxbox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3257. min=-360, max=360, decimals=3)
  3258. num, ok = skewxbox.get_value()
  3259. if ok:
  3260. # first get a bounding box to fit all
  3261. for obj in obj_list:
  3262. xmin, ymin, xmax, ymax = obj.bounds()
  3263. xminlist.append(xmin)
  3264. yminlist.append(ymin)
  3265. # get the minimum x,y and maximum x,y for all objects selected
  3266. xminimal = min(xminlist)
  3267. yminimal = min(yminlist)
  3268. for obj in obj_list:
  3269. obj.skew(num, 0, point=(xminimal, yminimal))
  3270. obj.plot()
  3271. self.object_changed.emit(obj)
  3272. def on_skewy(self):
  3273. self.report_usage("on_skewy()")
  3274. obj_list = self.collection.get_selected()
  3275. xminlist = []
  3276. yminlist = []
  3277. if not obj_list:
  3278. self.inform.emit("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis.")
  3279. else:
  3280. skewybox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3281. min=-360, max=360, decimals=3)
  3282. num, ok = skewybox.get_value()
  3283. if ok:
  3284. # first get a bounding box to fit all
  3285. for obj in obj_list:
  3286. xmin, ymin, xmax, ymax = obj.bounds()
  3287. xminlist.append(xmin)
  3288. yminlist.append(ymin)
  3289. # get the minimum x,y and maximum x,y for all objects selected
  3290. xminimal = min(xminlist)
  3291. yminimal = min(yminlist)
  3292. for obj in obj_list:
  3293. obj.skew(0, num, point=(xminimal, yminimal))
  3294. obj.plot()
  3295. self.object_changed.emit(obj)
  3296. def delete_first_selected(self):
  3297. # Keep this for later
  3298. try:
  3299. name = self.collection.get_active().options["name"]
  3300. except AttributeError:
  3301. self.log.debug("Nothing selected for deletion")
  3302. return
  3303. # Remove plot
  3304. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3305. # self.plotcanvas.auto_adjust_axes()
  3306. # Clear form
  3307. self.setup_component_editor()
  3308. # Remove from dictionary
  3309. self.collection.delete_active()
  3310. self.inform.emit("Object deleted: %s" % name)
  3311. def on_plots_updated(self):
  3312. """
  3313. Callback used to report when the plots have changed.
  3314. Adjust axes and zooms to fit.
  3315. :return: None
  3316. """
  3317. # self.plotcanvas.auto_adjust_axes()
  3318. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  3319. self.on_zoom_fit(None)
  3320. # TODO: Rework toolbar 'clear', 'replot' functions
  3321. def on_toolbar_replot(self):
  3322. """
  3323. Callback for toolbar button. Re-plots all objects.
  3324. :return: None
  3325. """
  3326. self.report_usage("on_toolbar_replot")
  3327. self.log.debug("on_toolbar_replot()")
  3328. try:
  3329. self.collection.get_active().read_form()
  3330. except AttributeError:
  3331. self.log.debug("on_toolbar_replot(): AttributeError")
  3332. pass
  3333. self.plot_all()
  3334. def on_row_activated(self, index):
  3335. if index.isValid():
  3336. if index.internalPointer().parent_item != self.collection.root_item:
  3337. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3338. def grid_status(self):
  3339. if self.ui.grid_snap_btn.isChecked():
  3340. return 1
  3341. else:
  3342. return 0
  3343. # def on_key_over_plot(self, event):
  3344. # """
  3345. # Callback for the key pressed event when the canvas is focused. Keyboard
  3346. # shortcuts are handled here. So far, these are the shortcuts:
  3347. #
  3348. # ========== ============================================
  3349. # Key Action
  3350. # ========== ============================================
  3351. # '1' Zoom-fit. Fits the axes limits to the data.
  3352. # '2' Zoom-out.
  3353. # '3' Zoom-in.
  3354. # 'ctrl+m' Toggle on-off the measuring tool.
  3355. # ========== ============================================
  3356. #
  3357. # :param event: Ignored.
  3358. # :return: None
  3359. # """
  3360. # print(type(event.key), event.key)
  3361. # self.key_modifiers = QtWidgets.QApplication.keyboardModifiers()
  3362. #
  3363. # if self.key_modifiers == QtCore.Qt.ControlModifier:
  3364. # if event.key == 'A':
  3365. # self.on_selectall()
  3366. #
  3367. # if event.key == 'C':
  3368. # self.on_copy_object()
  3369. #
  3370. # if event.key == 'E':
  3371. # self.on_fileopenexcellon()
  3372. #
  3373. # if event.key == 'G':
  3374. # self.on_fileopengerber()
  3375. #
  3376. # if event.key == 'N':
  3377. # self.on_file_new_click()
  3378. #
  3379. # if event.key == 'M':
  3380. # self.measurement_tool.run()
  3381. #
  3382. # if event.key == 'O':
  3383. # self.on_file_openproject()
  3384. #
  3385. # if event.key == 'S':
  3386. # self.on_file_saveproject()
  3387. #
  3388. # # Toggle Plot Area
  3389. # if event.key == 'F10':
  3390. # self.on_toggle_plotarea()
  3391. #
  3392. # return
  3393. # elif self.key_modifiers == QtCore.Qt.AltModifier:
  3394. # # place holder for further shortcut key
  3395. #
  3396. # if event.key == '1':
  3397. # self.enable_all_plots()
  3398. #
  3399. # if event.key == '2':
  3400. # self.disable_all_plots()
  3401. #
  3402. # if event.key == '3':
  3403. # self.disable_other_plots()
  3404. #
  3405. # if event.key == 'C':
  3406. # self.calculator_tool.run()
  3407. #
  3408. # if event.key == 'D':
  3409. # self.dblsidedtool.run()
  3410. #
  3411. # if event.key == 'L':
  3412. # self.film_tool.run()
  3413. #
  3414. # if event.key == 'N':
  3415. # self.ncclear_tool.run()
  3416. #
  3417. # if event.key == 'P':
  3418. # self.paint_tool.run()
  3419. #
  3420. # if event.key == 'R':
  3421. # self.transform_tool.run()
  3422. #
  3423. # if event.key == 'U':
  3424. # self.cutout_tool.run()
  3425. #
  3426. # if event.key == 'Z':
  3427. # self.panelize_tool.run()
  3428. #
  3429. # if event.key == 'F10':
  3430. # self.on_fullscreen()
  3431. #
  3432. # return
  3433. # elif self.key_modifiers == QtCore.Qt.ShiftModifier:
  3434. # # place holder for further shortcut key
  3435. #
  3436. # if event.key == 'C':
  3437. # self.on_copy_name()
  3438. #
  3439. # # Toggle axis
  3440. # if event.key == 'G':
  3441. # self.on_toggle_axis()
  3442. #
  3443. # # Open Preferences Window
  3444. # if event.key == 'P':
  3445. # self.on_preferences()
  3446. #
  3447. # # Rotate Object by 90 degree CCW
  3448. # if event.key == 'R':
  3449. # self.on_rotate(silent=True, preset=-90)
  3450. #
  3451. # # Run a Script
  3452. # if event.key == 'S':
  3453. # self.on_filerunscript()
  3454. #
  3455. # # Toggle Workspace
  3456. # if event.key == 'W':
  3457. # self.on_workspace_menu()
  3458. #
  3459. # # Skew on X axis
  3460. # if event.key == 'X':
  3461. # self.on_skewx()
  3462. #
  3463. # # Skew on Y axis
  3464. # if event.key == 'Y':
  3465. # self.on_skewy()
  3466. #
  3467. # else:
  3468. # if event.key == 'F1':
  3469. # webbrowser.open(self.manual_url)
  3470. # return
  3471. #
  3472. # if event.key == 'F2':
  3473. # webbrowser.open(self.video_url)
  3474. # return
  3475. #
  3476. # if event.key == self.defaults['zoom_out_key']: # '-'
  3477. # self.plotcanvas.zoom(1 / self.defaults['zoom_ratio'], self.mouse)
  3478. # return
  3479. #
  3480. # if event.key == self.defaults['zoom_in_key']: # '='
  3481. # self.plotcanvas.zoom(self.defaults['zoom_ratio'], self.mouse)
  3482. # return
  3483. #
  3484. # if event.key == 'Delete':
  3485. # self.on_delete()
  3486. # return
  3487. #
  3488. # if event.key == 'Space':
  3489. # if self.collection.get_active() is not None:
  3490. # self.collection.get_active().ui.plot_cb.toggle()
  3491. # self.delete_selection_shape()
  3492. #
  3493. # if event.key == '1':
  3494. # self.on_select_tab('project')
  3495. #
  3496. # if event.key == '2':
  3497. # self.on_select_tab('selected')
  3498. #
  3499. # if event.key == '3':
  3500. # self.on_select_tab('tool')
  3501. #
  3502. # if event.key == 'E':
  3503. # self.object2editor()
  3504. #
  3505. # if event.key == self.defaults['grid_toggle_key']: # G
  3506. # self.ui.grid_snap_btn.trigger()
  3507. #
  3508. # if event.key == 'J':
  3509. # self.on_jump_to()
  3510. #
  3511. # if event.key == 'L':
  3512. # self.new_excellon_object()
  3513. #
  3514. # if event.key == 'M':
  3515. # self.move_tool.toggle()
  3516. # return
  3517. #
  3518. # if event.key == 'N':
  3519. # self.on_new_geometry()
  3520. #
  3521. # if event.key == 'O':
  3522. # self.on_set_origin()
  3523. #
  3524. # if event.key == 'P':
  3525. # self.properties_tool.run()
  3526. #
  3527. # if event.key == 'Q':
  3528. # self.on_toggle_units_click()
  3529. #
  3530. # if event.key == 'R':
  3531. # self.on_rotate(silent=True, preset=90)
  3532. #
  3533. # if event.key == 'S':
  3534. # self.on_toggle_shell()
  3535. #
  3536. # if event.key == 'V':
  3537. # self.on_zoom_fit(None)
  3538. #
  3539. # if event.key == 'X':
  3540. # self.on_flipx()
  3541. #
  3542. # if event.key == 'Y':
  3543. # self.on_flipy()
  3544. #
  3545. # if event.key == '`':
  3546. # self.on_shortcut_list()
  3547. #
  3548. # def on_key_release_over_plot(self, event):
  3549. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  3550. #
  3551. # if modifiers == QtCore.Qt.ControlModifier:
  3552. # return
  3553. # elif modifiers == QtCore.Qt.AltModifier:
  3554. # # place holder for further shortcut key
  3555. # return
  3556. # elif modifiers == QtCore.Qt.ShiftModifier:
  3557. # # place holder for further shortcut key
  3558. # return
  3559. # else:
  3560. # return
  3561. def on_shortcut_list(self):
  3562. self.report_usage("on_shortcut_list()")
  3563. # add the tab if it was closed
  3564. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  3565. # delete the absolute and relative position and messages in the infobar
  3566. self.ui.position_label.setText("")
  3567. self.ui.rel_position_label.setText("")
  3568. # Switch plot_area to preferences page
  3569. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  3570. self.ui.show()
  3571. def on_select_tab(self, name):
  3572. if name == 'project':
  3573. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3574. elif name == 'selected':
  3575. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3576. elif name == 'tool':
  3577. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  3578. # if the splitter us hidden, display it
  3579. if self.ui.splitter.sizes()[0] == 0:
  3580. self.ui.splitter.setSizes([1, 1])
  3581. def on_copy_name(self):
  3582. self.report_usage("on_copy_name()")
  3583. obj = self.collection.get_active()
  3584. try:
  3585. name = obj.options["name"]
  3586. except AttributeError:
  3587. log.debug("on_copy_name() --> No object selected to copy it's name")
  3588. self.inform.emit("[WARNING_NOTCL]No object selected to copy it's name")
  3589. return
  3590. self.clipboard.setText(name)
  3591. self.inform.emit("Name copied on clipboard ...")
  3592. def on_mouse_click_over_plot(self, event):
  3593. """
  3594. Callback for the mouse click event over the plot. This event is generated
  3595. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3596. For details, see: http://matplotlib.org/users/event_handling.html
  3597. Default actions are:
  3598. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  3599. :param event: Contains information about the event, like which button
  3600. was clicked, the pixel coordinates and the axes coordinates.
  3601. :return: None
  3602. """
  3603. self.pos = []
  3604. # So it can receive key presses
  3605. self.plotcanvas.vispy_canvas.native.setFocus()
  3606. # Set the mouse button for panning
  3607. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  3608. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3609. if self.grid_status() == True:
  3610. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  3611. self.app_cursor.enabled = True
  3612. else:
  3613. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  3614. self.app_cursor.enabled = False
  3615. try:
  3616. # App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  3617. # event.button, event.pos[0], event.pos[1], self.pos[0], self.pos[1]))
  3618. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3619. if event.button == 1:
  3620. # Reset here the relative coordinates so there is a new reference on the click position
  3621. if self.rel_point1 is None:
  3622. self.rel_point1 = self.pos
  3623. else:
  3624. self.rel_point2 = copy(self.rel_point1)
  3625. self.rel_point1 = self.pos
  3626. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3627. if modifiers == QtCore.Qt.ShiftModifier:
  3628. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3629. return
  3630. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  3631. # and if it's not selected then it will be selected
  3632. if modifiers == QtCore.Qt.ControlModifier:
  3633. # If there is no active command (self.command_active is None) then we check if we clicked on
  3634. # a object by checking the bounding limits against mouse click position
  3635. if self.command_active is None:
  3636. self.select_objects(key='CTRL')
  3637. else:
  3638. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  3639. # checking the bounding limits against mouse click position
  3640. if self.command_active is None:
  3641. self.select_objects()
  3642. self.on_mouse_move_over_plot(event, origin_click=True)
  3643. except Exception as e:
  3644. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  3645. def on_double_click_over_plot(self, event):
  3646. # make double click work only for the LMB
  3647. if event.button == 1:
  3648. if self.collection.get_selected():
  3649. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3650. # delete the selection shape(S) as it may be in the way
  3651. self.delete_selection_shape()
  3652. def on_mouse_move_over_plot(self, event, origin_click=None):
  3653. """
  3654. Callback for the mouse motion event over the plot. This event is generated
  3655. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3656. For details, see: http://matplotlib.org/users/event_handling.html
  3657. :param event: Contains information about the event.
  3658. :param origin_click
  3659. :return: None
  3660. """
  3661. # So it can receive key presses
  3662. self.plotcanvas.vispy_canvas.native.setFocus()
  3663. self.pos_jump = event.pos
  3664. if origin_click is True:
  3665. pass
  3666. else:
  3667. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3668. if event.button == 2:
  3669. self.panning_action = True
  3670. return
  3671. else:
  3672. self.panning_action = False
  3673. if self.rel_point1 is not None:
  3674. try: # May fail in case mouse not within axes
  3675. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3676. if self.grid_status():
  3677. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3678. self.app_cursor.enabled = True
  3679. # Update cursor
  3680. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3681. else:
  3682. pos = (pos_canvas[0], pos_canvas[1])
  3683. self.app_cursor.enabled = False
  3684. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3685. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3686. dx = pos[0] - self.rel_point1[0]
  3687. dy = pos[1] - self.rel_point1[1]
  3688. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3689. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3690. self.mouse = [pos[0], pos[1]]
  3691. # if the mouse is moved and the LMB is clicked then the action is a selection
  3692. if event.is_dragging == 1 and event.button == 1:
  3693. self.delete_selection_shape()
  3694. if dx < 0:
  3695. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3696. face_color=self.defaults['global_alt_sel_fill'])
  3697. self.selection_type = False
  3698. else:
  3699. self.draw_moving_selection_shape(self.pos, pos)
  3700. self.selection_type = True
  3701. # delete the status message on mouse move
  3702. # self.inform.emit("")
  3703. except:
  3704. self.ui.position_label.setText("")
  3705. self.ui.rel_position_label.setText("")
  3706. self.mouse = None
  3707. def on_mouse_click_release_over_plot(self, event):
  3708. """
  3709. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3710. and has been registered in ''self.__init__()''.
  3711. :param event: contains information about the event.
  3712. :return:
  3713. """
  3714. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3715. if self.grid_status():
  3716. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3717. else:
  3718. pos = (pos_canvas[0], pos_canvas[1])
  3719. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3720. # canvas menu
  3721. try:
  3722. if event.button == 2: # right click
  3723. if self.panning_action is True:
  3724. self.panning_action = False
  3725. else:
  3726. self.cursor = QtGui.QCursor()
  3727. self.ui.popMenu.popup(self.cursor.pos())
  3728. except Exception as e:
  3729. log.warning("Error: %s" % str(e))
  3730. return
  3731. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3732. # selection and then select a type of selection ("enclosing" or "touching")
  3733. try:
  3734. if event.button == 1: # left click
  3735. if self.selection_type is not None:
  3736. self.selection_area_handler(self.pos, pos, self.selection_type)
  3737. self.selection_type = None
  3738. except Exception as e:
  3739. log.warning("Error: %s" % str(e))
  3740. return
  3741. def selection_area_handler(self, start_pos, end_pos, sel_type):
  3742. """
  3743. :param start_pos: mouse position when the selection LMB click was done
  3744. :param end_pos: mouse position when the left mouse button is released
  3745. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3746. :return:
  3747. """
  3748. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3749. self.delete_selection_shape()
  3750. for obj in self.collection.get_list():
  3751. try:
  3752. # select the object(s) only if it is enabled (plotted)
  3753. if obj.options['plot']:
  3754. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']), (obj.options['xmax'], obj.options['ymin']),
  3755. (obj.options['xmax'], obj.options['ymax']), (obj.options['xmin'], obj.options['ymax'])])
  3756. if sel_type is True:
  3757. if poly_obj.within(poly_selection):
  3758. # create the selection box around the selected object
  3759. self.draw_selection_shape(obj)
  3760. self.collection.set_active(obj.options['name'])
  3761. else:
  3762. if poly_selection.intersects(poly_obj):
  3763. # create the selection box around the selected object
  3764. self.draw_selection_shape(obj)
  3765. self.collection.set_active(obj.options['name'])
  3766. except:
  3767. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  3768. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  3769. # In this case poly_obj creation (see above) will fail
  3770. pass
  3771. def select_objects(self, key=None):
  3772. # list where we store the overlapped objects under our mouse left click position
  3773. objects_under_the_click_list = []
  3774. # Populate the list with the overlapped objects on the click position
  3775. curr_x, curr_y = self.pos
  3776. for obj in self.all_objects_list:
  3777. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  3778. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  3779. if obj.options['name'] not in objects_under_the_click_list:
  3780. if obj.options['plot']:
  3781. # add objects to the objects_under_the_click list only if the object is plotted
  3782. # (active and not disabled)
  3783. objects_under_the_click_list.append(obj.options['name'])
  3784. try:
  3785. # If there is no element in the overlapped objects list then make everyone inactive
  3786. # because we selected "nothing"
  3787. if not objects_under_the_click_list:
  3788. self.collection.set_all_inactive()
  3789. # delete the possible selection box around a possible selected object
  3790. self.delete_selection_shape()
  3791. # and as a convenience move the focus to the Project tab because Selected tab is now empty
  3792. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3793. # delete any text in the status bar, implicitly the last object name that was selected
  3794. self.inform.emit("")
  3795. else:
  3796. # case when there is only an object under the click and we toggle it
  3797. if len(objects_under_the_click_list) == 1:
  3798. if self.collection.get_active() is None :
  3799. self.collection.set_active(objects_under_the_click_list[0])
  3800. # create the selection box around the selected object
  3801. curr_sel_obj = self.collection.get_active()
  3802. self.draw_selection_shape(curr_sel_obj)
  3803. # self.inform.emit('[selected] %s: %s selected' %
  3804. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3805. if curr_sel_obj.kind == 'gerber':
  3806. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3807. ('green', str(curr_sel_obj.options['name'])))
  3808. elif curr_sel_obj.kind == 'excellon':
  3809. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3810. ('brown', str(curr_sel_obj.options['name'])))
  3811. elif curr_sel_obj.kind == 'cncjob':
  3812. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3813. ('blue', str(curr_sel_obj.options['name'])))
  3814. elif curr_sel_obj.kind == 'geometry':
  3815. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3816. ('red', str(curr_sel_obj.options['name'])))
  3817. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  3818. self.collection.set_all_inactive()
  3819. self.delete_selection_shape()
  3820. self.collection.set_active(objects_under_the_click_list[0])
  3821. # create the selection box around the selected object
  3822. curr_sel_obj = self.collection.get_active()
  3823. self.draw_selection_shape(curr_sel_obj)
  3824. # self.inform.emit('[selected] %s: %s selected' %
  3825. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3826. if curr_sel_obj.kind == 'gerber':
  3827. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3828. ('green', str(curr_sel_obj.options['name'])))
  3829. elif curr_sel_obj.kind == 'excellon':
  3830. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3831. ('brown', str(curr_sel_obj.options['name'])))
  3832. elif curr_sel_obj.kind == 'cncjob':
  3833. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3834. ('blue', str(curr_sel_obj.options['name'])))
  3835. elif curr_sel_obj.kind == 'geometry':
  3836. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3837. ('red', str(curr_sel_obj.options['name'])))
  3838. else:
  3839. self.collection.set_all_inactive()
  3840. self.delete_selection_shape()
  3841. self.inform.emit("")
  3842. else:
  3843. # If there is no selected object
  3844. # make active the first element of the overlapped objects list
  3845. if self.collection.get_active() is None:
  3846. self.collection.set_active(objects_under_the_click_list[0])
  3847. name_sel_obj = self.collection.get_active().options['name']
  3848. # In case that there is a selected object but it is not in the overlapped object list
  3849. # make that object inactive and activate the first element in the overlapped object list
  3850. if name_sel_obj not in objects_under_the_click_list:
  3851. self.collection.set_inactive(name_sel_obj)
  3852. name_sel_obj = objects_under_the_click_list[0]
  3853. self.collection.set_active(name_sel_obj)
  3854. else:
  3855. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  3856. self.collection.set_all_inactive()
  3857. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  3858. len(objects_under_the_click_list)])
  3859. curr_sel_obj = self.collection.get_active()
  3860. # delete the possible selection box around a possible selected object
  3861. self.delete_selection_shape()
  3862. # create the selection box around the selected object
  3863. self.draw_selection_shape(curr_sel_obj)
  3864. # self.inform.emit('[selected] %s: %s selected' %
  3865. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3866. if curr_sel_obj.kind == 'gerber':
  3867. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3868. ('green', str(curr_sel_obj.options['name'])))
  3869. elif curr_sel_obj.kind == 'excellon':
  3870. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3871. ('brown', str(curr_sel_obj.options['name'])))
  3872. elif curr_sel_obj.kind == 'cncjob':
  3873. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3874. ('blue', str(curr_sel_obj.options['name'])))
  3875. elif curr_sel_obj.kind == 'geometry':
  3876. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3877. ('red', str(curr_sel_obj.options['name'])))
  3878. # for obj in self.collection.get_list():
  3879. # obj.plot()
  3880. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  3881. # TODO: on selected objects change the object colors and do not draw the selection box
  3882. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  3883. except Exception as e:
  3884. log.error("[ERROR] Something went bad. %s" % str(e))
  3885. return
  3886. def delete_selection_shape(self):
  3887. self.move_tool.sel_shapes.clear()
  3888. self.move_tool.sel_shapes.redraw()
  3889. def draw_selection_shape(self, sel_obj):
  3890. """
  3891. :param sel_obj: the object for which the selection shape must be drawn
  3892. :return:
  3893. """
  3894. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  3895. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  3896. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  3897. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  3898. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3899. #blue_t = Color('blue')
  3900. blue_t = Color(self.defaults['global_sel_fill'])
  3901. blue_t.alpha = 0.3
  3902. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=self.defaults['global_sel_line'],
  3903. face_color=blue_t, update=True, layer=0, tolerance=None))
  3904. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  3905. """
  3906. :param old_coords: old coordinates
  3907. :param coords: new coordinates
  3908. :return:
  3909. """
  3910. if 'color' in kwargs:
  3911. color = kwargs['color']
  3912. else:
  3913. color = self.defaults['global_sel_line']
  3914. if 'face_color' in kwargs:
  3915. face_color = kwargs['face_color']
  3916. else:
  3917. face_color = self.defaults['global_sel_fill']
  3918. x0, y0 = old_coords
  3919. x1, y1 = coords
  3920. pt1 = (x0, y0)
  3921. pt2 = (x1, y0)
  3922. pt3 = (x1, y1)
  3923. pt4 = (x0, y1)
  3924. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3925. color_t = Color(face_color)
  3926. color_t.alpha = 0.3
  3927. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  3928. layer=0, tolerance=None)
  3929. def on_file_new_click(self):
  3930. if self.collection.get_list():
  3931. msgbox = QtWidgets.QMessageBox()
  3932. # msgbox.setText("<B>Save changes ...</B>")
  3933. msgbox.setText("There are files/objects opened in FlatCAM.\n"
  3934. "Creating a New project will delete them.\n"
  3935. "Do you want to Save the project?")
  3936. msgbox.setWindowTitle("Save changes")
  3937. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3938. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  3939. QtWidgets.QMessageBox.No)
  3940. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3941. response = msgbox.exec_()
  3942. if response == QtWidgets.QMessageBox.Yes:
  3943. self.on_file_saveprojectas()
  3944. elif response == QtWidgets.QMessageBox.Cancel:
  3945. return
  3946. self.on_file_new()
  3947. else:
  3948. self.on_file_new()
  3949. self.inform.emit("[success] New Project created...")
  3950. def on_file_new(self):
  3951. """
  3952. Callback for menu item File->New. Returns the application to its
  3953. startup state. This method is thread-safe.
  3954. :return: None
  3955. """
  3956. self.report_usage("on_file_new")
  3957. # Remove everything from memory
  3958. App.log.debug("on_file_new()")
  3959. # Clear pool
  3960. self.clear_pool()
  3961. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  3962. self.init_tcl()
  3963. self.delete_selection_shape()
  3964. self.collection.delete_all()
  3965. self.setup_component_editor()
  3966. # Clear project filename
  3967. self.project_filename = None
  3968. # Load the application defaults
  3969. self.load_defaults(filename='current_defaults')
  3970. # Re-fresh project options
  3971. self.on_options_app2project()
  3972. # Init Tools
  3973. self.init_tools()
  3974. # take the focus of the Notebook on Project Tab.
  3975. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3976. def obj_properties(self):
  3977. self.report_usage("obj_properties()")
  3978. self.properties_tool.run()
  3979. def obj_move(self):
  3980. self.report_usage("obj_move()")
  3981. self.move_tool.run()
  3982. def on_fileopengerber(self):
  3983. """
  3984. File menu callback for opening a Gerber.
  3985. :return: None
  3986. """
  3987. self.report_usage("on_fileopengerber")
  3988. App.log.debug("on_fileopengerber()")
  3989. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3990. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3991. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3992. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3993. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3994. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3995. "Allegro Files (*.art);;" \
  3996. "Mentor Files (*.pho *.gdo);;" \
  3997. "All Files (*.*)"
  3998. try:
  3999. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber",
  4000. directory=self.get_last_folder(), filter=_filter_)
  4001. except TypeError:
  4002. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber", filter=_filter_)
  4003. filenames = [str(filename) for filename in filenames]
  4004. if len(filenames) == 0:
  4005. self.inform.emit("[WARNING_NOTCL]Open Gerber cancelled.")
  4006. else:
  4007. for filename in filenames:
  4008. if filename != '':
  4009. self.worker_task.emit({'fcn': self.open_gerber,
  4010. 'params': [filename]})
  4011. def on_fileopengerber_follow(self):
  4012. """
  4013. File menu callback for opening a Gerber.
  4014. :return: None
  4015. """
  4016. self.report_usage("on_fileopengerber_follow")
  4017. App.log.debug("on_fileopengerber_follow()")
  4018. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  4019. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  4020. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  4021. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  4022. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  4023. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  4024. "Allegro Files (*.art);;" \
  4025. "Mentor Files (*.pho *.gdo);;" \
  4026. "All Files (*.*)"
  4027. try:
  4028. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow",
  4029. directory=self.get_last_folder(), filter=_filter_)
  4030. except TypeError:
  4031. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow", filter=_filter_)
  4032. # The Qt methods above will return a QString which can cause problems later.
  4033. # So far json.dump() will fail to serialize it.
  4034. # TODO: Improve the serialization methods and remove this fix.
  4035. filename = str(filename)
  4036. follow = True
  4037. if filename == "":
  4038. self.inform.emit("[WARNING_NOTCL]Open Gerber-Follow cancelled.")
  4039. else:
  4040. self.worker_task.emit({'fcn': self.open_gerber,
  4041. 'params': [filename, follow]})
  4042. def on_fileopenexcellon(self):
  4043. """
  4044. File menu callback for opening an Excellon file.
  4045. :return: None
  4046. """
  4047. self.report_usage("on_fileopenexcellon")
  4048. App.log.debug("on_fileopenexcellon()")
  4049. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  4050. "All Files (*.*)"
  4051. try:
  4052. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon",
  4053. directory=self.get_last_folder(), filter=_filter_)
  4054. except TypeError:
  4055. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon", filter=_filter_)
  4056. filenames = [str(filename) for filename in filenames]
  4057. if len(filenames) == 0:
  4058. self.inform.emit("[WARNING_NOTCL]Open Excellon cancelled.")
  4059. else:
  4060. for filename in filenames:
  4061. if filename != '':
  4062. self.worker_task.emit({'fcn': self.open_excellon,
  4063. 'params': [filename]})
  4064. def on_fileopengcode(self):
  4065. """
  4066. File menu call back for opening gcode.
  4067. :return: None
  4068. """
  4069. self.report_usage("on_fileopengcode")
  4070. App.log.debug("on_fileopengcode()")
  4071. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  4072. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  4073. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  4074. "All Files (*.*)"
  4075. try:
  4076. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code",
  4077. directory=self.get_last_folder(), filter=_filter_)
  4078. except TypeError:
  4079. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code", filter=_filter_)
  4080. filenames = [str(filename) for filename in filenames]
  4081. if len(filenames) == 0:
  4082. self.inform.emit("[WARNING_NOTCL]Open G-Code cancelled.")
  4083. else:
  4084. for filename in filenames:
  4085. if filename != '':
  4086. self.worker_task.emit({'fcn': self.open_gcode,
  4087. 'params': [filename]})
  4088. def on_file_openproject(self):
  4089. """
  4090. File menu callback for opening a project.
  4091. :return: None
  4092. """
  4093. self.report_usage("on_file_openproject")
  4094. App.log.debug("on_file_openproject()")
  4095. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  4096. try:
  4097. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project",
  4098. directory=self.get_last_folder(), filter=_filter_)
  4099. except TypeError:
  4100. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project", filter = _filter_)
  4101. # The Qt methods above will return a QString which can cause problems later.
  4102. # So far json.dump() will fail to serialize it.
  4103. # TODO: Improve the serialization methods and remove this fix.
  4104. filename = str(filename)
  4105. if filename == "":
  4106. self.inform.emit("[WARNING_NOTCL]Open Project cancelled.")
  4107. else:
  4108. # self.worker_task.emit({'fcn': self.open_project,
  4109. # 'params': [filename]})
  4110. # The above was failing because open_project() is not
  4111. # thread safe. The new_project()
  4112. self.open_project(filename)
  4113. def on_file_exportsvg(self):
  4114. """
  4115. Callback for menu item File->Export SVG.
  4116. :return: None
  4117. """
  4118. self.report_usage("on_file_exportsvg")
  4119. App.log.debug("on_file_exportsvg()")
  4120. obj = self.collection.get_active()
  4121. if obj is None:
  4122. self.inform.emit("WARNING: No object selected.")
  4123. msg = "Please Select a Geometry object to export"
  4124. msgbox = QtWidgets.QMessageBox()
  4125. msgbox.setInformativeText(msg)
  4126. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4127. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4128. msgbox.exec_()
  4129. return
  4130. # Check for more compatible types and add as required
  4131. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  4132. and not isinstance(obj, FlatCAMExcellon)):
  4133. msg = "[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used."
  4134. msgbox = QtWidgets.QMessageBox()
  4135. msgbox.setInformativeText(msg)
  4136. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4137. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4138. msgbox.exec_()
  4139. return
  4140. name = self.collection.get_active().options["name"]
  4141. filter = "SVG File (*.svg);;All Files (*.*)"
  4142. try:
  4143. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4144. caption="Export SVG",
  4145. directory=self.get_last_save_folder() + '/' + str(name),
  4146. filter=filter)
  4147. except TypeError:
  4148. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG", filter=filter)
  4149. filename = str(filename)
  4150. if filename == "":
  4151. self.inform.emit("[WARNING_NOTCL]Export SVG cancelled.")
  4152. return
  4153. else:
  4154. self.export_svg(name, filename)
  4155. self.file_saved.emit("SVG", filename)
  4156. def on_file_exportpng(self):
  4157. self.report_usage("on_file_exportpng")
  4158. App.log.debug("on_file_exportpng()")
  4159. image = _screenshot()
  4160. data = np.asarray(image)
  4161. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  4162. self.inform.emit('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4')
  4163. return
  4164. filter_ = "PNG File (*.png);;All Files (*.*)"
  4165. try:
  4166. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4167. caption="Export PNG Image",
  4168. directory=self.get_last_save_folder() + '/png_' + str(self.date).replace('-', ''),
  4169. filter=filter_)
  4170. except TypeError:
  4171. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image", filter=filter_)
  4172. filename = str(filename)
  4173. if filename == "":
  4174. self.inform.emit("Export PNG cancelled.")
  4175. return
  4176. else:
  4177. write_png(filename, data)
  4178. self.file_saved.emit("png", filename)
  4179. def on_file_exportexcellon(self, altium_format=None):
  4180. """
  4181. Callback for menu item File->Export SVG.
  4182. :return: None
  4183. """
  4184. self.report_usage("on_file_exportexcellon")
  4185. App.log.debug("on_file_exportexcellon()")
  4186. obj = self.collection.get_active()
  4187. if obj is None:
  4188. self.inform.emit("[WARNING_NOTCL] No object selected.")
  4189. msg = "Please Select an Excellon object to export"
  4190. msgbox = QtWidgets.QMessageBox()
  4191. msgbox.setInformativeText(msg)
  4192. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4193. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4194. msgbox.exec_()
  4195. return
  4196. # Check for more compatible types and add as required
  4197. if not isinstance(obj, FlatCAMExcellon):
  4198. msg = "[WARNING_NOTCL] Only Excellon objects can be used."
  4199. msgbox = QtWidgets.QMessageBox()
  4200. msgbox.setInformativeText(msg)
  4201. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4202. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4203. msgbox.exec_()
  4204. return
  4205. name = self.collection.get_active().options["name"]
  4206. filter = "Excellon File (*.drl);;Excellon File (*.txt);;All Files (*.*)"
  4207. try:
  4208. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4209. caption="Export Excellon",
  4210. directory=self.get_last_save_folder() + '/' + name,
  4211. filter=filter)
  4212. except TypeError:
  4213. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon", filter=filter)
  4214. filename = str(filename)
  4215. if filename == "":
  4216. self.inform.emit("[WARNING_NOTCL]Export Excellon cancelled.")
  4217. return
  4218. else:
  4219. if altium_format is None:
  4220. self.export_excellon(name, filename)
  4221. self.file_saved.emit("Excellon", filename)
  4222. else:
  4223. self.export_excellon(name, filename, altium_format=True)
  4224. self.file_saved.emit("Excellon", filename)
  4225. def on_file_exportdxf(self):
  4226. """
  4227. Callback for menu item File->Export DXF.
  4228. :return: None
  4229. """
  4230. self.report_usage("on_file_exportdxf")
  4231. App.log.debug("on_file_exportdxf()")
  4232. obj = self.collection.get_active()
  4233. if obj is None:
  4234. self.inform.emit("W[WARNING_NOTCL] No object selected.")
  4235. msg = "Please Select a Geometry object to export"
  4236. msgbox = QtWidgets.QMessageBox()
  4237. msgbox.setInformativeText(msg)
  4238. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4239. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4240. msgbox.exec_()
  4241. return
  4242. # Check for more compatible types and add as required
  4243. if not isinstance(obj, FlatCAMGeometry):
  4244. msg = "[ERROR_NOTCL] Only Geometry objects can be used."
  4245. msgbox = QtWidgets.QMessageBox()
  4246. msgbox.setInformativeText(msg)
  4247. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4248. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4249. msgbox.exec_()
  4250. return
  4251. name = self.collection.get_active().options["name"]
  4252. filter = "DXF File (*.DXF);;All Files (*.*)"
  4253. try:
  4254. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4255. caption="Export DXF",
  4256. directory=self.get_last_save_folder() + '/' + name,
  4257. filter=filter)
  4258. except TypeError:
  4259. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF", filter=filter)
  4260. filename = str(filename)
  4261. if filename == "":
  4262. self.inform.emit("[WARNING_NOTCL]Export DXF cancelled.")
  4263. return
  4264. else:
  4265. self.export_dxf(name, filename)
  4266. self.file_saved.emit("DXF", filename)
  4267. def on_file_importsvg(self, type_of_obj):
  4268. """
  4269. Callback for menu item File->Import SVG.
  4270. :param type_of_obj: to import the SVG as Geometry or as Gerber
  4271. :type type_of_obj: str
  4272. :return: None
  4273. """
  4274. self.report_usage("on_file_importsvg")
  4275. App.log.debug("on_file_importsvg()")
  4276. filter = "SVG File (*.svg);;All Files (*.*)"
  4277. try:
  4278. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG",
  4279. directory=self.get_last_folder(), filter=filter)
  4280. except TypeError:
  4281. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG", filter=filter)
  4282. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4283. type_of_obj = "geometry"
  4284. filenames = [str(filename) for filename in filenames]
  4285. if len(filenames) == 0:
  4286. self.inform.emit("[WARNING_NOTCL]Open SVG cancelled.")
  4287. else:
  4288. for filename in filenames:
  4289. if filename != '':
  4290. self.worker_task.emit({'fcn': self.import_svg,
  4291. 'params': [filename, type_of_obj]})
  4292. def on_file_importdxf(self, type_of_obj):
  4293. """
  4294. Callback for menu item File->Import DXF.
  4295. :param type_of_obj: to import the DXF as Geometry or as Gerber
  4296. :type type_of_obj: str
  4297. :return: None
  4298. """
  4299. self.report_usage("on_file_importdxf")
  4300. App.log.debug("on_file_importdxf()")
  4301. filter = "DXF File (*.DXF);;All Files (*.*)"
  4302. try:
  4303. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF",
  4304. directory=self.get_last_folder(), filter=filter)
  4305. except TypeError:
  4306. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF", filter=filter)
  4307. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4308. type_of_obj = "geometry"
  4309. filenames = [str(filename) for filename in filenames]
  4310. if len(filenames) == 0:
  4311. self.inform.emit("[WARNING_NOTCL]Open DXF cancelled.")
  4312. else:
  4313. for filename in filenames:
  4314. if filename != '':
  4315. self.worker_task.emit({'fcn': self.import_dxf,
  4316. 'params': [filename, type_of_obj]})
  4317. def on_filerunscript(self):
  4318. """
  4319. File menu callback for loading and running a TCL script.
  4320. :return: None
  4321. """
  4322. self.report_usage("on_filerunscript")
  4323. App.log.debug("on_file_runscript()")
  4324. _filter_ = "TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  4325. try:
  4326. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script",
  4327. directory=self.get_last_folder(), filter=_filter_)
  4328. except TypeError:
  4329. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script", filter=_filter_)
  4330. # The Qt methods above will return a QString which can cause problems later.
  4331. # So far json.dump() will fail to serialize it.
  4332. # TODO: Improve the serialization methods and remove this fix.
  4333. filename = str(filename)
  4334. if filename == "":
  4335. self.inform.emit("[WARNING_NOTCL]Open TCL script cancelled.")
  4336. else:
  4337. try:
  4338. with open(filename, "r") as tcl_script:
  4339. cmd_line_shellfile_content = tcl_script.read()
  4340. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  4341. except Exception as ext:
  4342. print("ERROR: ", ext)
  4343. sys.exit(2)
  4344. def on_file_saveproject(self):
  4345. """
  4346. Callback for menu item File->Save Project. Saves the project to
  4347. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  4348. if set to None. The project is saved by calling ``self.save_project()``.
  4349. :return: None
  4350. """
  4351. self.report_usage("on_file_saveproject")
  4352. if self.project_filename is None:
  4353. self.on_file_saveprojectas()
  4354. else:
  4355. self.worker_task.emit({'fcn': self.save_project,
  4356. 'params': [self.project_filename]})
  4357. # self.save_project(self.project_filename)
  4358. self.file_opened.emit("project", self.project_filename)
  4359. self.file_saved.emit("project", self.project_filename)
  4360. def on_file_saveprojectas(self, make_copy=False, thread=True):
  4361. """
  4362. Callback for menu item File->Save Project As... Opens a file
  4363. chooser and saves the project to the given file via
  4364. ``self.save_project()``.
  4365. :return: None
  4366. """
  4367. self.report_usage("on_file_saveprojectas")
  4368. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  4369. try:
  4370. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4371. caption="Save Project As ...",
  4372. directory=self.get_last_save_folder() + '/Project_' + self.date.replace('-', ''),
  4373. filter=filter_)
  4374. except TypeError:
  4375. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...", filter=filter_)
  4376. filename = str(filename)
  4377. if filename == '':
  4378. self.inform.emit("[WARNING_NOTCL]Save Project cancelled.")
  4379. return
  4380. try:
  4381. f = open(filename, 'r')
  4382. f.close()
  4383. exists = True
  4384. except IOError:
  4385. exists = False
  4386. msg = "File exists. Overwrite?"
  4387. if exists:
  4388. msgbox = QtWidgets.QMessageBox()
  4389. msgbox.setInformativeText(msg)
  4390. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel |QtWidgets.QMessageBox.Ok)
  4391. msgbox.setDefaultButton(QtWidgets.QMessageBox.Cancel)
  4392. result = msgbox.exec_()
  4393. if result ==QtWidgets.QMessageBox.Cancel:
  4394. return
  4395. if thread is True:
  4396. self.worker_task.emit({'fcn': self.save_project,
  4397. 'params': [filename]})
  4398. else:
  4399. self.save_project(filename)
  4400. # self.save_project(filename)
  4401. self.file_opened.emit("project", filename)
  4402. self.file_saved.emit("project", filename)
  4403. if not make_copy:
  4404. self.project_filename = filename
  4405. def export_svg(self, obj_name, filename, scale_factor=0.00):
  4406. """
  4407. Exports a Geometry Object to an SVG file.
  4408. :param filename: Path to the SVG file to save to.
  4409. :return:
  4410. """
  4411. self.report_usage("export_svg()")
  4412. if filename is None:
  4413. filename = self.defaults["global_last_save_folder"]
  4414. self.log.debug("export_svg()")
  4415. try:
  4416. obj = self.collection.get_by_name(str(obj_name))
  4417. except:
  4418. # TODO: The return behavior has not been established... should raise exception?
  4419. return "Could not retrieve object: %s" % obj_name
  4420. with self.proc_container.new("Exporting SVG") as proc:
  4421. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4422. # Determine bounding area for svg export
  4423. bounds = obj.bounds()
  4424. size = obj.size()
  4425. # Convert everything to strings for use in the xml doc
  4426. svgwidth = str(size[0])
  4427. svgheight = str(size[1])
  4428. minx = str(bounds[0])
  4429. miny = str(bounds[1] - size[1])
  4430. uom = obj.units.lower()
  4431. # Add a SVG Header and footer to the svg output from shapely
  4432. # The transform flips the Y Axis so that everything renders
  4433. # properly within svg apps such as inkscape
  4434. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4435. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4436. svg_header += 'width="' + svgwidth + uom + '" '
  4437. svg_header += 'height="' + svgheight + uom + '" '
  4438. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  4439. svg_header += '<g transform="scale(1,-1)">'
  4440. svg_footer = '</g> </svg>'
  4441. svg_elem = svg_header + exported_svg + svg_footer
  4442. # Parse the xml through a xml parser just to add line feeds
  4443. # and to make it look more pretty for the output
  4444. svgcode = parse_xml_string(svg_elem)
  4445. with open(filename, 'w') as fp:
  4446. fp.write(svgcode.toprettyxml())
  4447. self.file_saved.emit("SVG", filename)
  4448. self.inform.emit("[success] SVG file exported to " + filename)
  4449. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  4450. """
  4451. Exports a Geometry Object to an SVG file in negative.
  4452. :param filename: Path to the SVG file to save to.
  4453. :param: use_thread: If True use threads
  4454. :type: Bool
  4455. :return:
  4456. """
  4457. self.report_usage("export_negative()")
  4458. if filename is None:
  4459. filename = self.defaults["global_last_save_folder"]
  4460. self.log.debug("export_svg() negative")
  4461. try:
  4462. obj = self.collection.get_by_name(str(obj_name))
  4463. except:
  4464. # TODO: The return behavior has not been established... should raise exception?
  4465. return "Could not retrieve object: %s" % obj_name
  4466. try:
  4467. box = self.collection.get_by_name(str(box_name))
  4468. except:
  4469. # TODO: The return behavior has not been established... should raise exception?
  4470. return "Could not retrieve object: %s" % box_name
  4471. if box is None:
  4472. self.inform.emit("[WARNING_NOTCL]No object Box. Using instead %s" % obj)
  4473. box = obj
  4474. def make_negative_film():
  4475. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4476. self.progress.emit(40)
  4477. # Determine bounding area for svg export
  4478. bounds = box.bounds()
  4479. size = box.size()
  4480. uom = obj.units.lower()
  4481. # Convert everything to strings for use in the xml doc
  4482. svgwidth = str(size[0] + (2 * boundary))
  4483. svgheight = str(size[1] + (2 * boundary))
  4484. minx = str(bounds[0] - boundary)
  4485. miny = str(bounds[1] + boundary + size[1])
  4486. miny_rect = str(bounds[1] - boundary)
  4487. # Add a SVG Header and footer to the svg output from shapely
  4488. # The transform flips the Y Axis so that everything renders
  4489. # properly within svg apps such as inkscape
  4490. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4491. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4492. svg_header += 'width="' + svgwidth + uom + '" '
  4493. svg_header += 'height="' + svgheight + uom + '" '
  4494. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4495. svg_header += '>'
  4496. svg_header += '<g transform="scale(1,-1)">'
  4497. svg_footer = '</g> </svg>'
  4498. self.progress.emit(60)
  4499. # Change the attributes of the exported SVG
  4500. # We don't need stroke-width - wrong, we do when we have lines with certain width
  4501. # We set opacity to maximum
  4502. # We set the color to WHITE
  4503. root = ET.fromstring(exported_svg)
  4504. for child in root:
  4505. child.set('fill', '#FFFFFF')
  4506. child.set('opacity', '1.0')
  4507. child.set('stroke', '#FFFFFF')
  4508. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  4509. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  4510. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  4511. first_svg_elem_tag = 'rect'
  4512. first_svg_elem_attribs = {
  4513. 'x': minx,
  4514. 'y': miny_rect,
  4515. 'width': svgwidth,
  4516. 'height': svgheight,
  4517. 'id': 'neg_rect',
  4518. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  4519. }
  4520. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  4521. exported_svg = ET.tostring(root)
  4522. svg_elem = svg_header + str(exported_svg) + svg_footer
  4523. self.progress.emit(80)
  4524. # Parse the xml through a xml parser just to add line feeds
  4525. # and to make it look more pretty for the output
  4526. doc = parse_xml_string(svg_elem)
  4527. with open(filename, 'w') as fp:
  4528. fp.write(doc.toprettyxml())
  4529. self.progress.emit(100)
  4530. self.file_saved.emit("SVG", filename)
  4531. self.inform.emit("[success] SVG file exported to " + filename)
  4532. if use_thread is True:
  4533. proc = self.proc_container.new("Generating Film ... Please wait.")
  4534. def job_thread_film(app_obj):
  4535. try:
  4536. make_negative_film()
  4537. except Exception as e:
  4538. proc.done()
  4539. return
  4540. proc.done()
  4541. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4542. else:
  4543. make_negative_film()
  4544. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  4545. """
  4546. Exports a Geometry Object to an SVG file in negative.
  4547. :param filename: Path to the SVG file to save to.
  4548. :param: use_thread: If True use threads
  4549. :type: Bool
  4550. :return:
  4551. """
  4552. self.report_usage("export_svg_black()")
  4553. if filename is None:
  4554. filename = self.defaults["global_last_save_folder"]
  4555. self.log.debug("export_svg() black")
  4556. try:
  4557. obj = self.collection.get_by_name(str(obj_name))
  4558. except:
  4559. # TODO: The return behavior has not been established... should raise exception?
  4560. return "Could not retrieve object: %s" % obj_name
  4561. try:
  4562. box = self.collection.get_by_name(str(box_name))
  4563. except:
  4564. # TODO: The return behavior has not been established... should raise exception?
  4565. return "Could not retrieve object: %s" % box_name
  4566. if box is None:
  4567. self.inform.emit("[WARNING_NOTCL]No object Box. Using instead %s" % obj)
  4568. box = obj
  4569. def make_black_film():
  4570. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4571. self.progress.emit(40)
  4572. # Change the attributes of the exported SVG
  4573. # We don't need stroke-width
  4574. # We set opacity to maximum
  4575. # We set the colour to WHITE
  4576. root = ET.fromstring(exported_svg)
  4577. for child in root:
  4578. child.set('fill', '#000000')
  4579. child.set('opacity', '1.0')
  4580. child.set('stroke', '#000000')
  4581. exported_svg = ET.tostring(root)
  4582. # Determine bounding area for svg export
  4583. bounds = box.bounds()
  4584. size = box.size()
  4585. # This contain the measure units
  4586. uom = obj.units.lower()
  4587. # Define a boundary around SVG of about 1.0mm (~39mils)
  4588. if uom in "mm":
  4589. boundary = 1.0
  4590. else:
  4591. boundary = 0.0393701
  4592. self.progress.emit(80)
  4593. # Convert everything to strings for use in the xml doc
  4594. svgwidth = str(size[0] + (2 * boundary))
  4595. svgheight = str(size[1] + (2 * boundary))
  4596. minx = str(bounds[0] - boundary)
  4597. miny = str(bounds[1] + boundary + size[1])
  4598. self.log.debug(minx)
  4599. self.log.debug(miny)
  4600. # Add a SVG Header and footer to the svg output from shapely
  4601. # The transform flips the Y Axis so that everything renders
  4602. # properly within svg apps such as inkscape
  4603. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4604. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4605. svg_header += 'width="' + svgwidth + uom + '" '
  4606. svg_header += 'height="' + svgheight + uom + '" '
  4607. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4608. svg_header += '>'
  4609. svg_header += '<g transform="scale(1,-1)">'
  4610. svg_footer = '</g> </svg>'
  4611. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  4612. self.progress.emit(90)
  4613. # Parse the xml through a xml parser just to add line feeds
  4614. # and to make it look more pretty for the output
  4615. doc = parse_xml_string(svg_elem)
  4616. with open(filename, 'w') as fp:
  4617. fp.write(doc.toprettyxml())
  4618. self.progress.emit(100)
  4619. self.file_saved.emit("SVG", filename)
  4620. self.inform.emit("[success] SVG file exported to " + filename)
  4621. if use_thread is True:
  4622. proc = self.proc_container.new("Generating Film ... Please wait.")
  4623. def job_thread_film(app_obj):
  4624. try:
  4625. make_black_film()
  4626. except Exception as e:
  4627. proc.done()
  4628. return
  4629. proc.done()
  4630. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4631. else:
  4632. make_black_film()
  4633. def export_excellon(self, obj_name, filename, altium_format=None, use_thread=True):
  4634. """
  4635. Exports a Geometry Object to an Excellon file.
  4636. :param filename: Path to the Excellon file to save to.
  4637. :return:
  4638. """
  4639. self.report_usage("export_excellon()")
  4640. if filename is None:
  4641. filename = self.defaults["global_last_save_folder"]
  4642. self.log.debug("export_excellon()")
  4643. format_exc = ';FILE_FORMAT=2:4\n'
  4644. units = ''
  4645. try:
  4646. obj = self.collection.get_by_name(str(obj_name))
  4647. except:
  4648. # TODO: The return behavior has not been established... should raise exception?
  4649. return "Could not retrieve object: %s" % obj_name
  4650. # updated units
  4651. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4652. if units == 'IN' or units == 'INCH':
  4653. units = 'INCH'
  4654. elif units == 'MM' or units == 'METRIC':
  4655. units ='METRIC'
  4656. def make_excellon():
  4657. try:
  4658. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4659. header = 'M48\n'
  4660. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4661. (str(self.app.version), str(self.app.version_date))
  4662. header += ';Filename: %s' % str(obj_name) + '\n'
  4663. header += ';Created on : %s' % time_str + '\n'
  4664. if altium_format == None:
  4665. has_slots, excellon_code = obj.export_excellon()
  4666. header += units + '\n'
  4667. for tool in obj.tools:
  4668. if units == 'METRIC':
  4669. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.2f' % float(obj.tools[tool]['C']) + '\n'
  4670. else:
  4671. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  4672. else:
  4673. has_slots, excellon_code = obj.export_excellon_altium()
  4674. header += 'INCH,LZ\n'
  4675. header += format_exc
  4676. for tool in obj.tools:
  4677. if units == 'METRIC':
  4678. header += 'T' + str(tool) + 'F00S00' + 'C' + \
  4679. '%.4f' % (float(obj.tools[tool]['C']) / 25.4) + '\n'
  4680. else:
  4681. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  4682. header += '%\n'
  4683. footer = 'M30\n'
  4684. exported_excellon = header
  4685. exported_excellon += excellon_code
  4686. exported_excellon += footer
  4687. with open(filename, 'w') as fp:
  4688. fp.write(exported_excellon)
  4689. self.file_saved.emit("Excellon", filename)
  4690. self.inform.emit("[success] Excellon file exported to " + filename)
  4691. except:
  4692. return 'fail'
  4693. if use_thread is True:
  4694. with self.proc_container.new("Exporting Excellon") as proc:
  4695. def job_thread_exc(app_obj):
  4696. ret = make_excellon()
  4697. if ret == 'fail':
  4698. self.inform.emit('[ERROR_NOTCL] Could not export Excellon file.')
  4699. return
  4700. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4701. else:
  4702. ret = make_excellon()
  4703. if ret == 'fail':
  4704. self.inform.emit('[ERROR_NOTCL] Could not export Excellon file.')
  4705. return
  4706. def export_dxf(self, obj_name, filename, use_thread=True):
  4707. """
  4708. Exports a Geometry Object to an DXF file.
  4709. :param filename: Path to the DXF file to save to.
  4710. :return:
  4711. """
  4712. self.report_usage("export_dxf()")
  4713. if filename is None:
  4714. filename = self.defaults["global_last_save_folder"]
  4715. self.log.debug("export_dxf()")
  4716. format_exc = ''
  4717. units = ''
  4718. try:
  4719. obj = self.collection.get_by_name(str(obj_name))
  4720. except:
  4721. # TODO: The return behavior has not been established... should raise exception?
  4722. return "Could not retrieve object: %s" % obj_name
  4723. # updated units
  4724. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4725. if units == 'IN' or units == 'INCH':
  4726. units = 'INCH'
  4727. elif units == 'MM' or units == 'METIRC':
  4728. units ='METRIC'
  4729. def make_dxf():
  4730. try:
  4731. dxf_code = obj.export_dxf()
  4732. dxf_code.saveas(filename)
  4733. self.file_saved.emit("DXF", filename)
  4734. self.inform.emit("[success] DXF file exported to " + filename)
  4735. except:
  4736. return 'fail'
  4737. if use_thread is True:
  4738. with self.proc_container.new("Exporting DXF") as proc:
  4739. def job_thread_exc(app_obj):
  4740. ret = make_dxf()
  4741. if ret == 'fail':
  4742. self.inform.emit('[[WARNING_NOTCL]] Could not export DXF file.')
  4743. return
  4744. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4745. else:
  4746. ret = make_dxf()
  4747. if ret == 'fail':
  4748. self.inform.emit('[[WARNING_NOTCL]] Could not export DXF file.')
  4749. return
  4750. def import_svg(self, filename, geo_type='geometry', outname=None):
  4751. """
  4752. Adds a new Geometry Object to the projects and populates
  4753. it with shapes extracted from the SVG file.
  4754. :param filename: Path to the SVG file.
  4755. :param outname:
  4756. :return:
  4757. """
  4758. self.report_usage("import_svg()")
  4759. obj_type = ""
  4760. if geo_type is None or geo_type == "geometry":
  4761. obj_type = "geometry"
  4762. elif geo_type == "gerber":
  4763. obj_type = geo_type
  4764. else:
  4765. self.inform.emit("[ERROR_NOTCL] Not supported type was choosed as parameter. "
  4766. "Only Geometry and Gerber are supported")
  4767. return
  4768. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4769. def obj_init(geo_obj, app_obj):
  4770. geo_obj.import_svg(filename, obj_type, units=units)
  4771. geo_obj.multigeo = False
  4772. with self.proc_container.new("Importing SVG") as proc:
  4773. # Object name
  4774. name = outname or filename.split('/')[-1].split('\\')[-1]
  4775. self.new_object(obj_type, name, obj_init, autoselected=False)
  4776. self.progress.emit(20)
  4777. # Register recent file
  4778. self.file_opened.emit("svg", filename)
  4779. # GUI feedback
  4780. self.inform.emit("[success] Opened: " + filename)
  4781. self.progress.emit(100)
  4782. def import_dxf(self, filename, geo_type='geometry', outname=None):
  4783. """
  4784. Adds a new Geometry Object to the projects and populates
  4785. it with shapes extracted from the DXF file.
  4786. :param filename: Path to the DXF file.
  4787. :param outname:
  4788. :type putname: str
  4789. :return:
  4790. """
  4791. self.report_usage("import_dxf()")
  4792. obj_type = ""
  4793. if geo_type is None or geo_type == "geometry":
  4794. obj_type = "geometry"
  4795. elif geo_type == "gerber":
  4796. obj_type = geo_type
  4797. else:
  4798. self.inform.emit("[ERROR_NOTCL] Not supported type was choosed as parameter. "
  4799. "Only Geometry and Gerber are supported")
  4800. return
  4801. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4802. def obj_init(geo_obj, app_obj):
  4803. geo_obj.import_dxf(filename, obj_type, units=units)
  4804. geo_obj.multigeo = False
  4805. with self.proc_container.new("Importing DXF") as proc:
  4806. # Object name
  4807. name = outname or filename.split('/')[-1].split('\\')[-1]
  4808. self.new_object(obj_type, name, obj_init, autoselected=False)
  4809. self.progress.emit(20)
  4810. # Register recent file
  4811. self.file_opened.emit("dxf", filename)
  4812. # GUI feedback
  4813. self.inform.emit("[success] Opened: " + filename)
  4814. self.progress.emit(100)
  4815. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  4816. """
  4817. Adds a new Geometry Object to the projects and populates
  4818. it with shapes extracted from the SVG file.
  4819. :param filename: Path to the SVG file.
  4820. :param outname:
  4821. :return:
  4822. """
  4823. self.report_usage("import_image()")
  4824. obj_type = ""
  4825. if type is None or type == "geometry":
  4826. obj_type = "geometry"
  4827. elif type == "gerber":
  4828. obj_type = type
  4829. else:
  4830. self.inform.emit("[ERROR_NOTCL] Not supported type was picked as parameter. "
  4831. "Only Geometry and Gerber are supported")
  4832. return
  4833. def obj_init(geo_obj, app_obj):
  4834. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  4835. geo_obj.multigeo = False
  4836. with self.proc_container.new("Importing Image") as proc:
  4837. # Object name
  4838. name = outname or filename.split('/')[-1].split('\\')[-1]
  4839. units = self.general_options_form.general_app_group.units_radio.get_value()
  4840. self.new_object(obj_type, name, obj_init)
  4841. self.progress.emit(20)
  4842. # Register recent file
  4843. self.file_opened.emit("image", filename)
  4844. # GUI feedback
  4845. self.inform.emit("[success] Opened: " + filename)
  4846. self.progress.emit(100)
  4847. def open_gerber(self, filename, follow=False, outname=None):
  4848. """
  4849. Opens a Gerber file, parses it and creates a new object for
  4850. it in the program. Thread-safe.
  4851. :param outname: Name of the resulting object. None causes the
  4852. name to be that of the file.
  4853. :param filename: Gerber file filename
  4854. :type filename: str
  4855. :param follow: If true, the parser will not create polygons, just lines
  4856. following the gerber path.
  4857. :type follow: bool
  4858. :return: None
  4859. """
  4860. # How the object should be initialized
  4861. def obj_init(gerber_obj, app_obj):
  4862. assert isinstance(gerber_obj, FlatCAMGerber), \
  4863. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  4864. # Opening the file happens here
  4865. self.progress.emit(30)
  4866. try:
  4867. gerber_obj.parse_file(filename, follow=follow)
  4868. except IOError:
  4869. app_obj.inform.emit("[ERROR_NOTCL] Failed to open file: " + filename)
  4870. app_obj.progress.emit(0)
  4871. self.inform.emit('[ERROR_NOTCL] Failed to open file: ' + filename)
  4872. return "fail"
  4873. except ParseError as err:
  4874. app_obj.inform.emit("[ERROR_NOTCL] Failed to parse file: " + filename + ". " + str(err))
  4875. app_obj.progress.emit(0)
  4876. self.log.error(str(err))
  4877. return "fail"
  4878. except:
  4879. msg = "[ERROR] An internal error has ocurred. See shell.\n"
  4880. msg += traceback.format_exc()
  4881. app_obj.inform.emit(msg)
  4882. return "fail"
  4883. if gerber_obj.is_empty():
  4884. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  4885. # self.collection.set_active(gerber_obj.options["name"])
  4886. # self.collection.delete_active()
  4887. self.inform.emit("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation.")
  4888. return "fail"
  4889. # Further parsing
  4890. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  4891. if follow is False:
  4892. App.log.debug("open_gerber()")
  4893. else:
  4894. App.log.debug("open_gerber() with 'follow' attribute")
  4895. with self.proc_container.new("Opening Gerber") as proc:
  4896. self.progress.emit(10)
  4897. # Object name
  4898. name = outname or filename.split('/')[-1].split('\\')[-1]
  4899. ### Object creation ###
  4900. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  4901. if ret == 'fail':
  4902. self.inform.emit('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.')
  4903. return
  4904. # Register recent file
  4905. self.file_opened.emit("gerber", filename)
  4906. self.progress.emit(100)
  4907. # GUI feedback
  4908. self.inform.emit("[success] Opened: " + filename)
  4909. def open_excellon(self, filename, outname=None):
  4910. """
  4911. Opens an Excellon file, parses it and creates a new object for
  4912. it in the program. Thread-safe.
  4913. :param outname: Name of the resulting object. None causes the
  4914. name to be that of the file.
  4915. :param filename: Excellon file filename
  4916. :type filename: str
  4917. :return: None
  4918. """
  4919. App.log.debug("open_excellon()")
  4920. #self.progress.emit(10)
  4921. # How the object should be initialized
  4922. def obj_init(excellon_obj, app_obj):
  4923. # self.progress.emit(20)
  4924. try:
  4925. ret = excellon_obj.parse_file(filename)
  4926. if ret == "fail":
  4927. log.debug("Excellon parsing failed.")
  4928. self.inform.emit("[ERROR_NOTCL] This is not Excellon file.")
  4929. return "fail"
  4930. except IOError:
  4931. app_obj.inform.emit("[ERROR_NOTCL] Cannot open file: " + filename)
  4932. log.debug("Could not open Excellon object.")
  4933. self.progress.emit(0) # TODO: self and app_bjj mixed
  4934. return "fail"
  4935. except:
  4936. msg = "[ERROR_NOTCL] An internal error has occurred. See shell.\n"
  4937. msg += traceback.format_exc()
  4938. app_obj.inform.emit(msg)
  4939. return "fail"
  4940. ret = excellon_obj.create_geometry()
  4941. if ret == 'fail':
  4942. log.debug("Could not create geometry for Excellon object.")
  4943. return "fail"
  4944. if excellon_obj.is_empty():
  4945. app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  4946. return "fail"
  4947. with self.proc_container.new("Opening Excellon."):
  4948. # Object name
  4949. name = outname or filename.split('/')[-1].split('\\')[-1]
  4950. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  4951. if ret == 'fail':
  4952. self.inform.emit('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.')
  4953. return
  4954. # Register recent file
  4955. self.file_opened.emit("excellon", filename)
  4956. # GUI feedback
  4957. self.inform.emit("[success] Opened: " + filename)
  4958. # self.progress.emit(100)
  4959. def open_gcode(self, filename, outname=None):
  4960. """
  4961. Opens a G-gcode file, parses it and creates a new object for
  4962. it in the program. Thread-safe.
  4963. :param outname: Name of the resulting object. None causes the
  4964. name to be that of the file.
  4965. :param filename: G-code file filename
  4966. :type filename: str
  4967. :return: None
  4968. """
  4969. App.log.debug("open_gcode()")
  4970. # How the object should be initialized
  4971. def obj_init(job_obj, app_obj_):
  4972. """
  4973. :type app_obj_: App
  4974. """
  4975. assert isinstance(app_obj_, App), \
  4976. "Initializer expected App, got %s" % type(app_obj_)
  4977. self.progress.emit(10)
  4978. try:
  4979. f = open(filename)
  4980. gcode = f.read()
  4981. f.close()
  4982. except IOError:
  4983. app_obj_.inform.emit("[ERROR_NOTCL] Failed to open " + filename)
  4984. self.progress.emit(0)
  4985. return "fail"
  4986. job_obj.gcode = gcode
  4987. self.progress.emit(20)
  4988. ret = job_obj.gcode_parse()
  4989. if ret == "fail":
  4990. self.inform.emit("[ERROR_NOTCL] This is not GCODE")
  4991. return "fail"
  4992. self.progress.emit(60)
  4993. job_obj.create_geometry()
  4994. with self.proc_container.new("Opening G-Code."):
  4995. # Object name
  4996. name = outname or filename.split('/')[-1].split('\\')[-1]
  4997. # New object creation and file processing
  4998. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  4999. if ret == 'fail':
  5000. self.inform.emit("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  5001. "Attempting to create a FlatCAM CNCJob Object from "
  5002. "G-Code file failed during processing")
  5003. return "fail"
  5004. # Register recent file
  5005. self.file_opened.emit("cncjob", filename)
  5006. # GUI feedback
  5007. self.inform.emit("[success] Opened: " + filename)
  5008. self.progress.emit(100)
  5009. def open_project(self, filename, run_from_arg=None):
  5010. """
  5011. Loads a project from the specified file.
  5012. 1) Loads and parses file
  5013. 2) Registers the file as recently opened.
  5014. 3) Calls on_file_new()
  5015. 4) Updates options
  5016. 5) Calls new_object() with the object's from_dict() as init method.
  5017. 6) Calls plot_all()
  5018. :param filename: Name of the file from which to load.
  5019. :type filename: str
  5020. :return: None
  5021. """
  5022. App.log.debug("Opening project: " + filename)
  5023. # Open and parse
  5024. try:
  5025. f = open(filename, 'r')
  5026. except IOError:
  5027. App.log.error("Failed to open project file: %s" % filename)
  5028. self.inform.emit("[ERROR_NOTCL] Failed to open project file: %s" % filename)
  5029. return
  5030. try:
  5031. d = json.load(f, object_hook=dict2obj)
  5032. except:
  5033. App.log.error("Failed to parse project file: %s" % filename)
  5034. self.inform.emit("[ERROR_NOTCL] Failed to parse project file: %s" % filename)
  5035. f.close()
  5036. return
  5037. self.file_opened.emit("project", filename)
  5038. # Clear the current project
  5039. ## NOT THREAD SAFE ##
  5040. if run_from_arg is True:
  5041. pass
  5042. else:
  5043. self.on_file_new()
  5044. #Project options
  5045. self.options.update(d['options'])
  5046. self.project_filename = filename
  5047. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  5048. self.set_screen_units(self.options["units"])
  5049. # Re create objects
  5050. App.log.debug("Re-creating objects...")
  5051. for obj in d['objs']:
  5052. def obj_init(obj_inst, app_inst):
  5053. obj_inst.from_dict(obj)
  5054. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  5055. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  5056. # self.plot_all()
  5057. self.inform.emit("[success] Project loaded from: " + filename)
  5058. App.log.debug("Project loaded")
  5059. def propagate_defaults(self, silent=False):
  5060. """
  5061. This method is used to set default values in classes. It's
  5062. an alternative to project options but allows the use
  5063. of values invisible to the user.
  5064. :return: None
  5065. """
  5066. if silent is False:
  5067. self.log.debug("propagate_defaults()")
  5068. # Which objects to update the given parameters.
  5069. routes = {
  5070. "global_zdownrate": CNCjob,
  5071. "excellon_zeros": Excellon,
  5072. "excellon_format_upper_in": Excellon,
  5073. "excellon_format_lower_in": Excellon,
  5074. "excellon_format_upper_mm": Excellon,
  5075. "excellon_format_lower_mm": Excellon,
  5076. "excellon_units": Excellon,
  5077. "gerber_use_buffer_for_union": Gerber,
  5078. "geometry_multidepth": Geometry
  5079. }
  5080. for param in routes:
  5081. if param in routes[param].defaults:
  5082. try:
  5083. routes[param].defaults[param] = self.defaults[param]
  5084. if silent is False:
  5085. self.log.debug(" " + param + " OK")
  5086. except KeyError:
  5087. if silent is False:
  5088. self.log.debug(" ERROR: " + param + " not in defaults.")
  5089. else:
  5090. # Try extracting the name:
  5091. # classname_param here is param in the object
  5092. if param.find(routes[param].__name__.lower() + "_") == 0:
  5093. p = param[len(routes[param].__name__) + 1:]
  5094. if p in routes[param].defaults:
  5095. routes[param].defaults[p] = self.defaults[param]
  5096. if silent is False:
  5097. self.log.debug(" " + param + " OK!")
  5098. def restore_main_win_geom(self):
  5099. try:
  5100. self.ui.setGeometry(self.defaults["global_def_win_x"],
  5101. self.defaults["global_def_win_y"],
  5102. self.defaults["global_def_win_w"],
  5103. self.defaults["global_def_win_h"])
  5104. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  5105. except KeyError:
  5106. pass
  5107. def plot_all(self, zoom=True):
  5108. """
  5109. Re-generates all plots from all objects.
  5110. :return: None
  5111. """
  5112. self.log.debug("Plot_all()")
  5113. for obj in self.collection.get_list():
  5114. def worker_task(obj):
  5115. with self.proc_container.new("Plotting"):
  5116. obj.plot()
  5117. if zoom:
  5118. self.object_plotted.emit(obj)
  5119. # Send to worker
  5120. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  5121. # self.progress.emit(10)
  5122. #
  5123. # def worker_task(app_obj):
  5124. # print "worker task"
  5125. # percentage = 0.1
  5126. # try:
  5127. # delta = 0.9 / len(self.collection.get_list())
  5128. # except ZeroDivisionError:
  5129. # self.progress.emit(0)
  5130. # return
  5131. # for obj in self.collection.get_list():
  5132. # with self.proc_container.new("Plotting"):
  5133. # obj.plot()
  5134. # app_obj.object_plotted.emit(obj)
  5135. #
  5136. # percentage += delta
  5137. # self.progress.emit(int(percentage*100))
  5138. #
  5139. # self.progress.emit(0)
  5140. # self.plots_updated.emit()
  5141. #
  5142. # # Send to worker
  5143. # #self.worker.add_task(worker_task, [self])
  5144. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5145. def register_folder(self, filename):
  5146. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5147. def register_save_folder(self, filename):
  5148. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5149. def set_progress_bar(self, percentage, text=""):
  5150. self.ui.progress_bar.setValue(int(percentage))
  5151. def setup_shell(self):
  5152. """
  5153. Creates shell functions. Runs once at startup.
  5154. :return: None
  5155. """
  5156. self.log.debug("setup_shell()")
  5157. def shelp(p=None):
  5158. if not p:
  5159. return "Available commands:\n" + \
  5160. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  5161. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  5162. if p not in commands:
  5163. return "Unknown command: %s" % p
  5164. return commands[p]["help"]
  5165. # --- Migrated to new architecture ---
  5166. # def options(name):
  5167. # ops = self.collection.get_by_name(str(name)).options
  5168. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  5169. def h(*args):
  5170. """
  5171. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  5172. and standalone parameters into list.
  5173. """
  5174. kwa = {}
  5175. a = []
  5176. n = len(args)
  5177. name = None
  5178. for i in range(n):
  5179. match = re.search(r'^-([a-zA-Z].*)', args[i])
  5180. if match:
  5181. assert name is None
  5182. name = match.group(1)
  5183. continue
  5184. if name is None:
  5185. a.append(args[i])
  5186. else:
  5187. kwa[name] = args[i]
  5188. name = None
  5189. return a, kwa
  5190. @contextmanager
  5191. def wait_signal(signal, timeout=10000):
  5192. """
  5193. Block loop until signal emitted, timeout (ms) elapses
  5194. or unhandled exception happens in a thread.
  5195. :param signal: Signal to wait for.
  5196. """
  5197. loop = QtCore.QEventLoop()
  5198. # Normal termination
  5199. signal.connect(loop.quit)
  5200. # Termination by exception in thread
  5201. self.thread_exception.connect(loop.quit)
  5202. status = {'timed_out': False}
  5203. def report_quit():
  5204. status['timed_out'] = True
  5205. loop.quit()
  5206. yield
  5207. # Temporarily change how exceptions are managed.
  5208. oeh = sys.excepthook
  5209. ex = []
  5210. def except_hook(type_, value, traceback_):
  5211. ex.append(value)
  5212. oeh(type_, value, traceback_)
  5213. sys.excepthook = except_hook
  5214. # Terminate on timeout
  5215. if timeout is not None:
  5216. QtCore.QTimer.singleShot(timeout, report_quit)
  5217. #### Block ####
  5218. loop.exec_()
  5219. # Restore exception management
  5220. sys.excepthook = oeh
  5221. if ex:
  5222. self.raiseTclError(str(ex[0]))
  5223. if status['timed_out']:
  5224. raise Exception('Timed out!')
  5225. def make_docs():
  5226. output = ''
  5227. import collections
  5228. od = collections.OrderedDict(sorted(commands.items()))
  5229. for cmd_, val in od.items():
  5230. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  5231. t = val['help']
  5232. usage_i = t.find('>')
  5233. if usage_i < 0:
  5234. expl = t
  5235. output += expl + '\n\n'
  5236. continue
  5237. expl = t[:usage_i - 1]
  5238. output += expl + '\n\n'
  5239. end_usage_i = t[usage_i:].find('\n')
  5240. if end_usage_i < 0:
  5241. end_usage_i = len(t[usage_i:])
  5242. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  5243. else:
  5244. extras = t[usage_i+end_usage_i+1:]
  5245. parts = [s.strip() for s in extras.split('\n')]
  5246. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  5247. for p in parts:
  5248. output += ' ' + p + '\n\n'
  5249. return output
  5250. '''
  5251. Howto implement TCL shell commands:
  5252. All parameters passed to command should be possible to set as None and test it afterwards.
  5253. This is because we need to see error caused in tcl,
  5254. if None value as default parameter is not allowed TCL will return empty error.
  5255. Use:
  5256. def mycommand(name=None,...):
  5257. Test it like this:
  5258. if name is None:
  5259. self.raise_tcl_error('Argument name is missing.')
  5260. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  5261. otherwise we will miss it and processing will silently continue.
  5262. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  5263. which is catched in exec_command and displayed in TCL shell console with red background.
  5264. Error in console is displayed with TCL trace.
  5265. This behavior works only within main thread,
  5266. errors with promissed tasks can be catched and detected only with log.
  5267. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  5268. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  5269. '''
  5270. commands = {
  5271. 'help': {
  5272. 'fcn': shelp,
  5273. 'help': "Shows list of commands."
  5274. },
  5275. }
  5276. # Import/overwrite tcl commands as objects of TclCommand descendants
  5277. # This modifies the variable 'commands'.
  5278. tclCommands.register_all_commands(self, commands)
  5279. # Add commands to the tcl interpreter
  5280. for cmd in commands:
  5281. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  5282. # Make the tcl puts function return instead of print to stdout
  5283. self.tcl.eval('''
  5284. rename puts original_puts
  5285. proc puts {args} {
  5286. if {[llength $args] == 1} {
  5287. return "[lindex $args 0]"
  5288. } else {
  5289. eval original_puts $args
  5290. }
  5291. }
  5292. ''')
  5293. def setup_recent_items(self):
  5294. # TODO: Move this to constructor
  5295. icons = {
  5296. "gerber": "share/flatcam_icon16.png",
  5297. "excellon": "share/drill16.png",
  5298. "cncjob": "share/cnc16.png",
  5299. "project": "share/project16.png",
  5300. "svg": "share/geometry16.png",
  5301. "dxf": "share/dxf16.png",
  5302. "image": "share/image16.png"
  5303. }
  5304. openers = {
  5305. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  5306. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  5307. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  5308. 'project': self.open_project,
  5309. 'svg': self.import_svg,
  5310. 'dxf': self.import_dxf,
  5311. 'image': self.import_image
  5312. }
  5313. # Open file
  5314. try:
  5315. f = open(self.data_path + '/recent.json')
  5316. except IOError:
  5317. App.log.error("Failed to load recent item list.")
  5318. self.inform.emit("[ERROR_NOTCL] Failed to load recent item list.")
  5319. return
  5320. try:
  5321. self.recent = json.load(f)
  5322. except json.scanner.JSONDecodeError:
  5323. App.log.error("Failed to parse recent item list.")
  5324. self.inform.emit("[ERROR_NOTCL] Failed to parse recent item list.")
  5325. f.close()
  5326. return
  5327. f.close()
  5328. # Closure needed to create callbacks in a loop.
  5329. # Otherwise late binding occurs.
  5330. def make_callback(func, fname):
  5331. def opener():
  5332. func(fname)
  5333. return opener
  5334. def reset_recent():
  5335. # Reset menu
  5336. self.ui.recent.clear()
  5337. self.recent = []
  5338. try:
  5339. f = open(self.data_path + '/recent.json', 'w')
  5340. except IOError:
  5341. App.log.error("Failed to open recent items file for writing.")
  5342. return
  5343. json.dump(self.recent, f)
  5344. # Reset menu
  5345. self.ui.recent.clear()
  5346. # Create menu items
  5347. for recent in self.recent:
  5348. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5349. try:
  5350. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5351. # Attach callback
  5352. o = make_callback(openers[recent["kind"]], recent['filename'])
  5353. action.triggered.connect(o)
  5354. self.ui.recent.addAction(action)
  5355. except KeyError:
  5356. App.log.error("Unsupported file type: %s" % recent["kind"])
  5357. # Last action in Recent Files menu is one that Clear the content
  5358. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  5359. clear_action.triggered.connect(reset_recent)
  5360. self.ui.recent.addSeparator()
  5361. self.ui.recent.addAction(clear_action)
  5362. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  5363. # self.ui.menufilerecent.set_submenu(recent_menu)
  5364. # recent_menu.show_all()
  5365. # self.ui.recent.show()
  5366. self.log.debug("Recent items list has been populated.")
  5367. def setup_component_editor(self):
  5368. # label = QtWidgets.QLabel("Choose an item from Project")
  5369. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  5370. sel_title = QtWidgets.QTextEdit(
  5371. '<b>Shortcut Key List</b>')
  5372. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5373. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5374. # font = self.sel_title.font()
  5375. # font.setPointSize(12)
  5376. # self.sel_title.setFont(font)
  5377. selected_text = '''
  5378. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  5379. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5380. The normal flow when working in FlatCAM is the following:</span></p>
  5381. <ol>
  5382. <li><span style="font-size:10px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  5383. <br />
  5384. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  5385. &nbsp;</li>
  5386. <li><span style="font-size:10px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  5387. <br />
  5388. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  5389. <br />
  5390. You can change the parameters in this screen and the flow direction is like this:<br />
  5391. <br />
  5392. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  5393. </ol>
  5394. <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  5395. '''
  5396. sel_title.setText(selected_text)
  5397. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5398. self.ui.selected_scroll_area.setWidget(sel_title)
  5399. # tool_title = QtWidgets.QTextEdit(
  5400. # '<b>Shortcut Key List</b>')
  5401. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5402. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5403. # # font = self.sel_title.font()
  5404. # # font.setPointSize(12)
  5405. # # self.sel_title.setFont(font)
  5406. #
  5407. # tool_text = '''
  5408. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  5409. #
  5410. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5411. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  5412. #
  5413. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  5414. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  5415. #
  5416. # <ol>
  5417. # </ol>
  5418. #
  5419. # <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: &#39;`&#39; (key left to 1).</span></p>
  5420. #
  5421. # '''
  5422. #
  5423. # tool_title.setText(tool_text)
  5424. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5425. #
  5426. # self.ui.tool_scroll_area.setWidget(tool_title)
  5427. def setup_obj_classes(self):
  5428. """
  5429. Sets up application specifics on the FlatCAMObj class.
  5430. :return: None
  5431. """
  5432. FlatCAMObj.app = self
  5433. ObjectCollection.app = self
  5434. FCProcess.app = self
  5435. FCProcessContainer.app = self
  5436. def version_check(self):
  5437. """
  5438. Checks for the latest version of the program. Alerts the
  5439. user if theirs is outdated. This method is meant to be run
  5440. in a separate thread.
  5441. :return: None
  5442. """
  5443. self.log.debug("version_check()")
  5444. if self.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  5445. full_url = App.version_url + \
  5446. "?s=" + str(self.defaults['global_serial']) + \
  5447. "&v=" + str(self.version) + \
  5448. "&os=" + str(self.os) + \
  5449. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  5450. else:
  5451. # no_stats dict; just so it won't break things on website
  5452. no_ststs_dict = {}
  5453. no_ststs_dict["global_ststs"] = {}
  5454. full_url = App.version_url + \
  5455. "?s=" + str(self.defaults['global_serial']) + \
  5456. "&v=" + str(self.version) + \
  5457. "&os=" + str(self.os) + \
  5458. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  5459. App.log.debug("Checking for updates @ %s" % full_url)
  5460. ### Get the data
  5461. try:
  5462. f = urllib.request.urlopen(full_url)
  5463. except:
  5464. # App.log.warning("Failed checking for latest version. Could not connect.")
  5465. self.log.warning("Failed checking for latest version. Could not connect.")
  5466. self.inform.emit("[WARNING_NOTCL] Failed checking for latest version. Could not connect.")
  5467. return
  5468. try:
  5469. data = json.load(f)
  5470. except Exception as e:
  5471. App.log.error("Could not parse information about latest version.")
  5472. self.inform.emit("[ERROR_NOTCL] Could not parse information about latest version.")
  5473. App.log.debug("json.load(): %s" % str(e))
  5474. f.close()
  5475. return
  5476. f.close()
  5477. ### Latest version?
  5478. if self.version >= data["version"]:
  5479. App.log.debug("FlatCAM is up to date!")
  5480. self.inform.emit("[success] FlatCAM is up to date!")
  5481. return
  5482. App.log.debug("Newer version available.")
  5483. self.message.emit(
  5484. "Newer Version Available",
  5485. str("There is a newer version of FlatCAM " +
  5486. "available for download:<br><br>" +
  5487. "<B>" + data["name"] + "</b><br>" +
  5488. data["message"].replace("\n", "<br>")),
  5489. "info"
  5490. )
  5491. def on_zoom_fit(self, event):
  5492. """
  5493. Callback for zoom-out request. This can be either from the corresponding
  5494. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  5495. with axes limits from the geometry bounds of all objects.
  5496. :param event: Ignored.
  5497. :return: None
  5498. """
  5499. self.plotcanvas.fit_view()
  5500. def disable_all_plots(self):
  5501. self.report_usage("disable_all_plots()")
  5502. self.disable_plots(self.collection.get_list())
  5503. self.inform.emit("[success]All plots disabled.")
  5504. def disable_other_plots(self):
  5505. self.report_usage("disable_other_plots()")
  5506. self.disable_plots(self.collection.get_non_selected())
  5507. self.inform.emit("[success]All non selected plots disabled.")
  5508. def enable_all_plots(self):
  5509. self.report_usage("enable_all_plots()")
  5510. self.enable_plots(self.collection.get_list())
  5511. self.inform.emit("[success]All plots enabled.")
  5512. # TODO: FIX THIS
  5513. '''
  5514. By default this is not threaded
  5515. If threaded the app give warnings like this:
  5516. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5517. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5518. '''
  5519. def enable_plots(self, objects, threaded=False):
  5520. if threaded is True:
  5521. def worker_task(app_obj):
  5522. percentage = 0.1
  5523. try:
  5524. delta = 0.9 / len(objects)
  5525. except ZeroDivisionError:
  5526. self.progress.emit(0)
  5527. return
  5528. for obj in objects:
  5529. obj.options['plot'] = True
  5530. percentage += delta
  5531. self.progress.emit(int(percentage*100))
  5532. self.progress.emit(0)
  5533. self.plots_updated.emit()
  5534. self.collection.update_view()
  5535. # Send to worker
  5536. # self.worker.add_task(worker_task, [self])
  5537. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5538. else:
  5539. for obj in objects:
  5540. obj.options['plot'] = True
  5541. self.progress.emit(0)
  5542. self.plots_updated.emit()
  5543. self.collection.update_view()
  5544. # TODO: FIX THIS
  5545. '''
  5546. By default this is not threaded
  5547. If threaded the app give warnings like this:
  5548. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5549. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5550. '''
  5551. def disable_plots(self, objects, threaded=False):
  5552. # TODO: This method is very similar to replot_all. Try to merge.
  5553. """
  5554. Disables plots
  5555. :param objects: list
  5556. Objects to be disabled
  5557. :return:
  5558. """
  5559. if threaded is True:
  5560. self.progress.emit(10)
  5561. def worker_task(app_obj):
  5562. percentage = 0.1
  5563. try:
  5564. delta = 0.9 / len(objects)
  5565. except ZeroDivisionError:
  5566. self.progress.emit(0)
  5567. return
  5568. for obj in objects:
  5569. obj.options['plot'] = False
  5570. percentage += delta
  5571. self.progress.emit(int(percentage*100))
  5572. self.progress.emit(0)
  5573. self.plots_updated.emit()
  5574. self.collection.update_view()
  5575. # Send to worker
  5576. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5577. else:
  5578. for obj in objects:
  5579. obj.options['plot'] = False
  5580. self.plots_updated.emit()
  5581. self.collection.update_view()
  5582. def clear_plots(self):
  5583. objects = self.collection.get_list()
  5584. for obj in objects:
  5585. obj.clear(obj == objects[-1])
  5586. # Clear pool to free memory
  5587. self.clear_pool()
  5588. def generate_cnc_job(self, objects):
  5589. self.report_usage("generate_cnc_job()")
  5590. for obj in objects:
  5591. obj.generatecncjob()
  5592. def save_project(self, filename):
  5593. """
  5594. Saves the current project to the specified file.
  5595. :param filename: Name of the file in which to save.
  5596. :type filename: str
  5597. :return: None
  5598. """
  5599. self.log.debug("save_project()")
  5600. with self.proc_container.new("Saving FlatCAM Project") as proc:
  5601. ## Capture the latest changes
  5602. # Current object
  5603. try:
  5604. self.collection.get_active().read_form()
  5605. except:
  5606. self.log.debug("[WARNING] There was no active object")
  5607. pass
  5608. # Project options
  5609. self.options_read_form()
  5610. # Serialize the whole project
  5611. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  5612. "options": self.options,
  5613. "version": self.version}
  5614. # Open file
  5615. try:
  5616. f = open(filename, 'w')
  5617. except IOError:
  5618. App.log.error("[ERROR] Failed to open file for saving: %s", filename)
  5619. return
  5620. # Write
  5621. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  5622. f.close()
  5623. # verification of the saved project
  5624. # Open and parse
  5625. try:
  5626. saved_f = open(filename, 'r')
  5627. except IOError:
  5628. self.inform.emit("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it." % filename)
  5629. return
  5630. try:
  5631. saved_d = json.load(saved_f, object_hook=dict2obj)
  5632. except:
  5633. self.inform.emit("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it." % filename)
  5634. f.close()
  5635. return
  5636. saved_f.close()
  5637. if 'version' in saved_d:
  5638. self.inform.emit("[success] Project saved to: %s" % filename)
  5639. else:
  5640. self.inform.emit("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it." % filename)
  5641. def on_options_app2project(self):
  5642. """
  5643. Callback for Options->Transfer Options->App=>Project. Copies options
  5644. from application defaults to project defaults.
  5645. :return: None
  5646. """
  5647. self.report_usage("on_options_app2project")
  5648. self.defaults_read_form()
  5649. self.options.update(self.defaults)
  5650. self.options_write_form()
  5651. def on_options_project2app(self):
  5652. """
  5653. Callback for Options->Transfer Options->Project=>App. Copies options
  5654. from project defaults to application defaults.
  5655. :return: None
  5656. """
  5657. self.report_usage("on_options_project2app")
  5658. self.options_read_form()
  5659. self.defaults.update(self.options)
  5660. self.defaults_write_form()
  5661. def on_options_project2object(self):
  5662. """
  5663. Callback for Options->Transfer Options->Project=>Object. Copies options
  5664. from project defaults to the currently selected object.
  5665. :return: None
  5666. """
  5667. self.report_usage("on_options_project2object")
  5668. self.options_read_form()
  5669. obj = self.collection.get_active()
  5670. if obj is None:
  5671. self.inform.emit("WARNING: No object selected.")
  5672. return
  5673. for option in self.options:
  5674. if option.find(obj.kind + "_") == 0:
  5675. oname = option[len(obj.kind) + 1:]
  5676. obj.options[oname] = self.options[option]
  5677. obj.to_form() # Update UI
  5678. def on_options_object2project(self):
  5679. """
  5680. Callback for Options->Transfer Options->Object=>Project. Copies options
  5681. from the currently selected object to project defaults.
  5682. :return: None
  5683. """
  5684. self.report_usage("on_options_object2project")
  5685. obj = self.collection.get_active()
  5686. if obj is None:
  5687. self.inform.emit("WARNING: No object selected.")
  5688. return
  5689. obj.read_form()
  5690. for option in obj.options:
  5691. if option in ['name']: # TODO: Handle this better...
  5692. continue
  5693. self.options[obj.kind + "_" + option] = obj.options[option]
  5694. self.options_write_form()
  5695. def on_options_object2app(self):
  5696. """
  5697. Callback for Options->Transfer Options->Object=>App. Copies options
  5698. from the currently selected object to application defaults.
  5699. :return: None
  5700. """
  5701. self.report_usage("on_options_object2app")
  5702. obj = self.collection.get_active()
  5703. if obj is None:
  5704. self.inform.emit("WARNING: No object selected.")
  5705. return
  5706. obj.read_form()
  5707. for option in obj.options:
  5708. if option in ['name']: # TODO: Handle this better...
  5709. continue
  5710. self.defaults[obj.kind + "_" + option] = obj.options[option]
  5711. self.defaults_write_form()
  5712. def on_options_app2object(self):
  5713. """
  5714. Callback for Options->Transfer Options->App=>Object. Copies options
  5715. from application defaults to the currently selected object.
  5716. :return: None
  5717. """
  5718. self.report_usage("on_options_app2object")
  5719. self.defaults_read_form()
  5720. obj = self.collection.get_active()
  5721. if obj is None:
  5722. self.inform.emit("WARNING: No object selected.")
  5723. return
  5724. for option in self.defaults:
  5725. if option.find(obj.kind + "_") == 0:
  5726. oname = option[len(obj.kind) + 1:]
  5727. obj.options[oname] = self.defaults[option]
  5728. obj.to_form() # Update UI
  5729. # end of file